From 528b12eb7a30ba264ddcb4e33860e403bd133623 Mon Sep 17 00:00:00 2001 From: u3shit Date: Tue, 21 Apr 2020 02:13:06 +0200 Subject: [PATCH 001/959] Fix glClipControl(GL_UPPER_LEFT) handling in opengl3. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_opengl3.cpp | 21 +++++++++++---------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 81cb3bab..18cb9659 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,8 @@ Other Changes: - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) +- Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the + projection matrix top and bottom values. (#3143, #3146) [@u3shit] ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 40e531dd..bf8225d0 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader. // 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader. @@ -243,6 +244,14 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif + // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) + bool clip_origin_lower_left = true; +#if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__) + GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); + if (current_clip_origin == GL_UPPER_LEFT) + clip_origin_lower_left = false; +#endif + // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); @@ -250,6 +259,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, @@ -318,12 +328,6 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); - bool clip_origin_lower_left = true; -#if defined(GL_CLIP_ORIGIN) && !defined(__APPLE__) - GLenum last_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&last_clip_origin); // Support for GL 4.5's glClipControl(GL_UPPER_LEFT) - if (last_clip_origin == GL_UPPER_LEFT) - clip_origin_lower_left = false; -#endif // Setup desired GL state // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) @@ -371,10 +375,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f) { // Apply scissor/clipping rectangle - if (clip_origin_lower_left) - glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y)); - else - glScissor((int)clip_rect.x, (int)clip_rect.y, (int)clip_rect.z, (int)clip_rect.w); // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) + glScissor((int)clip_rect.x, (int)(fb_height - clip_rect.w), (int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y)); // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); From fd6d3155c07fb2292e7ef84f4d53d0fb8eb1196a Mon Sep 17 00:00:00 2001 From: Silent Date: Wed, 22 Apr 2020 10:13:20 +0200 Subject: [PATCH 002/959] Fix wrong comment in ImGuiCond_ (#3139) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 5ac453c4..bdc241fa 100644 --- a/imgui.h +++ b/imgui.h @@ -1265,7 +1265,7 @@ enum ImGuiMouseCursor_ enum ImGuiCond_ { ImGuiCond_Always = 1 << 0, // Set the variable - ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) + ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed) ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) }; From 223297b075a7c2c76f33356a3854e6dd8da2b49b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Apr 2020 16:30:37 +0200 Subject: [PATCH 003/959] Clarified comments about popups input blocking and ImGuiHoveredFlags_AllowWhenBlockedByPopup flag. (#3154) --- imgui.h | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/imgui.h b/imgui.h index bdc241fa..f2b1cd9d 100644 --- a/imgui.h +++ b/imgui.h @@ -591,13 +591,16 @@ namespace ImGui // Popups, Modals // The properties of popups windows are: - // - They block normal mouse hovering detection outside them. (*) + // - They block normal mouse hovering detection outside them. (*1) // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. - // - Their visibility state (~bool) is held internally by imgui instead of being held by the programmer as we are used to with regular Begin() calls. - // User can manipulate the visibility state by calling OpenPopup(). + // Because hovering detection is disabled outside the popup, when clicking outside the click will not be seen by underlying widgets! (*1) + // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as we are used to with regular Begin() calls. + // User can manipulate the visibility state by calling OpenPopup(), CloseCurrentPopup() etc. // - We default to use the right mouse (ImGuiMouseButton_Right=1) for the Popup Context functions. - // (*) You can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup. - // Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time. + // Those three properties are connected: we need to retain popup visibility state in the library because popups may be closed as any time. + // (*1) You can bypass that restriction and detect hovering even when normally blocked by a popup. + // To do this use the ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // This is what BeginPopupContextItem() and BeginPopupContextWindow() are doing already, allowing a right-click to reopen another popups without losing the click. IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! From 5ac5d3674fc79bfb41634df6ce412eb9bc098453 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Apr 2020 15:30:30 +0200 Subject: [PATCH 004/959] Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 1 + imgui.h | 15 ++++++++------- imgui_draw.cpp | 21 +++++++++------------ 4 files changed, 21 insertions(+), 19 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 18cb9659..ad309327 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,6 +36,9 @@ HOW TO UPDATE? Breaking Changes: +- Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please + note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. + Other Changes: - TreeNode: Fixed bug where BeginDragDropSource() failed when the _OpenOnDoubleClick flag is diff --git a/imgui.cpp b/imgui.cpp index 0d4d9780..f900a010 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/04/23 (1.77) - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead. - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value. diff --git a/imgui.h b/imgui.h index f2b1cd9d..d3460d72 100644 --- a/imgui.h +++ b/imgui.h @@ -2150,13 +2150,13 @@ struct ImFontGlyphRangesBuilder // See ImFontAtlas::AddCustomRectXXX functions. struct ImFontAtlasCustomRect { - unsigned int ID; // Input // User ID. Use < 0x110000 to map into a font glyph, >= 0x110000 for other/internal/custom texture data. unsigned short Width, Height; // Input // Desired rectangle dimension unsigned short X, Y; // Output // Packed position in Atlas - float GlyphAdvanceX; // Input // For custom font glyphs only (ID < 0x110000): glyph xadvance - ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID < 0x110000): glyph display offset - ImFont* Font; // Input // For custom font glyphs only (ID < 0x110000): target font - ImFontAtlasCustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } + unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000) + 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() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } bool IsPacked() const { return X != 0xFFFF; } }; @@ -2235,8 +2235,9 @@ struct ImFontAtlas // 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. // Read docs/FONTS.txt for more details about using colorful icons. - IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x110000. Id >= 0x80000000 are reserved for ImGui and ImDrawList - IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x110000 to register a rectangle to map into a specific font. + // 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)); const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } // [Internal] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d0d6a1e7..909949dc 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1543,7 +1543,6 @@ ImFontConfig::ImFontConfig() // The white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 108; const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; -const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000; static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX " @@ -1826,14 +1825,11 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed return font; } -int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) +int ImFontAtlas::AddCustomRectRegular(int width, int height) { - // Breaking change on 2019/11/21 (1.74): ImFontAtlas::AddCustomRectRegular() now requires an ID >= 0x110000 (instead of >= 0x10000) - IM_ASSERT(id >= 0x110000); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); ImFontAtlasCustomRect r; - r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; CustomRects.push_back(r); @@ -1842,13 +1838,16 @@ int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height) int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset) { +#ifdef IMGUI_USE_WCHAR32 + IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX); +#endif IM_ASSERT(font != NULL); IM_ASSERT(width > 0 && width <= 0xFFFF); IM_ASSERT(height > 0 && height <= 0xFFFF); ImFontAtlasCustomRect r; - r.ID = id; r.Width = (unsigned short)width; r.Height = (unsigned short)height; + r.GlyphID = id; r.GlyphAdvanceX = advance_x; r.GlyphOffset = offset; r.Font = font; @@ -1873,7 +1872,6 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou IM_ASSERT(CustomRectIds[0] != -1); ImFontAtlasCustomRect& r = CustomRects[CustomRectIds[0]]; - IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); 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; @@ -2208,9 +2206,9 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->CustomRectIds[0] >= 0) return; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); else - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_ID, 2, 2); + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(2, 2); } void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) @@ -2259,7 +2257,6 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) IM_ASSERT(atlas->CustomRectIds[0] >= 0); IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; - IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); IM_ASSERT(r.IsPacked()); const int w = atlas->TexWidth; @@ -2294,13 +2291,13 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) for (int i = 0; i < atlas->CustomRects.Size; i++) { const ImFontAtlasCustomRect& r = atlas->CustomRects[i]; - if (r.Font == NULL || r.ID >= 0x110000) + if (r.Font == NULL || r.GlyphID == 0) continue; IM_ASSERT(r.Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; atlas->CalcCustomRectUV(&r, &uv0, &uv1); - r.Font->AddGlyph((ImWchar)r.ID, 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); + r.Font->AddGlyph((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); } // Build all fonts lookup tables From d3212482fe6e158db71999ae84de754f908ab8fd Mon Sep 17 00:00:00 2001 From: Matt Haynie Date: Thu, 23 Apr 2020 13:58:45 -0700 Subject: [PATCH 005/959] Fix multiple macro definitions of GLFW_INCLUDE_NONE (#3157) --- examples/imgui_impl_opengl3.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index bf8225d0..c60df73d 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -121,12 +121,16 @@ #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Needs to be initialized with gladLoadGL() in user's code. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) +#ifndef GLFW_INCLUDE_NONE #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. +#endif #include // Needs to be initialized with glbinding::Binding::initialize() in user's code. #include using namespace gl; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) +#ifndef GLFW_INCLUDE_NONE #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. +#endif #include // Needs to be initialized with glbinding::initialize() in user's code. #include using namespace gl; From 73c30aa085d8432fcaa9288572b317a3c8951530 Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Thu, 4 Jul 2019 18:28:34 -0700 Subject: [PATCH 006/959] Backends: Vulkan: Don't skip drawing when there's no vertexes to ensure that user callbacks are still processed. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_vulkan.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ad309327..70480187 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData + structure didn't have any vertices. (#2697) [@kudaba] ----------------------------------------------------------------------- diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 095a7f26..72866dde 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. // 2019-08-01: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. // 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. @@ -274,6 +275,7 @@ static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkCommandBu } // Bind Vertex And Index Buffer: + if (draw_data->TotalVtxCount > 0) { VkBuffer vertex_buffers[1] = { rb->VertexBuffer }; VkDeviceSize vertex_offset[1] = { 0 }; @@ -314,7 +316,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); - if (fb_width <= 0 || fb_height <= 0 || draw_data->TotalVtxCount == 0) + if (fb_width <= 0 || fb_height <= 0) return; ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; @@ -343,6 +345,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); // Upload vertex/index data into a single contiguous GPU buffer + if (vertex_size > 0) { ImDrawVert* vtx_dst = NULL; ImDrawIdx* idx_dst = NULL; From 2593b6a1c86dcfc2fee95bbe55fbd9ae04d5991c Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 27 Apr 2020 12:01:59 +0300 Subject: [PATCH 007/959] Drag and Drop: Fix unintended fallback "..." tooltip during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) --- docs/CHANGELOG.txt | 4 +++- imgui.cpp | 2 +- imgui.h | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70480187..11a9560c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,8 +49,10 @@ Other Changes: - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] -- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] +- Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when + drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] ----------------------------------------------------------------------- diff --git a/imgui.cpp b/imgui.cpp index f900a010..8e66bbed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4216,7 +4216,7 @@ void ImGui::EndFrame() } // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing. - if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount) + if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { g.DragDropWithinSource = true; SetTooltip("..."); diff --git a/imgui.h b/imgui.h index d3460d72..5420ac53 100644 --- a/imgui.h +++ b/imgui.h @@ -644,6 +644,7 @@ namespace ImGui // Drag and Drop // - [BETA API] API may evolve! + // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip as replacement) IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource() IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! From 8cbff5ccb23675f5b3eaa1080a79bb2ae575fc33 Mon Sep 17 00:00:00 2001 From: Ryan Pavlik Date: Fri, 24 Apr 2020 15:50:27 -0500 Subject: [PATCH 008/959] Fix various typos. (#3161) (found by Debian's lintian on a package that uses imgui.) (found by codespell.) --- imgui.cpp | 12 ++++++------ imgui.h | 4 ++-- imgui_demo.cpp | 10 +++++----- imgui_draw.cpp | 14 +++++++------- imgui_widgets.cpp | 10 +++++----- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 8e66bbed..8ce07618 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -900,7 +900,7 @@ static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end) static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow(). static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. -static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certaint time, unless mouse moved. +static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS @@ -4231,7 +4231,7 @@ void ImGui::EndFrame() UpdateMouseMovingWindowEndFrame(); // Sort the window list so that all child windows are after their parent - // We cannot do that on FocusWindow() because childs may not exist yet + // We cannot do that on FocusWindow() because children may not exist yet g.WindowsTempSortBuffer.resize(0); g.WindowsTempSortBuffer.reserve(g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) @@ -4331,7 +4331,7 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex } // Find window given position, search front-to-back -// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically +// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is // called, aka before the next Begin(). Moving window isn't affected. static void FindHoveredWindow() @@ -6360,7 +6360,7 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) } // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) -// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly. +// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. // If you want a window to never be focused, you may use the e.g. NoInputs flag. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) { @@ -6814,7 +6814,7 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() { ImGuiContext& g = *GImGui; - // Verify that io.KeyXXX fields haven't been tampered with. Key mods shoudl not be modified between NewFrame() and EndFrame() + // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() const ImGuiKeyModFlags expected_key_mod_flags = GetMergedKeyModFlags(); IM_ASSERT(g.IO.KeyMods == expected_key_mod_flags && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(expected_key_mod_flags); @@ -7811,7 +7811,7 @@ void ImGui::EndPopup() // Make all menus and popups wrap around for now, may need to expose that policy. NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); - // Child-popups don't need to be layed out + // Child-popups don't need to be laid out IM_ASSERT(g.WithinEndChild == false); if (window->Flags & ImGuiWindowFlags_ChildWindow) g.WithinEndChild = true; diff --git a/imgui.h b/imgui.h index 5420ac53..3dfdc39c 100644 --- a/imgui.h +++ b/imgui.h @@ -371,7 +371,7 @@ namespace ImGui // Cursor / Layout // - By "cursor" we mean the current output position. // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. - // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceeding widget. + // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: // Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos() // Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. @@ -2299,7 +2299,7 @@ struct ImFont float Scale; // 4 // in // = 1.f // Base font scale, 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] 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) - ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 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 accross all used codepoints. + ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 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. // Methods IMGUI_API ImFont(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e9652ef7..a052205c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -644,7 +644,7 @@ static void ShowDemoWindowWidgets() static bool test_drag_and_drop = false; ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be layed out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth); 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); @@ -994,7 +994,7 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Alignment")) { - HelpMarker("By default, Selectables uses style.SelectableTextAlign but it can be overriden on a per-item basis using PushStyleVar(). You'll probably want to always keep your default situation to left-align otherwise it becomes difficult to layout multiple items on a same line"); + HelpMarker("By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item basis using PushStyleVar(). You'll probably want to always keep your default situation to left-align otherwise it becomes difficult to layout multiple items on a same line"); static bool selected[3*3] = { true, false, true, false, true, false, true, false, true }; for (int y = 0; y < 3; y++) { @@ -1065,7 +1065,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Resize Callback")) { // To wire InputText() with std::string or any other custom string type, - // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper using your prefered type. + // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper using your preferred type. // See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. HelpMarker("Demonstrate using ImGuiInputTextFlags_CallbackResize to wire your resizable string type to InputText().\n\nSee misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); struct Funcs @@ -1082,7 +1082,7 @@ static void ShowDemoWindowWidgets() return 0; } - // Tip: Because ImGui:: is a namespace you would typicall add your own function into the namespace in your own source files. + // Tip: Because ImGui:: is a namespace you would typically add your own function into the namespace in your own source files. // For example, you may add a function called ImGui::InputText(const char* label, MyString* my_str). static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) { @@ -3865,7 +3865,7 @@ struct ExampleAppConsole AddLog("Unknown command: '%s'\n", command_line); } - // On commad input, we scroll to bottom even if AutoScroll==false + // On command input, we scroll to bottom even if AutoScroll==false ScrollToBottom = true; } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 909949dc..954c5536 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -615,7 +615,7 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c _IdxWritePtr += 6; } -// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superflous function calls to optimize debug/non-inlined builds. +// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. // Those macros expects l-values. #define IM_NORMALIZE2F_OVER_ZERO(VX,VY) do { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = 1.0f / ImSqrt(d2); VX *= inv_len; VY *= inv_len; } } while (0) #define IM_FIXNORMAL2F(VX,VY) do { float d2 = VX*VX + VY*VY; if (d2 < 0.5f) d2 = 0.5f; float inv_lensq = 1.0f / d2; VX *= inv_lensq; VY *= inv_lensq; } while (0) @@ -684,7 +684,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_x *= AA_SIZE; dm_y *= AA_SIZE; - // Add temporary vertexes + // Add temporary vertices 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; @@ -701,7 +701,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertexes + // Add vertices for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; @@ -741,7 +741,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 float dm_in_x = dm_x * half_inner_thickness; float dm_in_y = dm_y * half_inner_thickness; - // Add temporary vertexes + // Add temporary vertices ImVec2* out_vtx = &temp_points[i2*4]; out_vtx[0].x = points[i2].x + dm_out_x; out_vtx[0].y = points[i2].y + dm_out_y; @@ -764,7 +764,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertexes + // Add vertices for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; @@ -2307,7 +2307,7 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) // Ellipsis character 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: Also note that 0x2026 is currently seldomly included in our font ranges. Because of this we are more likely to use three individual dots. + // FIXME: Also note that 0x2026 is currently seldom included in our font ranges. Because of this we are more likely to use three individual dots. for (int i = 0; i < atlas->Fonts.size(); i++) { ImFont* font = atlas->Fonts[i]; @@ -3329,7 +3329,7 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im // Helper for ColorPicker4() // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. -// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether. +// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. // FIXME: uses ImGui::GetColorU32 void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 02ac3cd5..e58c8aea 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2345,7 +2345,7 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); } -// FIXME: Move some of the code into SliderBehavior(). Current responsability is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. +// FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { @@ -2942,7 +2942,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0) flags |= ImGuiInputTextFlags_CharsDecimal; flags |= ImGuiInputTextFlags_AutoSelectAll; - flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselve by comparing the actual data rather than the string. + flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. if (p_step != NULL) { @@ -3360,7 +3360,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (!is_resizable) return; - // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the midly similar code (until we remove the U16 buffer alltogether!) + // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!) ImGuiContext& g = *GImGui; ImGuiInputTextState* edit_state = &g.InputTextState; IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); @@ -4745,7 +4745,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags__DisplayMask) == 0) if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB)) { - // FIXME: Hackily differenciating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. + // FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050) value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap); value_changed = true; @@ -6249,7 +6249,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent) // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, - // However the final position is going to be different! It is choosen by FindBestWindowPosForPopup(). + // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup(). // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. ImVec2 popup_pos, pos = window->DC.CursorPos; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) From a2454f2a45ea016443411fcf69a971e9b1d650f6 Mon Sep 17 00:00:00 2001 From: Clownacy Date: Tue, 28 Apr 2020 15:15:00 +0100 Subject: [PATCH 009/959] Use __NEWLIB__ instead of __SWITCH__ and __CYGWIN__ for alloca.h-detection (#3070) Cygwin uses newlib, so it's covered by the __NEWLIB__ check. You can see how it defines __NEWLIB__ here: https://cygwin.com/git/?p=newlib-cygwin.git;a=blob;f=newlib/configure.in#l453 --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 954c5536..1df83d12 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -36,7 +36,7 @@ Index of this file: #include // vsnprintf, sscanf, printf #if !defined(alloca) -#if defined(__GLIBC__) || defined(__sun) || defined(__CYGWIN__) || defined(__APPLE__) || defined(__SWITCH__) +#if defined(__GLIBC__) || defined(__sun) || defined(__APPLE__) || defined(__NEWLIB__) #include // alloca (glibc uses . Note that Cygwin may have _WIN32 defined, so the order matters here) #elif defined(_WIN32) #include // alloca From d5ce3b43aeff58e31966903f23e8ed3dea6f11af Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 11:03:05 +0200 Subject: [PATCH 010/959] Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) --- docs/CHANGELOG.txt | 3 ++- examples/imgui_impl_vulkan.cpp | 25 ++++++++++++------------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 11a9560c..039a67ad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,7 +49,8 @@ Other Changes: - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] -- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData +- Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 72866dde..652476c7 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices. // 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. // 2019-08-01: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. // 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. @@ -334,22 +335,20 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm wrb->Index = (wrb->Index + 1) % wrb->Count; ImGui_ImplVulkanH_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; - VkResult err; - - // Create or resize the vertex/index buffers - size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); - size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); - if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size) - CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); - if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size) - CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); - - // Upload vertex/index data into a single contiguous GPU buffer - if (vertex_size > 0) + if (draw_data->TotalVtxCount > 0) { + // Create or resize the vertex/index buffers + size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); + size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); + if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size) + CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); + if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size) + CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); + + // Upload vertex/index data into a single contiguous GPU buffer ImDrawVert* vtx_dst = NULL; ImDrawIdx* idx_dst = NULL; - err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); + VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)(&vtx_dst)); check_vk_result(err); err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)(&idx_dst)); check_vk_result(err); From 794bf7a28d80caffb423b1ede77ca993c3efa387 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 29 Apr 2020 13:32:16 +0300 Subject: [PATCH 011/959] CI: Implement builds with IMGUI_DISABLE_WIN32_FUNCTIONS, IMGUI_DISABLE_FILE_FUNCTIONS, IMGUI_USE_BGRA_PACKED_COLOR IM_VEC2_CLASS_EXTRA, IM_VEC4_CLASS_EXTRA and building library as a DLL. --- .github/workflows/build.yml | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b089bfb4..03641749 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -59,6 +59,29 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp + - name: Build example_null (with IMGUI_DISABLE_WIN32_FUNCTIONS) + shell: bash + run: | + echo '#define IMGUI_DISABLE_WIN32_FUNCTIONS' > example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp + + - name: Build example_null (as DLL) + shell: cmd + run: | + "%VS_PATH%\VC\Auxiliary\Build\vcvarsall.bat" x64 + echo '#ifdef _EXPORT' > example_single_file.cpp + echo '# define IMGUI_API __declspec(dllexport)' >> example_single_file.cpp + echo '#else' >> example_single_file.cpp + echo '# define IMGUI_API __declspec(dllimport)' >> example_single_file.cpp + echo '#endif' >> example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + cl.exe /D_USRDLL /D_WINDLL /D_EXPORT /I. example_single_file.cpp /LD /FeImGui.dll /link + cl.exe /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp + - name: Build Win32 example_glfw_opengl2 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj /p:Platform=Win32 /p:Configuration=Release' @@ -233,6 +256,38 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (with IMGUI_DISABLE_FILE_FUNCTIONS) + run: | + echo '#define IMGUI_DISABLE_FILE_FUNCTIONS' > example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + + - name: Build example_null (with IMGUI_USE_BGRA_PACKED_COLOR) + run: | + echo '#define IMGUI_USE_BGRA_PACKED_COLOR' > example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + + - name: Build example_null (with IM_VEC2_CLASS_EXTRA and IM_VEC4_CLASS_EXTRA) + run: | + echo 'struct MyVec2 { float x; float y; MyVec2(float x, float y) : x(x), y(y) { } };' > example_single_file.cpp + echo 'struct MyVec4 { float x; float y; float z; float w;' >> example_single_file.cpp + echo 'MyVec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { } };' >> example_single_file.cpp + echo '#define IM_VEC2_CLASS_EXTRA \' >> example_single_file.cpp + echo ' ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \' >> example_single_file.cpp + echo ' operator MyVec2() const { return MyVec2(x, y); }' >> example_single_file.cpp + echo '#define IM_VEC4_CLASS_EXTRA \' >> example_single_file.cpp + echo ' ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \' >> example_single_file.cpp + echo ' operator MyVec4() const { return MyVec4(x, y, z, w); }' >> example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 From 1e9abf60d1b6c71a738c96ef9c123ab358608bf8 Mon Sep 17 00:00:00 2001 From: Silent Date: Tue, 28 Apr 2020 21:53:46 +0200 Subject: [PATCH 012/959] Backends: Keep shader blobs as local variables. (#3176) --- examples/imgui_impl_dx10.cpp | 33 ++++++++++++++++++++------------- examples/imgui_impl_dx11.cpp | 33 ++++++++++++++++++++------------- examples/imgui_impl_dx12.cpp | 30 ++++++++++++++++++------------ 3 files changed, 58 insertions(+), 38 deletions(-) diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 7eb4e5af..ffaa7707 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -41,11 +41,9 @@ static ID3D10Device* g_pd3dDevice = NULL; static IDXGIFactory* g_pFactory = NULL; static ID3D10Buffer* g_pVB = NULL; static ID3D10Buffer* g_pIB = NULL; -static ID3D10Blob* g_pVertexShaderBlob = NULL; static ID3D10VertexShader* g_pVertexShader = NULL; static ID3D10InputLayout* g_pInputLayout = NULL; static ID3D10Buffer* g_pVertexConstantBuffer = NULL; -static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D10PixelShader* g_pPixelShader = NULL; static ID3D10SamplerState* g_pFontSampler = NULL; static ID3D10ShaderResourceView*g_pFontTextureView = NULL; @@ -369,11 +367,14 @@ bool ImGui_ImplDX10_CreateDeviceObjects() return output;\ }"; - D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL); - if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK) + ID3DBlob* vertexShaderBlob; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pVertexShader) != S_OK) + { + vertexShaderBlob->Release(); return false; + } // Create the input layout D3D10_INPUT_ELEMENT_DESC local_layout[] = @@ -382,8 +383,12 @@ bool ImGui_ImplDX10_CreateDeviceObjects() { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; - if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + { + vertexShaderBlob->Release(); return false; + } + vertexShaderBlob->Release(); // Create the constant buffer { @@ -415,11 +420,15 @@ bool ImGui_ImplDX10_CreateDeviceObjects() return out_col; \ }"; - D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL); - if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK) + ID3DBlob* pixelShaderBlob; + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &g_pPixelShader) != S_OK) + { + pixelShaderBlob->Release(); return false; + } + pixelShaderBlob->Release(); } // Create the blending setup @@ -482,11 +491,9 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; } if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; } if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; } - if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; } if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; } if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; } if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; } - if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; } } bool ImGui_ImplDX10_Init(ID3D10Device* device) diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 97e17ff1..5aa09f9b 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -42,11 +42,9 @@ static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; static IDXGIFactory* g_pFactory = NULL; static ID3D11Buffer* g_pVB = NULL; static ID3D11Buffer* g_pIB = NULL; -static ID3D10Blob* g_pVertexShaderBlob = NULL; static ID3D11VertexShader* g_pVertexShader = NULL; static ID3D11InputLayout* g_pInputLayout = NULL; static ID3D11Buffer* g_pVertexConstantBuffer = NULL; -static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D11PixelShader* g_pPixelShader = NULL; static ID3D11SamplerState* g_pFontSampler = NULL; static ID3D11ShaderResourceView*g_pFontTextureView = NULL; @@ -381,11 +379,14 @@ bool ImGui_ImplDX11_CreateDeviceObjects() return output;\ }"; - D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL); - if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK) + ID3DBlob* vertexShaderBlob; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK) + { + vertexShaderBlob->Release(); return false; + } // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = @@ -394,8 +395,12 @@ bool ImGui_ImplDX11_CreateDeviceObjects() { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; - if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) + { + vertexShaderBlob->Release(); return false; + } + vertexShaderBlob->Release(); // Create the constant buffer { @@ -427,11 +432,15 @@ bool ImGui_ImplDX11_CreateDeviceObjects() return out_col; \ }"; - D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL); - if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK) + ID3DBlob* pixelShaderBlob; + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (g_pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK) + { + pixelShaderBlob->Release(); return false; + } + pixelShaderBlob->Release(); } // Create the blending setup @@ -494,11 +503,9 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; } if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; } if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; } - if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; } if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; } if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; } if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; } - if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; } } bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index e7bb5e9c..a2913613 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -37,8 +37,6 @@ // DirectX data static ID3D12Device* g_pd3dDevice = NULL; -static ID3D10Blob* g_pVertexShaderBlob = NULL; -static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D12RootSignature* g_pRootSignature = NULL; static ID3D12PipelineState* g_pPipelineState = NULL; static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN; @@ -473,6 +471,9 @@ bool ImGui_ImplDX12_CreateDeviceObjects() psoDesc.SampleDesc.Count = 1; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; + ID3DBlob* vertexShaderBlob; + ID3DBlob* pixelShaderBlob; + // Create the vertex shader { static const char* vertexShader = @@ -503,10 +504,9 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return output;\ }"; - D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &g_pVertexShaderBlob, NULL); - if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - psoDesc.VS = { g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize() }; + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &vertexShaderBlob, NULL))) + return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() }; // Create the input layout static D3D12_INPUT_ELEMENT_DESC local_layout[] = { @@ -535,10 +535,12 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return out_col; \ }"; - D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &g_pPixelShaderBlob, NULL); - if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - return false; - psoDesc.PS = { g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize() }; + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &pixelShaderBlob, NULL))) + { + vertexShaderBlob->Release(); + return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + } + psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() }; } // Create the blending setup @@ -584,7 +586,13 @@ bool ImGui_ImplDX12_CreateDeviceObjects() } if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK) + { + vertexShaderBlob->Release(); + pixelShaderBlob->Release(); return false; + } + vertexShaderBlob->Release(); + pixelShaderBlob->Release(); ImGui_ImplDX12_CreateFontsTexture(); @@ -596,8 +604,6 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() if (!g_pd3dDevice) return; - SafeRelease(g_pVertexShaderBlob); - SafeRelease(g_pPixelShaderBlob); SafeRelease(g_pRootSignature); SafeRelease(g_pPipelineState); SafeRelease(g_pFontTextureResource); From 099091280f055c1267bf75dc390a8d95665e8c3f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 11:32:58 +0200 Subject: [PATCH 013/959] Backends: DX10/DX11: Minor tweaks. --- examples/imgui_impl_dx10.cpp | 30 +++++++++++++++--------------- examples/imgui_impl_dx11.cpp | 30 +++++++++++++++--------------- examples/imgui_impl_dx12.cpp | 9 +++------ 3 files changed, 33 insertions(+), 36 deletions(-) diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index ffaa7707..23ade277 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -342,29 +342,29 @@ bool ImGui_ImplDX10_CreateDeviceObjects() static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ - float4x4 ProjectionMatrix; \ + float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ - float2 pos : POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float2 pos : POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ - float4 pos : SV_POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float4 pos : SV_POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ - PS_INPUT output;\ - output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ - output.col = input.col;\ - output.uv = input.uv;\ - return output;\ + PS_INPUT output;\ + output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ + output.col = input.col;\ + output.uv = input.uv;\ + return output;\ }"; ID3DBlob* vertexShaderBlob; @@ -379,9 +379,9 @@ bool ImGui_ImplDX10_CreateDeviceObjects() // Create the input layout D3D10_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) { diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 5aa09f9b..26eb407f 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -354,29 +354,29 @@ bool ImGui_ImplDX11_CreateDeviceObjects() static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ - float4x4 ProjectionMatrix; \ + float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ - float2 pos : POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float2 pos : POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ - float4 pos : SV_POSITION;\ - float4 col : COLOR0;\ - float2 uv : TEXCOORD0;\ + float4 pos : SV_POSITION;\ + float4 col : COLOR0;\ + float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ - PS_INPUT output;\ - output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ - output.col = input.col;\ - output.uv = input.uv;\ - return output;\ + PS_INPUT output;\ + output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ + output.col = input.col;\ + output.uv = input.uv;\ + return output;\ }"; ID3DBlob* vertexShaderBlob; @@ -391,9 +391,9 @@ bool ImGui_ImplDX11_CreateDeviceObjects() // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (g_pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) { diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index a2913613..167a189b 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -585,14 +585,11 @@ bool ImGui_ImplDX12_CreateDeviceObjects() desc.BackFace = desc.FrontFace; } - if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK) - { - vertexShaderBlob->Release(); - pixelShaderBlob->Release(); - return false; - } + HRESULT result_pipeline_state = g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)); vertexShaderBlob->Release(); pixelShaderBlob->Release(); + if (result_pipeline_state != S_OK) + return false; ImGui_ImplDX12_CreateFontsTexture(); From b4dd28ffbbe4d382d38ef6de742db93388b5482f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 14:58:21 +0200 Subject: [PATCH 014/959] Style: Added style.TabMinWidthForUnselectedCloseButton settings. Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 3 +++ imgui.h | 1 + imgui_internal.h | 2 +- imgui_widgets.cpp | 23 +++++++++++++++++++---- 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 039a67ad..819abbec 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,10 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) +- Style: Added style.TabMinWidthForUnselectedCloseButton settings. + Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). + Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). + Set to an intermediary value to toggle behavior based on width (same as Firefox). - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] diff --git a/imgui.cpp b/imgui.cpp index 8ce07618..680a3289 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1028,6 +1028,7 @@ ImGuiStyle::ImGuiStyle() GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. + TabMinWidthForUnselectedCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. 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. @@ -1064,6 +1065,8 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); TabRounding = ImFloor(TabRounding * scale_factor); + if (TabMinWidthForUnselectedCloseButton != FLT_MAX) + TabMinWidthForUnselectedCloseButton = ImFloor(TabMinWidthForUnselectedCloseButton * scale_factor); DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); diff --git a/imgui.h b/imgui.h index 3dfdc39c..9c85e97b 100644 --- a/imgui.h +++ b/imgui.h @@ -1393,6 +1393,7 @@ struct ImGuiStyle float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. + float TabMinWidthForUnselectedCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. 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. diff --git a/imgui_internal.h b/imgui_internal.h index d6ef765d..46cca946 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1827,7 +1827,7 @@ namespace ImGui IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags); IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button); IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); - IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id); + IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible); // Render helpers // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e58c8aea..200c43e4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7090,6 +7090,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->NextSelectedTabId = id; // Lock visibility + // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!) bool tab_contents_visible = (tab_bar->VisibleTabId == id); if (tab_contents_visible) tab_bar->VisibleTabWasSubmitted = true; @@ -7195,7 +7196,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Render tab label, process close button const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; - bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id); + bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); if (just_closed && p_open != NULL) { *p_open = false; @@ -7270,13 +7271,21 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. -bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id) +bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible) { ImGuiContext& g = *GImGui; ImVec2 label_size = CalcTextSize(label, NULL, true); if (bb.GetWidth() <= 1.0f) return false; + // In Style V2 we'll have full override of all colors per state (e.g. focused, selected) + // But right now if you want to alter text color of tabs this is what you need to do. +#if 0 + const float backup_alpha = g.Style.Alpha; + if (!is_contents_visible) + g.Style.Alpha *= 0.7f; +#endif + // Render text label (with clipping + alpha gradient) + unsaved marker const char* TAB_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); @@ -7296,8 +7305,9 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, bool close_button_pressed = false; bool close_button_visible = false; if (close_button_id != 0) - if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id) - close_button_visible = true; + if (is_contents_visible || bb.GetWidth() >= g.Style.TabMinWidthForUnselectedCloseButton) + if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id) + close_button_visible = true; if (close_button_visible) { ImGuiItemHoveredDataBackup last_item_backup; @@ -7318,6 +7328,11 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f; 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); +#if 0 + if (!is_contents_visible) + g.Style.Alpha = backup_alpha; +#endif + return close_button_pressed; } From 11a3e75f47085fe14da5ff4ca5fe2298092fd937 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 4 May 2020 20:46:20 +0200 Subject: [PATCH 015/959] Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_win32.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 819abbec..96cadc9b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) +- Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index aa00a1f9..ae18eb6e 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -359,7 +359,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA #if !defined(_versionhelpers_H_INCLUDED_) && !defined(_INC_VERSIONHELPERS) static BOOL IsWindowsVersionOrGreater(WORD major, WORD minor, WORD sp) { - OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0, { 0 }, sp }; + OSVERSIONINFOEXW osvi = { sizeof(osvi), major, minor, 0, 0, { 0 }, sp, 0, 0, 0, 0 }; DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR; ULONGLONG cond = ::VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL); cond = ::VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL); @@ -405,7 +405,9 @@ void ImGui_ImplWin32_EnableDpiAwareness() return; } } - SetProcessDPIAware(); +#if _WIN32_WINNT >= 0x0600 + ::SetProcessDPIAware(); +#endif } #if defined(_MSC_VER) && !defined(NOGDI) From 419f905f91f1a7f0dc0c836a73b7579b66e454ce Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 May 2020 19:53:54 +0200 Subject: [PATCH 016/959] Demo: Extracted some code out of ShowStyleEditor() into NodeFont(). --- imgui_demo.cpp | 160 +++++++++++++++++++++++++++---------------------- 1 file changed, 90 insertions(+), 70 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a052205c..24699261 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3285,6 +3285,95 @@ void ImGui::ShowFontSelector(const char* label) "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame()."); } +// [Internal] Display details for a single font, called by ShowStyleEditor(). +static void NodeFont(ImFont* font) +{ + ImGuiIO& io = ImGui::GetIO(); + ImGuiStyle& style = ImGui::GetStyle(); + bool font_details_opened = ImGui::TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)", + font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); + ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; } + if (!font_details_opened) + return; + + ImGui::PushFont(font); + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::PopFont(); + ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font + ImGui::SameLine(); HelpMarker( + "Note than 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.)"); + ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, "%.0f"); + ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + ImGui::Text("Fallback character: '%c' (U+%04X)", font->FallbackChar, font->FallbackChar); + ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar); + const int surface_sqrt = (int)sqrtf((float)font->MetricsTotalSurface); + ImGui::Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + if (font->ConfigData) + if (const ImFontConfig* cfg = &font->ConfigData[config_i]) + ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", + config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); + if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + { + // Display all glyphs of the fonts in separate pages of 256 characters + const ImU32 glyph_col = ImGui::GetColorU32(ImGuiCol_Text); + 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 & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) + { + base += 4096 - 256; + continue; + } + + int count = 0; + for (unsigned int n = 0; n < 256; n++) + if (font->FindGlyphNoFallback((ImWchar)(base + n))) + count++; + if (count <= 0) + continue; + if (!ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) + continue; + float cell_size = font->FontSize * 1; + float cell_spacing = style.ItemSpacing.y; + ImVec2 base_pos = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + 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 + // in order to generate a zero-terminated 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) + font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n)); + if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) + { + ImGui::BeginTooltip(); + ImGui::Text("Codepoint: U+%04X", base + n); + ImGui::Separator(); + ImGui::Text("Visible: %d", glyph->Visible); + ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX); + ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + ImGui::EndTooltip(); + } + } + ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); +} + void ImGui::ShowStyleEditor(ImGuiStyle* ref) { // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to an internally stored reference) @@ -3433,76 +3522,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImFont* font = atlas->Fonts[i]; ImGui::PushID(font); - bool font_details_opened = ImGui::TreeNode(font, "Font %d: \"%s\"\n%.2f px, %d glyphs, %d file(s)", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); - ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; } - if (font_details_opened) - { - ImGui::PushFont(font); - ImGui::Text("The quick brown fox jumps over the lazy dog"); - ImGui::PopFont(); - ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font - ImGui::SameLine(); HelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont 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 should hopefully be rewritten in the future to make scaling more natural and automatic.)"); - ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, "%.0f"); - ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); - ImGui::Text("Fallback character: '%c' (U+%04X)", font->FallbackChar, font->FallbackChar); - ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar); - const float surface_sqrt = sqrtf((float)font->MetricsTotalSurface); - ImGui::Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, (int)surface_sqrt, (int)surface_sqrt); - for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) - if (font->ConfigData) - if (const ImFontConfig* cfg = &font->ConfigData[config_i]) - ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); - if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) - { - // Display all glyphs of the fonts in separate pages of 256 characters - 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 & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) - { - base += 4096 - 256; - continue; - } - - int count = 0; - for (unsigned int n = 0; n < 256; n++) - count += font->FindGlyphNoFallback((ImWchar)(base + n)) ? 1 : 0; - if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) - { - float cell_size = font->FontSize * 1; - float cell_spacing = style.ItemSpacing.y; - ImVec2 base_pos = ImGui::GetCursorScreenPos(); - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - for (unsigned int n = 0; n < 256; n++) - { - 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) - font->RenderChar(draw_list, cell_size, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base + n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string. - if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) - { - ImGui::BeginTooltip(); - ImGui::Text("Codepoint: U+%04X", base + n); - ImGui::Separator(); - ImGui::Text("Visible: %d", glyph->Visible); - ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX); - ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); - ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); - ImGui::EndTooltip(); - } - } - ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16)); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - } - ImGui::TreePop(); - } + NodeFont(font); ImGui::PopID(); } if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) From f152fac4f1962aedf1d483a5b05a525637354b3a Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 5 May 2020 19:39:24 +0200 Subject: [PATCH 017/959] Demo: Wrapped many (not all) code and comments lines to 120 characters to fit below GitHub viewer limit. (#3193) --- imgui.cpp | 2 +- imgui.h | 2 +- imgui_demo.cpp | 1238 ++++++++++++++++++++++++++++++------------------ 3 files changed, 781 insertions(+), 461 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 680a3289..86af727d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4,7 +4,7 @@ // Help: // - Read FAQ at http://dearimgui.org/faq // - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. -// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // Read imgui.cpp for details, links and comments. // Resources: diff --git a/imgui.h b/imgui.h index 9c85e97b..788f74c9 100644 --- a/imgui.h +++ b/imgui.h @@ -4,7 +4,7 @@ // Help: // - Read FAQ at http://dearimgui.org/faq // - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. -// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // Read imgui.cpp for details, links and comments. // Resources: diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 24699261..3b2ceee1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4,38 +4,39 @@ // Help: // - Read FAQ at http://dearimgui.org/faq // - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. -// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. All applications in examples/ are doing that. +// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // Read imgui.cpp for more details, documentation and comments. // Get latest version at https://github.com/ocornut/imgui // Message to the person tempted to delete this file when integrating Dear ImGui into their code base: -// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other coders -// will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available debug menu of -// your game/app! Removing this file from your project is hindering access to documentation for everyone in your team, -// likely leading you to poorer usage of the library. +// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other +// coders will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available +// debug menu of your game/app! Removing this file from your project is hindering access to documentation for everyone +// in your team, likely leading you to poorer usage of the library. // Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow(). -// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be linked, -// you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty. +// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be +// linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty. // In other situation, whenever you have Dear ImGui available you probably want this to be available for reference. // Thank you, // -Your beloved friend, imgui_demo.cpp (which you won't delete) // Message to beginner C/C++ programmers about the meaning of the 'static' keyword: -// In this demo code, we frequently we use 'static' variables inside functions. A static variable persist across calls, so it is -// essentially like a global variable but declared inside the scope of the function. We do this as a way to gather code and data -// in the same place, to make the demo source code faster to read, faster to write, and smaller in size. -// It also happens to be a convenient way of storing simple UI related information as long as your function doesn't need to be -// reentrant or used in multiple threads. This might be a pattern you will want to use in your code, but most of the real data -// you would be editing is likely going to be stored outside your functions. +// In this demo code, we frequently we use 'static' variables inside functions. A static variable persist across calls, +// so it is essentially like a global variable but declared inside the scope of the function. We do this as a way to +// gather code and data in the same place, to make the demo source code faster to read, faster to write, and smaller +// in size. It also happens to be a convenient way of storing simple UI related information as long as your function +// doesn't need to be reentrant or used in multiple threads. This might be a pattern you will want to use in your code, +// but most of the real data you would be editing is likely going to be stored outside your functions. // The Demo code in this file is designed to be easy to copy-and-paste in into your application! // Because of this: -// - We never omit the ImGui:: namespace when calling functions, even though most of our code is already in the same namespace. +// - We never omit the ImGui:: prefix when calling functions, even though most code here is in the same namespace. // - We try to declare static variables in the local scope, as close as possible to the code using them. -// - We never use any of the helpers/facilities used internally by Dear ImGui, unless it has been exposed in the public API (imgui.h). -// - We never use maths operators on ImVec2/ImVec4. For other of our sources files, they are provided by imgui_internal.h w/ IMGUI_DEFINE_MATH_OPERATORS. -// For your own sources file they are optional and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h. -// Because we don't want to assume anything about your support of maths operators, we don't use them in imgui_demo.cpp. +// - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API. +// - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided +// by imgui_internal.h using the IMGUI_DEFINE_MATH_OPERATORS define. For your own sources file they are optional +// and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h. +// Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp. /* @@ -82,31 +83,31 @@ Index of this file: #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif #if defined(__clang__) -#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. -#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) -#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' -#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal -#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. -#pragma clang diagnostic ignored "-Wunused-macros" // warning : warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type +#pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. #if __has_warning("-Wzero-as-null-pointer-constant") -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") -#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. #endif #if __has_warning("-Wreserved-id-macro") -#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier #endif #elif defined(__GNUC__) -#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size -#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) -#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function -#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value -#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. #endif -// Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!) +// Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!) #ifdef _WIN32 #define IM_NEWLINE "\r\n" #else @@ -161,7 +162,9 @@ void ImGui::ShowUserGuide() { ImGuiIO& io = ImGui::GetIO(); ImGui::BulletText("Double-click on title bar to collapse window."); - ImGui::BulletText("Click and drag on lower corner to resize window\n(double-click to auto fit window to its contents)."); + ImGui::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."); if (io.FontAllowUserScaling) @@ -196,7 +199,8 @@ void ImGui::ShowUserGuide() // - ShowDemoWindowMisc() //----------------------------------------------------------------------------- -// We split the contents of the big ShowDemoWindow() function into smaller functions (because the link time of very large functions grow non-linearly) +// We split the contents of the big ShowDemoWindow() function into smaller functions +// (because the link time of very large functions grow non-linearly) static void ShowDemoWindowWidgets(); static void ShowDemoWindowLayout(); static void ShowDemoWindowPopups(); @@ -204,10 +208,13 @@ static void ShowDemoWindowColumns(); static void ShowDemoWindowMisc(); // Demonstrate most Dear ImGui features (this is big function!) -// You may execute this function to experiment with the UI and understand what it does. You may then search for keywords in the code when you are interested by a specific feature. +// You may execute this function to experiment with the UI and understand what it does. +// You may then search for keywords in the code when you are interested by a specific feature. void ImGui::ShowDemoWindow(bool* p_open) { - IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); // Exceptionally add an extra assert here for people confused with initial dear imgui setup + // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup + // Most ImGui functions would normally just crash if the context is missing. + IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); // Examples Apps (accessible from the "Examples" menu) static bool show_app_documents = false; @@ -241,9 +248,14 @@ void ImGui::ShowDemoWindow(bool* p_open) static bool show_app_style_editor = false; static bool show_app_about = false; - if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); } - if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); } - if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); } + if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); } + if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); } + if (show_app_style_editor) + { + ImGui::Begin("Dear ImGui Style Editor", &show_app_style_editor); + ImGui::ShowStyleEditor(); + ImGui::End(); + } // Demonstrate the various window flags. Typically you would just use the default! static bool no_titlebar = false; @@ -269,7 +281,8 @@ void ImGui::ShowDemoWindow(bool* p_open) if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus; if (no_close) p_open = NULL; // Don't pass our bool* to Begin - // We specify a default position/size in case there's no data in the .ini file. Typically this isn't required! We only do it to make the Demo applications a little more welcoming. + // We specify a default position/size in case there's no data in the .ini file. + // We only do it to make the demo applications a little more welcoming, but typically this isn't required. ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); @@ -281,9 +294,13 @@ void ImGui::ShowDemoWindow(bool* p_open) return; } - // Most "big" widgets share a common width settings by default. - //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // Use 2/3 of the space for widgets and 1/3 for labels (default) - ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // Use fixed width for labels (by passing a negative value), the rest goes to widgets. We choose a width proportional to our font size. + // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. + + // e.g. Use 2/3 of the space for widgets and 1/3 for labels (default) + //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); + + // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. + ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // Menu Bar if (ImGui::BeginMenuBar()) @@ -350,13 +367,15 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Configuration##2")) { - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); ImGui::SameLine(); HelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); - ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); - if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) // Create a way to restore this flag otherwise we could be stuck completely! + ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); + + // The "NoMouse" option above can get us stuck with a disable mouse! Provide an alternative way to fix it: + if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) { if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f) { @@ -374,18 +393,22 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback."); ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly); ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); - ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor for you. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); + ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); ImGui::TreePop(); ImGui::Separator(); } if (ImGui::TreeNode("Backend Flags")) { - HelpMarker("Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.\nHere we expose then as read-only fields to avoid breaking interactions with your back-end."); - ImGuiBackendFlags backend_flags = io.BackendFlags; // Make a local copy to avoid modifying actual back-end flags. - ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); - ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); - ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasSetMousePos); + HelpMarker( + "Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.\n" + "Here we expose then as read-only fields to avoid breaking interactions with your back-end."); + + // Make a local copy to avoid modifying actual back-end flags. + ImGuiBackendFlags backend_flags = io.BackendFlags; + ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); + ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasSetMousePos); ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); ImGui::TreePop(); ImGui::Separator(); @@ -401,10 +424,13 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Capture/Logging")) { - ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded."); - HelpMarker("Try opening any of the contents below in this window and then click one of the \"Log To\" button."); + HelpMarker( + "The logging API redirects all text output so you can easily capture the content of " + "a window or a block. Tree nodes can be automatically expanded.\n" + "Try opening any of the contents below in this window and then click one of the \"Log To\" button."); ImGui::LogButtons(); - ImGui::TextWrapped("You can also call ImGui::LogText() to output directly to the log without a visual output."); + + HelpMarker("You can also call ImGui::LogText() to output directly to the log without a visual output."); if (ImGui::Button("Copy \"Hello, world!\" to clipboard")) { ImGui::LogToClipboard(); @@ -478,7 +504,9 @@ static void ShowDemoWindowWidgets() ImGui::PopID(); } - // Use AlignTextToFramePadding() to align text baseline to the baseline of framed elements (otherwise a Text+SameLine+Button sequence will have the text a little too high by default) + // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + // See 'Demo->Layout->Text Baseline Alignment' for details. ImGui::AlignTextToFramePadding(); ImGui::Text("Hold to repeat:"); ImGui::SameLine(); @@ -516,7 +544,7 @@ static void ShowDemoWindowWidgets() { // Using the _simplified_ one-liner Combo() api here // See "Combo" section for examples of how to use the more complete BeginCombo()/EndCombo() api. - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; static int item_current = 0; ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); HelpMarker("Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n"); @@ -527,14 +555,28 @@ static void ShowDemoWindowWidgets() // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file. static char str0[128] = "Hello, world!"; ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); - ImGui::SameLine(); HelpMarker("USER:\nHold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n\nPROGRAMMER:\nYou can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated in imgui_demo.cpp)."); + ImGui::SameLine(); HelpMarker( + "USER:\n" + "Hold SHIFT or use mouse to select text.\n" + "CTRL+Left/Right to word jump.\n" + "CTRL+A or double-click to select all.\n" + "CTRL+X,CTRL+C,CTRL+V clipboard.\n" + "CTRL+Z,CTRL+Y undo/redo.\n" + "ESCAPE to revert.\n\n" + "PROGRAMMER:\n" + "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() " + "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated " + "in imgui_demo.cpp)."); static char str1[128] = ""; ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1)); static int i0 = 123; ImGui::InputInt("input int", &i0); - ImGui::SameLine(); HelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); + ImGui::SameLine(); HelpMarker( + "You can apply arithmetic operators +,*,/ on numerical values.\n" + " e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\n" + "Use +- to subtract."); static float f0 = 0.001f; ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); @@ -544,7 +586,9 @@ static void ShowDemoWindowWidgets() static float f1 = 1.e10f; ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); - ImGui::SameLine(); HelpMarker("You can input value using the scientific notation,\n e.g. \"1e+8\" becomes \"100000000\".\n"); + ImGui::SameLine(); HelpMarker( + "You can input value using the scientific notation,\n" + " e.g. \"1e+8\" becomes \"100000000\"."); static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; ImGui::InputFloat3("input float3", vec4a); @@ -553,7 +597,10 @@ static void ShowDemoWindowWidgets() { static int i1 = 50, i2 = 42; ImGui::DragInt("drag int", &i1, 1); - ImGui::SameLine(); HelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value."); + ImGui::SameLine(); HelpMarker( + "Click and drag to edit value.\n" + "Hold SHIFT/ALT for faster/slower edit.\n" + "Double-click or CTRL+click to input value."); ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%"); @@ -578,10 +625,10 @@ static void ShowDemoWindowWidgets() // Here we completely omit '%d' from the format string, so it'll only display a name. // This technique can also be used with DragInt(). enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT }; - const char* element_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; - static int current_element = Element_Fire; - const char* current_element_name = (current_element >= 0 && current_element < Element_COUNT) ? element_names[current_element] : "Unknown"; - ImGui::SliderInt("slider enum", ¤t_element, 0, Element_COUNT - 1, current_element_name); + static int elem = Element_Fire; + const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" }; + const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown"; + ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer."); } @@ -589,16 +636,20 @@ static void ShowDemoWindowWidgets() static float col1[3] = { 1.0f,0.0f,0.2f }; static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; ImGui::ColorEdit3("color 1", col1); - ImGui::SameLine(); HelpMarker("Click on the colored square to open a color picker.\nClick and hold to use drag and drop.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n"); + ImGui::SameLine(); HelpMarker( + "Click on the colored square to open a color picker.\n" + "Click and hold to use drag and drop.\n" + "Right-click on the colored square to show options.\n" + "CTRL+click on individual component to input value.\n"); ImGui::ColorEdit4("color 2", col2); } { // List box - const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; - static int listbox_item_current = 1; - ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int item_current = 1; + ImGui::ListBox("listbox\n(single select)", &item_current, items, IM_ARRAYSIZE(items), 4); //static int listbox_item_current2 = 2; //ImGui::SetNextItemWidth(-1); @@ -620,8 +671,8 @@ static void ShowDemoWindowWidgets() { for (int i = 0; i < 5; i++) { - // Use SetNextItemOpen() so set the default state of a node to be open. - // We could also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing! + // Use SetNextItemOpen() so set the default state of a node to be open. We could + // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing! if (i == 0) ImGui::SetNextItemOpen(true, ImGuiCond_Once); @@ -638,25 +689,31 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Advanced, with Selectable nodes")) { - HelpMarker("This is a more typical looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); + HelpMarker( + "This is a more typical looking tree with selectable nodes.\n" + "Click to select, CTRL+Click to toggle, click on arrows or double-click to open."); static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; static bool align_label_with_current_x_position = false; static bool test_drag_and_drop = false; - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth); 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!"); if (align_label_with_current_x_position) ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); - static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. - int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc. + // 'selection_mask' is dumb representation of what may be user-side selection state. + // You may retain selection state inside or outside your objects in whatever format you see fit. + // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end + /// of the loop. May be a pointer to your own node type, etc. + static int selection_mask = (1 << 2); + int node_clicked = -1; for (int i = 0; i < 6; i++) { - // Disable the default open on single-click behavior and pass in Selected flag according to our selection state. + // Disable the default "open on single-click behavior" + set Selected flag according to our selection. ImGuiTreeNodeFlags node_flags = base_flags; const bool is_selected = (selection_mask & (1 << i)) != 0; if (is_selected) @@ -682,8 +739,8 @@ static void ShowDemoWindowWidgets() else { // Items 3..5 are Tree Leaves - // The only reason we use TreeNode at all is to allow selection of the leaf. - // Otherwise we can use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can + // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i); if (ImGui::IsItemClicked()) @@ -698,10 +755,11 @@ static void ShowDemoWindowWidgets() } if (node_clicked != -1) { - // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. + // Update selection state + // (process outside of tree loop to avoid visual inconsistencies during the clicking frame) if (ImGui::GetIO().KeyCtrl) selection_mask ^= (1 << node_clicked); // CTRL+click to toggle - else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection selection_mask = (1 << node_clicked); // Click to single-select } if (align_label_with_current_x_position) @@ -769,21 +827,24 @@ static void ShowDemoWindowWidgets() static float wrap_width = 200.0f; ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); - ImGui::Text("Test paragraph 1:"); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("The lazy dog is a good dog. This paragraph is made to fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); - ImGui::PopTextWrapPos(); - - ImGui::Text("Test paragraph 2:"); - pos = ImGui::GetCursorScreenPos(); - ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); - ImGui::PopTextWrapPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 2; n++) + { + ImGui::Text("Test paragraph %d:", n); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y); + ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + if (n == 0) + ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); + if (n == 1) + ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + + // Draw actual text bounding box, following by marker of our expected limit (should not overlap!) + draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255)); + draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)); + ImGui::PopTextWrapPos(); + } ImGui::TreePop(); } @@ -791,14 +852,19 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("UTF-8 Text")) { // UTF-8 test with Japanese characters - // (Needs a suitable font, try Noto, or Arial Unicode, or M+ fonts. Read docs/FONTS.txt for details.) + // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.txt for details.) // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 - // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. Visual Studio save your file as 'UTF-8 without signature') - // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 CHARACTERS IN THIS SOURCE FILE. - // Instead we are encoding a few strings with hexadecimal constants. Don't do this in your application! - // Please use u8"text in any language" in your application! - // Note that characters values are preserved even by InputText() if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. - ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. Read docs/FONTS.txt for details."); + // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you + // can save your source files as 'UTF-8 without signature'). + // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8 + // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants. + // Don't do this in your application! Please use u8"text in any language" in your application! + // Note that characters values are preserved even by InputText() if the font cannot be displayed, + // so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped( + "CJK text will only appears if the font was loaded with the appropriate CJK character ranges. " + "Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. " + "Read docs/FONTS.txt for details."); ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); // Normally we would use u8"blah blah" with the proper characters directly in the string. ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; @@ -814,41 +880,63 @@ static void ShowDemoWindowWidgets() ImGuiIO& io = ImGui::GetIO(); ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); - // Here we are grabbing the font texture because that's the only one we have access to inside the demo code. - // Remember that ImTextureID is just storage for whatever you want it to be, it is essentially a value that will be passed to the render function inside the ImDrawCmd structure. - // If you use one of the default imgui_impl_XXXX.cpp renderer, they all have comments at the top of their file to specify what they expect to be stored in ImTextureID. - // (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.) - // 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. - // Using ShowMetricsWindow() as a "debugger" to inspect the draw data that are being passed to your render will help you debug issues if you are confused about this. - // Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage(). + // 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 back-end via the ImDrawCmd structure. + // If you use one of the default imgui_impl_XXXX.cpp rendering back-end, 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 + // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. + // More: + // - 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, + // it will help you debug issues if you are confused about it. + // - 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; - - ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0,0), ImVec2(1,1), ImVec4(1.0f,1.0f,1.0f,1.0f), ImVec4(1.0f,1.0f,1.0f,0.5f)); - if (ImGui::IsItemHovered()) { - ImGui::BeginTooltip(); - float region_sz = 32.0f; - float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; if (region_x < 0.0f) region_x = 0.0f; else if (region_x > my_tex_w - region_sz) region_x = my_tex_w - region_sz; - float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; if (region_y < 0.0f) region_y = 0.0f; else if (region_y > my_tex_h - region_sz) region_y = my_tex_h - region_sz; - float zoom = 4.0f; - ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); - ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); - ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); - ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); - ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, ImVec4(1.0f, 1.0f, 1.0f, 1.0f), ImVec4(1.0f, 1.0f, 1.0f, 0.5f)); - ImGui::EndTooltip(); + 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 + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); // 50% opaque white + ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + float region_sz = 32.0f; + float region_x = io.MousePos.x - pos.x - region_sz * 0.5f; + float region_y = io.MousePos.y - pos.y - region_sz * 0.5f; + float zoom = 4.0f; + if (region_x < 0.0f) { region_x = 0.0f; } + else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; } + if (region_y < 0.0f) { region_y = 0.0f; } + else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; } + ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y); + ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz); + ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h); + ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h); + ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, tint_col, border_col); + ImGui::EndTooltip(); + } } ImGui::TextWrapped("And now some textured buttons.."); static int pressed_count = 0; for (int i = 0; i < 8; i++) { ImGui::PushID(i); - int frame_padding = -1 + i; // -1 = uses default padding - if (ImGui::ImageButton(my_tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/my_tex_w,32/my_tex_h), frame_padding, ImVec4(0.0f,0.0f,0.0f,1.0f))) + int frame_padding = -1 + i; // -1 == uses default padding (style.FramePadding) + ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible + ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left + ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32 / my_tex_h); // UV coordinates for (32,32) in our texture + ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background + ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint + if (ImGui::ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col)) pressed_count += 1; ImGui::PopID(); ImGui::SameLine(); @@ -869,19 +957,23 @@ static void ShowDemoWindowWidgets() if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", (unsigned int*)&flags, ImGuiComboFlags_NoPreview)) flags &= ~ImGuiComboFlags_NoArrowButton; // Clear the other flag, as we cannot combine both - // General BeginCombo() API, you have full control over your selection data and display type. - // (your selection data could be an index, a pointer to the object, an id for the object, a flag stored in the object itself, etc.) + // Using the generic BeginCombo() API, you have full control over how to display the combo contents. + // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + // stored in the object itself, etc.) const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; - static const char* item_current = items[0]; // Here our selection is a single pointer stored outside the object. - if (ImGui::BeginCombo("combo 1", item_current, flags)) // The second parameter is the label previewed before opening the combo. + static int item_current_idx = 0; // Here our selection data is an index. + const char* combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically could be anything)( + if (ImGui::BeginCombo("combo 1", combo_label, flags)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) { - bool is_selected = (item_current == items[n]); + const bool is_selected = (item_current_idx == n); if (ImGui::Selectable(items[n], is_selected)) - item_current = items[n]; + item_current_idx = n; + + // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (is_selected) - ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch) + ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } @@ -905,9 +997,11 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Selectables")) { // Selectable() has 2 overloads: - // - The one taking "bool selected" as a read-only selection information. When Selectable() has been clicked is returns true and you can alter selection state accordingly. + // - The one taking "bool selected" as a read-only selection information. + // When Selectable() has been clicked it returns true and you can alter selection state accordingly. // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) - // The earlier is more flexible, as in real application your selection may be stored in a different manner (in flags within objects, as an external list, etc). + // The earlier is more flexible, as in real application your selection may be stored in many different ways + // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). if (ImGui::TreeNode("Basic")) { static bool selection[5] = { false, true, false, false, false }; @@ -951,7 +1045,8 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Rendering more text into the same line")) { - // Using the Selectable() override that takes "bool* p_selected" parameter and toggle your booleans automatically. + // Using the Selectable() override that takes "bool* p_selected" parameter, + // this function toggle your bool value automatically. static bool selected[3] = { false, false, false }; ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); @@ -973,13 +1068,17 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Grid")) { - static bool selected[4*4] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; + static int selected[4*4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; for (int i = 0; i < 4*4; i++) { ImGui::PushID(i); - if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50))) + if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50,50))) { - // Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer. The second part of each test is unnecessary. + // Toggle + selected[i] = !selected[i]; + + // Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer. + // The second part of each test is unnecessary. int x = i % 4; int y = i / 4; if (x > 0) { selected[i - 1] ^= 1; } @@ -994,8 +1093,11 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Alignment")) { - HelpMarker("By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item basis using PushStyleVar(). You'll probably want to always keep your default situation to left-align otherwise it becomes difficult to layout multiple items on a same line"); - static bool selected[3*3] = { true, false, true, false, true, false, true, false, true }; + HelpMarker( + "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item " + "basis using PushStyleVar(). You'll probably want to always keep your default situation to " + "left-align otherwise it becomes difficult to layout multiple items on a same line"); + static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true }; for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) @@ -1045,12 +1147,22 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Filtered Text Input")) { - static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); - static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); + struct TextFilters + { + // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i' + static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) + { + if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) + return 0; + return 1; + } + }; + + static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); + static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); - static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); - struct TextFilters { static int FilterImGuiLetters(ImGuiInputTextCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; + static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); ImGui::Text("Password input"); @@ -1065,9 +1177,11 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Resize Callback")) { // To wire InputText() with std::string or any other custom string type, - // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper using your preferred type. - // See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. - HelpMarker("Demonstrate using ImGuiInputTextFlags_CallbackResize to wire your resizable string type to InputText().\n\nSee misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); + // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper + // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string. + HelpMarker( + "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n" + "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string."); struct Funcs { static int MyResizeCallback(ImGuiInputTextCallbackData* data) @@ -1076,14 +1190,14 @@ static void ShowDemoWindowWidgets() { ImVector* my_str = (ImVector*)data->UserData; IM_ASSERT(my_str->begin() == data->Buf); - my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 + my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 data->Buf = my_str->begin(); } return 0; } - // Tip: Because ImGui:: is a namespace you would typically add your own function into the namespace in your own source files. - // For example, you may add a function called ImGui::InputText(const char* label, MyString* my_str). + // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace. + // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)' static bool MyInputTextMultiline(const char* label, ImVector* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0) { IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); @@ -1092,7 +1206,8 @@ static void ShowDemoWindowWidgets() }; // For this demo we are using ImVector as a string container. - // Note that because we need to store a terminating zero character, our size/capacity are 1 more than usually reported by a typical string class. + // Note that because we need to store a terminating zero character, our size/capacity are 1 more + // than usually reported by a typical string class. static ImVector my_str; if (my_str.empty()) my_str.push_back(0); @@ -1105,7 +1220,8 @@ static void ShowDemoWindowWidgets() } // Plot/Graph widgets are currently fairly limited. - // Consider writing your own plotting widget, or using a third-party one (see "Wiki->Useful Widgets", or github.com/ocornut/imgui/issues/2747) + // Consider writing your own plotting widget, or using a third-party one + // (for third-party Plot widgets, see 'Wiki->Useful Widgets' or https://github.com/ocornut/imgui/labels/plot%2Fgraph) if (ImGui::TreeNode("Plots Widgets")) { static bool animate = true; @@ -1115,13 +1231,14 @@ static void ShowDemoWindowWidgets() ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); // Create a dummy array of contiguous float values to plot - // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter. + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float + // and the sizeof() of your structure in the "stride" parameter. static float values[90] = {}; static int values_offset = 0; static double refresh_time = 0.0; if (!animate || refresh_time == 0.0) refresh_time = ImGui::GetTime(); - while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 hz rate for the demo + while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 Hz rate for the demo { static float phase = 0.0f; values[values_offset] = cosf(phase); @@ -1139,12 +1256,13 @@ static void ShowDemoWindowWidgets() average /= (float)IM_ARRAYSIZE(values); char overlay[32]; sprintf(overlay, "avg %f", average); - ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); } - ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); // Use functions to generate output - // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count. + // FIXME: This is rather awkward because current plot API only pass in indices. + // We probably want an API passing floats and user provide sample rate/count. struct Funcs { static float Sin(void*, int i) { return sinf(i * 0.1f); } @@ -1200,7 +1318,9 @@ static void ShowDemoWindowWidgets() ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions); ImGui::Text("Color widget:"); - ImGui::SameLine(); HelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n"); + ImGui::SameLine(); HelpMarker( + "Click on the colored square to open a color picker.\n" + "CTRL+click on individual component to input value.\n"); ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); ImGui::Text("Color widget HSV with Alpha:"); @@ -1210,7 +1330,10 @@ static void ShowDemoWindowWidgets() ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags); ImGui::Text("Color button with Picker:"); - ImGui::SameLine(); HelpMarker("With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\nWith the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only be used for the tooltip and picker popup."); + ImGui::SameLine(); HelpMarker( + "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n" + "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only " + "be used for the tooltip and picker popup."); ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags); ImGui::Text("Color button with Custom Picker Popup:"); @@ -1222,7 +1345,8 @@ static void ShowDemoWindowWidgets() { for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) { - ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); + ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f, + saved_palette[n].x, saved_palette[n].y, saved_palette[n].z); saved_palette[n].w = 1.0f; // Alpha } saved_palette_init = false; @@ -1257,11 +1381,13 @@ static void ShowDemoWindowWidgets() ImGui::PushID(n); if ((n % 8) != 0) ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); - if (ImGui::ColorButton("##palette", saved_palette[n], ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip, ImVec2(20,20))) + + ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20,20))) color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! - // Allow user to drop colors into each palette entry - // (Note that ColorButton is already a drag source by default, unless using ImGuiColorEditFlags_NoDragDrop) + // Allow user to drop colors into each palette entry. Note that ColorButton() is already a + // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag. if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) @@ -1304,7 +1430,10 @@ static void ShowDemoWindowWidgets() } } ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0"); - ImGui::SameLine(); HelpMarker("ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); + ImGui::SameLine(); HelpMarker( + "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, " + "but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex " + "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions()."); ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0"); ImGui::SameLine(); HelpMarker("User can right-click the picker to change mode."); ImGuiColorEditFlags flags = misc_flags; @@ -1319,22 +1448,29 @@ static void ShowDemoWindowWidgets() if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex; ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL); - ImGui::Text("Programmatically set defaults:"); - ImGui::SameLine(); HelpMarker("SetColorEditOptions() is designed to allow you to set boot-time default.\nWe don't have Push/Pop functions because you can force options on a per-widget basis if needed, and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid encouraging you to persistently save values that aren't forward-compatible."); + ImGui::Text("Set defaults in code:"); + ImGui::SameLine(); HelpMarker( + "SetColorEditOptions() is designed to allow you to set boot-time default.\n" + "We don't have Push/Pop functions because you can force options on a per-widget basis if needed," + "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid" + "encouraging you to persistently save values that aren't forward-compatible."); if (ImGui::Button("Default: Uint8 + HSV + Hue Bar")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar); if (ImGui::Button("Default: Float + HDR + Hue Wheel")) ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel); // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) - static ImVec4 color_stored_as_hsv(0.23f, 1.0f, 1.0f, 1.0f); + static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV! ImGui::Spacing(); ImGui::Text("HSV encoded colors"); - ImGui::SameLine(); HelpMarker("By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); + ImGui::SameLine(); HelpMarker( + "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV" + "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the" + "added benefit that you can manipulate hue values with the picker even when saturation or value are zero."); ImGui::Text("Color widget with InputHSV:"); - ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); - ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_stored_as_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); - ImGui::DragFloat4("Raw HSV values", (float*)&color_stored_as_hsv, 0.01f, 0.0f, 1.0f); + ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float); + ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f); ImGui::TreePop(); } @@ -1350,20 +1486,23 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Data Types")) { - // The DragScalar/InputScalar/SliderScalar functions allow various data types: signed/unsigned int/long long and float/double - // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum to pass the type, - // and passing all arguments by address. + // DragScalar/InputScalar/SliderScalar functions allow various data types + // - signed/unsigned + // - 8/16/32/64-bits + // - integer/float/double + // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + // to pass the type, and passing all arguments by pointer. // This is the reason the test code below creates local variables to hold "zero" "one" etc. for each types. - // In practice, if you frequently use a given type that is not covered by the normal API entry points, you can wrap it - // yourself inside a 1 line function which can take typed argument as value instead of void*, and then pass their address - // to the generic function. For example: + // In practice, if you frequently use a given type that is not covered by the normal API entry points, + // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*, + // and then pass their address to the generic function. For example: // bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld") // { // return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format); // } - // Limits (as helper variables that we can take the address of) - // Note that the SliderScalar function has a maximum usable range of half the natural type maximum, hence the /2 below. + // Setup limits (as helper variables so we can take their address, as explained above) + // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. #ifndef LLONG_MIN ImS64 LLONG_MIN = -9223372036854775807LL - 1; ImS64 LLONG_MAX = 9223372036854775807LL; @@ -1552,8 +1691,9 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Drag and drop in standard widgets")) { // ColorEdit widgets automatically act as drag source and drag target. - // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F to allow your own widgets - // to use colors in their drag and drop interaction. Also see the demo in Color Picker -> Palette demo. + // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + // to allow your own widgets to use colors in their drag and drop interaction. + // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. HelpMarker("You can drag from the colored squares."); static float col1[3] = { 1.0f, 0.0f, 0.2f }; static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; @@ -1574,7 +1714,12 @@ static void ShowDemoWindowWidgets() if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } - static const char* names[9] = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }; + const char* names[9] = + { + "Bobby", "Beatrice", "Betty", + "Brianna", "Barry", "Bernard", + "Bibi", "Blaine", "Bryn" + }; for (int n = 0; n < IM_ARRAYSIZE(names); n++) { ImGui::PushID(n); @@ -1585,8 +1730,12 @@ static void ShowDemoWindowWidgets() // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { - ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); // Set payload to carry the index of our item (could be anything) - if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } // Display preview (could be anything, e.g. when dragging an image we could decide to display the filename and a small preview of the image, etc.) + // Set payload to carry the index of our item (could be anything) + ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int)); + + // Display preview (could be anything, e.g. when dragging an image we could decide to display + // the filename and a small preview of the image, etc.) + if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); } if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); } if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); } ImGui::EndDragDropSource(); @@ -1623,7 +1772,9 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Drag to reorder items (simple)")) { // Simple reordering - HelpMarker("We don't use the drag and drop api at all here! Instead we query when the item is held but not hovered, and order items accordingly."); + HelpMarker( + "We don't use the drag and drop api at all here! " + "Instead we query when the item is held but not hovered, and order items accordingly."); static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }; for (int n = 0; n < IM_ARRAYSIZE(item_names); n++) { @@ -1649,11 +1800,18 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Querying Status (Active/Focused/Hovered etc.)")) { - // Submit an item (various types available) so we can query their status in the following block. + // Select an item type + const char* item_names[] = + { + "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputFloat", + "InputFloat3", "ColorEdit4", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "ListBox" + }; static int item_type = 1; - ImGui::Combo("Item Type", &item_type, "Text\0Button\0Button (w/ repeat)\0Checkbox\0SliderFloat\0InputText\0InputFloat\0InputFloat3\0ColorEdit4\0MenuItem\0TreeNode\0TreeNode (w/ double-click)\0ListBox\0", 20); + ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names)); ImGui::SameLine(); HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions."); + + // Submit selected item item so we can query their status in the code following it. bool ret = false; static bool b = false; static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f }; @@ -1672,10 +1830,10 @@ static void ShowDemoWindowWidgets() if (item_type == 11){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy. if (item_type == 12){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); } - // Display the value of IsItemHovered() and other common item state functions. + // Display the values of IsItemHovered() and other common item state functions. // Note that the ImGuiHoveredFlags_XXX flags can be combined. // Because BulletText is an item itself and that would affect the output of IsItemXXX functions, - // we query every state in a single call to avoid storing them and to simplify the code + // we query every state in a single call to avoid storing them and to simplify the code. ImGui::BulletText( "Return value = %d\n" "IsItemFocused() = %d\n" @@ -1718,7 +1876,7 @@ static void ShowDemoWindowWidgets() static bool embed_all_inside_a_child_window = false; ImGui::Checkbox("Embed everything inside a child window (for additional testing)", &embed_all_inside_a_child_window); if (embed_all_inside_a_child_window) - ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20), true); + ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), true); // Testing IsWindowFocused() function with its various flags. // Note that the ImGuiFocusedFlags_XXX flags can be combined. @@ -1764,7 +1922,7 @@ static void ShowDemoWindowWidgets() ImGui::InputText("dummy", dummy_str, IM_ARRAYSIZE(dummy_str), ImGuiInputTextFlags_ReadOnly); // Calling IsItemHovered() after begin returns the hovered status of the title bar. - // This is useful in particular if you want to create a context menu (with BeginPopupContextItem) associated to the title bar of a window. + // This is useful in particular if you want to create a context menu associated to the title bar of a window. static bool test_window = false; ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window); if (test_window) @@ -1807,7 +1965,9 @@ static void ShowDemoWindowLayout() // Child 1: no border, enable horizontal scrollbar { - ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; ImGui::BeginChild("ChildL", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags); for (int i = 0; i < 100; i++) { @@ -1824,7 +1984,11 @@ static void ShowDemoWindowLayout() // Child 2: rounded border { - ImGuiWindowFlags window_flags = (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_None; + if (disable_mouse_wheel) + window_flags |= ImGuiWindowFlags_NoScrollWithMouse; + if (!disable_menu) + window_flags |= ImGuiWindowFlags_MenuBar; ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); ImGui::BeginChild("ChildR", ImVec2(0, 260), true, window_flags); if (!disable_menu && ImGui::BeginMenuBar()) @@ -1852,10 +2016,11 @@ static void ShowDemoWindowLayout() // Demonstrate a few extra things // - Changing ImGuiCol_ChildBg (which is transparent black in default styles) - // - Using SetCursorPos() to position the child window (because the child window is an item from the POV of the parent window) - // You can also call SetNextWindowPos() to position the child window. The parent window will effectively layout from this position. - // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from the POV of the parent window) - // See "Widgets" -> "Querying Status (Active/Focused/Hovered etc.)" section for more details about this. + // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) + // You can also call SetNextWindowPos() to position the child window. The parent window will effectively + // layout from this position. + // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from + // the POV of the parent window). See 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details. { ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10); ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); @@ -1876,6 +2041,9 @@ static void ShowDemoWindowLayout() { // Use SetNextItemWidth() to set the width of a single upcoming item. // Use PushItemWidth()/PopItemWidth() to set the width of a group of items. + // In real code use you'll probably want to choose width values that are proportional to your font size + // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. + static float f = 0.0f; ImGui::Text("SetNextItemWidth/PushItemWidth(100)"); ImGui::SameLine(); HelpMarker("Fixed width."); @@ -1897,7 +2065,8 @@ static void ShowDemoWindowLayout() ImGui::SetNextItemWidth(-100); ImGui::DragFloat("float##4", &f); - // Demonstrate using PushItemWidth to surround three items. Calling SetNextItemWidth() before each of them would have the same effect. + // Demonstrate using PushItemWidth to surround three items. + // Calling SetNextItemWidth() before each of them would have the same effect. ImGui::Text("SetNextItemWidth/PushItemWidth(-1)"); ImGui::SameLine(); HelpMarker("Align to right edge"); ImGui::PushItemWidth(-1); @@ -1978,7 +2147,8 @@ static void ShowDemoWindowLayout() ImGui::Dummy(button_sz); ImGui::SameLine(); ImGui::Button("B", button_sz); - // Manually wrapping (we should eventually provide this as an automatic layout feature, but for now you can do it manually) + // Manually wrapping + // (we should eventually provide this as an automatic layout feature, but for now you can do it manually) ImGui::Text("Manually wrapping:"); ImGuiStyle& style = ImGui::GetStyle(); int buttons_count = 20; @@ -2049,7 +2219,8 @@ static void ShowDemoWindowLayout() ImGui::Checkbox(names[n], &opened[n]); } - // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): the underlying bool will be set to false when the tab is closed. + // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): + // the underlying bool will be set to false when the tab is closed. if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { for (int n = 0; n < IM_ARRAYSIZE(opened); n++) @@ -2070,7 +2241,10 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Groups")) { - HelpMarker("BeginGroup() basically locks the horizontal position for new line. EndGroup() bundles the whole group so that you can use \"item\" functions such as IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group."); + HelpMarker( + "BeginGroup() basically locks the horizontal position for new line. " + "EndGroup() bundles the whole group so that you can use \"item\" functions such as " + "IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group."); ImGui::BeginGroup(); { ImGui::BeginGroup(); @@ -2093,9 +2267,9 @@ static void ShowDemoWindowLayout() const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); - ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f, size.y)); + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); ImGui::SameLine(); - ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f, size.y)); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y)); ImGui::EndGroup(); ImGui::SameLine(); @@ -2116,8 +2290,9 @@ static void ShowDemoWindowLayout() { { ImGui::BulletText("Text baseline:"); - ImGui::SameLine(); - HelpMarker("This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets."); + ImGui::SameLine(); HelpMarker( + "This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. " + "Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets."); ImGui::Indent(); ImGui::Text("KO Blahblah"); ImGui::SameLine(); @@ -2125,7 +2300,8 @@ static void ShowDemoWindowLayout() HelpMarker("Baseline of button will look misaligned with text.."); // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. - // Because we don't know what's coming after the Text() statement, we need to move the text baseline down by FramePadding.y + // (because we don't know what's coming after the Text() statement, we need to move the text baseline + // down by FramePadding.y ahead of time) ImGui::AlignTextToFramePadding(); ImGui::Text("OK Blahblah"); ImGui::SameLine(); ImGui::Button("Some framed item"); ImGui::SameLine(); @@ -2177,7 +2353,7 @@ static void ShowDemoWindowLayout() ImGui::BulletText("Misc items:"); ImGui::Indent(); - // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button + // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. ImGui::Button("80x80", ImVec2(80, 80)); ImGui::SameLine(); ImGui::Button("50x50", ImVec2(50, 50)); @@ -2190,12 +2366,29 @@ static void ShowDemoWindowLayout() const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; ImGui::Button("Button##1"); ImGui::SameLine(0.0f, spacing); - if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + if (ImGui::TreeNode("Node##1")) + { + // Dummy tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } - ImGui::AlignTextToFramePadding(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit). - bool node_open = ImGui::TreeNode("Node##2");// Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. + // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. + // Otherwise you can use SmallButton() (smaller fit). + ImGui::AlignTextToFramePadding(); + + // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add + // other contents below the node. + bool node_open = ImGui::TreeNode("Node##2"); ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); - if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + if (node_open) + { + // Dummy tree data + for (int i = 0; i < 6; i++) + ImGui::BulletText("Item %d..", i); + ImGui::TreePop(); + } // Bullet ImGui::Button("Button##3"); @@ -2252,8 +2445,9 @@ static void ShowDemoWindowLayout() const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" }; ImGui::TextUnformatted(names[i]); - ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; - bool window_visible = ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, child_flags); + const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0; + const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), true, child_flags); if (ImGui::BeginMenuBar()) { ImGui::TextUnformatted("abc"); @@ -2263,7 +2457,7 @@ static void ShowDemoWindowLayout() ImGui::SetScrollY(scroll_to_off_px); if (scroll_to_pos) ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f); - if (window_visible) // Avoid calling SetScrollHereY when running with culled items + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items { for (int item = 0; item < 100; item++) { @@ -2288,18 +2482,25 @@ static void ShowDemoWindowLayout() // Horizontal scroll functions ImGui::Spacing(); - HelpMarker("Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\nUsing the \"Scroll To Pos\" button above will make the discontinuity at edges visible: scrolling to the top/bottom/left/right-most item will add an additional WindowPadding to reflect on reaching the edge of the list.\n\nBecause the clipping rectangle of most window hides half worth of WindowPadding on the left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the equivalent SetScrollFromPosY(+1) wouldn't."); + HelpMarker( + "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" + "Using the \"Scroll To Pos\" button above will make the discontinuity at edges visible: " + "scrolling to the top/bottom/left/right-most item will add an additional WindowPadding to reflect " + "on reaching the edge of the list.\n\nBecause the clipping rectangle of most window hides half " + "worth of WindowPadding on the left/right, using SetScrollFromPosX(+1) will usually result in " + "clipped text whereas the equivalent SetScrollFromPosY(+1) wouldn't."); ImGui::PushID("##HorizontalScrolling"); for (int i = 0; i < 5; i++) { float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f; ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0); - bool window_visible = ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(-100, child_height), true, child_flags); + ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i); + bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), true, child_flags); if (scroll_to_off) ImGui::SetScrollX(scroll_to_off_px); if (scroll_to_pos) ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f); - if (window_visible) // Avoid calling SetScrollHereY when running with culled items + if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items { for (int item = 0; item < 100; item++) { @@ -2326,16 +2527,21 @@ static void ShowDemoWindowLayout() ImGui::PopID(); // Miscellaneous Horizontal Scrolling Demo - HelpMarker("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\nYou may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); + HelpMarker( + "Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n" + "You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin()."); static int lines = 7; ImGui::SliderInt("Lines", &lines, 1, 15); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); - ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar); + ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30); + ImGui::BeginChild("scrolling", scrolling_child_size, true, ImGuiWindowFlags_HorizontalScrollbar); for (int line = 0; line < lines; line++) { - // Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off - // manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API) + // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() + // If you want to create your own time line for a real application you may be better off manipulating + // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets + // yourself. You may also want to use the lower-level ImDrawList API. int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); for (int n = 0; n < num_buttons; n++) { @@ -2358,13 +2564,21 @@ static void ShowDemoWindowLayout() ImGui::EndChild(); ImGui::PopStyleVar(2); float scroll_x_delta = 0.0f; - ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) { scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; } ImGui::SameLine(); + ImGui::SmallButton("<<"); + if (ImGui::IsItemActive()) + scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("Scroll from code"); ImGui::SameLine(); - ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) { scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; } ImGui::SameLine(); + ImGui::SmallButton(">>"); + if (ImGui::IsItemActive()) + scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x); if (scroll_x_delta != 0.0f) { - ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window) + // Demonstrate a trick: you can use Begin to set yourself in the context of another window + // (here we are already out of your child window) + ImGui::BeginChild("scrolling"); ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); ImGui::EndChild(); } @@ -2465,15 +2679,22 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Clipping")) { static ImVec2 size(100, 100), offset(50, 20); - ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + ImGui::TextWrapped( + "On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. " + "Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. " + "The system is designed to try minimizing both execution and CPU/GPU rendering cost."); ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); ImGui::TextWrapped("(Click and drag)"); ImVec2 pos = ImGui::GetCursorScreenPos(); ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); ImGui::InvisibleButton("##dummy", size); - if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; } + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) + { + offset.x += ImGui::GetIO().MouseDelta.x; + offset.y += ImGui::GetIO().MouseDelta.y; + } ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x + size.x, pos.y + size.y), IM_COL32(90, 90, 120, 255)); - ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x + offset.x, pos.y + offset.y), IM_COL32(255, 255, 255, 255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x + offset.x, pos.y + offset.y), IM_COL32_WHITE, "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); ImGui::TreePop(); } } @@ -2486,10 +2707,12 @@ static void ShowDemoWindowPopups() // The properties of popups windows are: // - They block normal mouse hovering detection outside them. (*) // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. - // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as we are used to with regular Begin() calls. - // User can manipulate the visibility state by calling OpenPopup(). - // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup. - // Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time. + // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as + // we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup(). + // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even + // when normally blocked by a popup. + // Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close + // popups at any time. // Typical use for regular windows: // bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End(); @@ -2501,14 +2724,16 @@ static void ShowDemoWindowPopups() if (ImGui::TreeNode("Popups")) { - ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it."); + ImGui::TextWrapped( + "When a popup is active, it inhibits interacting with windows that are behind the popup. " + "Clicking outside the popup closes it."); static int selected_fish = -1; const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; static bool toggles[] = { true, false, false, false, false }; - // Simple selection popup - // (If you want to show the current selection inside the Button itself, you may want to build a string using the "###" operator to preserve a constant ID with a variable label) + // Simple selection popup (if you want to show the current selection inside the Button itself, + // you may want to build a string using the "###" operator to preserve a constant ID with a variable label) if (ImGui::Button("Select..")) ImGui::OpenPopup("my_select_popup"); ImGui::SameLine(); @@ -2582,7 +2807,8 @@ static void ShowDemoWindowPopups() // if (IsItemHovered() && IsMouseReleased(0)) // OpenPopup(id); // return BeginPopup(id); - // For more advanced uses you may want to replicate and cuztomize this code. This the comments inside BeginPopupContextItem() implementation. + // For more advanced uses you may want to replicate and customize this code. + // See details in BeginPopupContextItem(). static float value = 0.5f; ImGui::Text("Value = %.3f (<-- right-click here)", value); if (ImGui::BeginPopupContextItem("item context menu")) @@ -2594,16 +2820,19 @@ static void ShowDemoWindowPopups() ImGui::EndPopup(); } - // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the Begin call. - // So here we will make it that clicking on the text field with the right mouse button (1) will toggle the visibility of the popup above. + // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the + // Begin() call. So here we will make it that clicking on the text field with the right mouse button (1) + // will toggle the visibility of the popup above. ImGui::Text("(You can also right-click me to open the same popup as above.)"); ImGui::OpenPopupOnItemClick("item context menu", 1); - // When used after an item that has an ID (here the Button), we can skip providing an ID to BeginPopupContextItem(). + // When used after an item that has an ID (e.g.Button), we can skip providing an ID to BeginPopupContextItem(). // BeginPopupContextItem() will use the last item ID as the popup ID. - // In addition here, we want to include your editable label inside the button label. We use the ### operator to override the ID (read FAQ about ID for details) + // In addition here, we want to include your editable label inside the button label. + // We use the ### operator to override the ID (read FAQ about ID for details) static char name[32] = "Label1"; - char buf[64]; sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label + char buf[64]; + sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label ImGui::Button(buf); if (ImGui::BeginPopupContextItem()) { @@ -2620,7 +2849,7 @@ static void ShowDemoWindowPopups() if (ImGui::TreeNode("Modals")) { - ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window."); + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside."); if (ImGui::Button("Delete..")) ImGui::OpenPopup("Delete?"); @@ -2669,8 +2898,9 @@ static void ShowDemoWindowPopups() if (ImGui::Button("Add another modal..")) ImGui::OpenPopup("Stacked 2"); - // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which will close the popup. - // Note that the visibility state of popups is owned by imgui, so the input value of the bool actually doesn't matter here. + // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which + // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value + // of the bool actually doesn't matter here. bool dummy_open = true; if (ImGui::BeginPopupModal("Stacked 2", &dummy_open)) { @@ -2692,9 +2922,12 @@ static void ShowDemoWindowPopups() { ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); ImGui::Separator(); - // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above. - // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here - // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus. + + // Note: As a quirk in this very specific example, we want to differentiate the parent of this menu from the + // parent of the various popup menus above. To do so we are encloding the items in a PushID()/PopID() block + // to make them two different menusets. If we don't, opening any popup above and hovering our menu here would + // open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, + // which is the desired behavior for regular menus. ImGui::PushID("foo"); ImGui::MenuItem("Menu item", "CTRL+M"); if (ImGui::BeginMenu("Menu inside a regular window")) @@ -2876,7 +3109,8 @@ static void ShowDemoWindowColumns() if (ImGui::TreeNode("Horizontal Scrolling")) { ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f)); - ImGui::BeginChild("##ScrollingRegion", ImVec2(0, ImGui::GetFontSize() * 20), false, ImGuiWindowFlags_HorizontalScrollbar); + ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f); + ImGui::BeginChild("##ScrollingRegion", child_size, false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::Columns(10); int ITEMS_COUNT = 2000; ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list @@ -2975,7 +3209,7 @@ static void ShowDemoWindowMisc() ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } - ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); @@ -2985,9 +3219,9 @@ static void ShowDemoWindowMisc() ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. - ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); } - ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); } - ImGui::Text("NavInputs duration:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]); } + ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); } + ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); } + ImGui::Text("NavInputs duration:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]); } ImGui::Button("Hovering me sets the\nkeyboard capture flag"); if (ImGui::IsItemHovered()) @@ -3009,7 +3243,7 @@ static void ShowDemoWindowMisc() ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); ImGui::PushAllowKeyboardFocus(false); ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); - //ImGui::SameLine(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + //ImGui::SameLine(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool) to disable tabbing through certain widgets."); ImGui::PopAllowKeyboardFocus(); ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); ImGui::TreePop(); @@ -3059,19 +3293,27 @@ static void ShowDemoWindowMisc() { ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); for (int button = 0; button < 3; button++) - ImGui::Text("IsMouseDragging(%d):\n w/ default threshold: %d,\n w/ zero threshold: %d\n w/ large threshold: %d", - button, ImGui::IsMouseDragging(button), ImGui::IsMouseDragging(button, 0.0f), ImGui::IsMouseDragging(button, 20.0f)); + { + ImGui::Text("IsMouseDragging(%d):", button); + ImGui::Text(" w/ default threshold: %d,", ImGui::IsMouseDragging(button)); + ImGui::Text(" w/ zero threshold: %d,", ImGui::IsMouseDragging(button, 0.0f)); + ImGui::Text(" w/ large threshold: %d,", ImGui::IsMouseDragging(button, 20.0f)); + } ImGui::Button("Drag Me"); if (ImGui::IsItemActive()) ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor - // Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold) - // You can request a lower or higher threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta() + // Drag operations gets "unlocked" when the mouse has moved past a certain threshold + // (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher + // threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta(). ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); ImVec2 mouse_delta = io.MouseDelta; - ImGui::Text("GetMouseDragDelta(0):\n w/ default threshold: (%.1f, %.1f),\n w/ zero threshold: (%.1f, %.1f)\nMouseDelta: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y, value_raw.x, value_raw.y, mouse_delta.x, mouse_delta.y); + ImGui::Text("GetMouseDragDelta(0):"); + ImGui::Text(" w/ default threshold: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y); + ImGui::Text(" w/ zero threshold: (%.1f, %.1f)", value_raw.x, value_raw.y); + ImGui::Text("io.MouseDelta: (%.1f, %.1f)", mouse_delta.x, mouse_delta.y); ImGui::TreePop(); } @@ -3080,9 +3322,13 @@ static void ShowDemoWindowMisc() const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "NotAllowed" }; IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT); - ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]); + ImGuiMouseCursor current = ImGui::GetMouseCursor(); + ImGui::Text("Current mouse cursor = %d: %s", current, mouse_cursors_names[current]); ImGui::Text("Hover to see mouse cursors:"); - ImGui::SameLine(); HelpMarker("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, otherwise your backend needs to handle it."); + ImGui::SameLine(); HelpMarker( + "Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. " + "If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, " + "otherwise your backend needs to handle it."); for (int i = 0; i < ImGuiMouseCursor_COUNT; i++) { char label[32]; @@ -3121,11 +3367,12 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGuiStyle& style = ImGui::GetStyle(); bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); - ImGui::BeginChildFrame(ImGui::GetID("cfginfos"), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18), ImGuiWindowFlags_NoMove); + ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18); + ImGui::BeginChildFrame(ImGui::GetID("cfg_infos"), child_size, ImGuiWindowFlags_NoMove); if (copy_to_clipboard) { ImGui::LogToClipboard(); - ImGui::LogText("```\n"); // Back quotes will make the text appears without formatting when pasting to GitHub + ImGui::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub } ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM); @@ -3242,7 +3489,8 @@ void ImGui::ShowAboutWindow(bool* p_open) //----------------------------------------------------------------------------- // 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. +// 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. bool ImGui::ShowStyleSelector(const char* label) { static int style_idx = -1; @@ -3324,8 +3572,8 @@ static void NodeFont(ImFont* font) 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) + // 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 & 4095) && font->IsGlyphRangeUnused(base, base + 4095)) { base += 4096 - 256; @@ -3346,8 +3594,8 @@ static void NodeFont(ImFont* font) ImDrawList* draw_list = ImGui::GetWindowDrawList(); 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 - // in order to generate a zero-terminated string. + // 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)); @@ -3376,7 +3624,8 @@ static void NodeFont(ImFont* font) void ImGui::ShowStyleEditor(ImGuiStyle* ref) { - // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to an internally stored reference) + // 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(); static ImGuiStyle ref_saved_style; @@ -3394,14 +3643,14 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ref_saved_style = style; ImGui::ShowFontSelector("Fonts##Selector"); - // Simplified Settings + // 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 window_border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &window_border)) style.WindowBorderSize = window_border ? 1.0f : 0.0f; } + { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } } ImGui::SameLine(); - { bool frame_border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &frame_border)) style.FrameBorderSize = frame_border ? 1.0f : 0.0f; } + { bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } } ImGui::SameLine(); - { bool popup_border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &popup_border)) style.PopupBorderSize = popup_border ? 1.0f : 0.0f; } + { bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } } // Save/Revert button if (ImGui::Button("Save Ref")) @@ -3410,7 +3659,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* 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(); @@ -3447,9 +3698,12 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0")) style.WindowMenuButtonPosition = window_menu_button_position - 1; 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::Text("Safe Area Padding"); ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); + 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::Text("Safe Area Padding"); + ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured)."); ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); ImGui::EndTabItem(); } @@ -3470,7 +3724,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) const ImVec4& col = style.Colors[i]; const char* name = ImGui::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, name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + ImGui::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(); } @@ -3481,10 +3736,13 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) filter.Draw("Filter colors", ImGui::GetFontSize() * 16); static ImGuiColorEditFlags alpha_flags = 0; - if (ImGui::RadioButton("Opaque", alpha_flags == 0)) { alpha_flags = 0; } 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(); - HelpMarker("In the color list:\nLeft-click on colored square to open color picker,\nRight-click to open edit options menu."); + 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(); + HelpMarker( + "In the color list:\n" + "Left-click on colored square to open color picker,\n" + "Right-click to open edit options menu."); ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); ImGui::PushItemWidth(-160); @@ -3497,10 +3755,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::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. + // 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.txt 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]; + 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]; } } ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); ImGui::TextUnformatted(name); @@ -3535,9 +3794,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) HelpMarker("Those are old settings provided for convenience.\nHowever, 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."); static float window_scale = 1.0f; - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.2f")) // scale only this window + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.2f")) // Scale only this window ImGui::SetWindowFontScale(window_scale); - ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.2f"); // scale everything + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.2f"); // Scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); @@ -3545,7 +3804,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::BeginTabItem("Rendering")) { - ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); + ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + ImGui::SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); @@ -3572,7 +3832,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) // Demonstrate creating a "main" fullscreen menu bar and populating it. // Note the difference between BeginMainMenuBar() and BeginMenuBar(): -// - BeginMenuBar() = menu-bar inside current window we Begin()-ed into (the window needs the ImGuiWindowFlags_MenuBar flag) +// - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags_MenuBar flag!) // - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it. static void ShowExampleAppMainMenuBar() { @@ -3597,7 +3857,8 @@ static void ShowExampleAppMainMenuBar() } } -// Note that shortcuts are currently provided for display only (future version will add flags to BeginMenu to process shortcuts) +// Note that shortcuts are currently provided for display only +// (future version will add explicit flags to BeginMenu() to request processing shortcuts) static void ShowExampleMenuFile() { ImGui::MenuItem("(dummy menu)", NULL, false, false); @@ -3679,7 +3940,7 @@ static void ShowExampleMenuFile() //----------------------------------------------------------------------------- // Demonstrate creating a simple console window, with scrolling, filtering, completion and history. -// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions. +// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions. struct ExampleAppConsole { char InputBuf[256]; @@ -3696,10 +3957,12 @@ struct ExampleAppConsole ClearLog(); memset(InputBuf, 0, sizeof(InputBuf)); HistoryPos = -1; + + // "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. Commands.push_back("HELP"); Commands.push_back("HISTORY"); Commands.push_back("CLEAR"); - Commands.push_back("CLASSIFY"); // "classify" is only here to provide an example of "C"+[tab] completing to "CL" and displaying matches. + Commands.push_back("CLASSIFY"); AutoScroll = true; ScrollToBottom = false; AddLog("Welcome to Dear ImGui!"); @@ -3712,10 +3975,10 @@ struct ExampleAppConsole } // Portable helpers - static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } - static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } - static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)str, len); } - static void Strtrim(char* str) { char* str_end = str + strlen(str); while (str_end > str && str_end[-1] == ' ') str_end--; *str_end = 0; } + static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; } + static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; } + static char* Strdup(const char* s) { size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); } + static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; } void ClearLog() { @@ -3745,7 +4008,8 @@ struct ExampleAppConsole return; } - // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. So e.g. IsItemHovered() will return true when hovering the title bar. + // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. + // So e.g. IsItemHovered() will return true when hovering the title bar. // Here we create a context menu only available from the title bar. if (ImGui::BeginPopupContextItem()) { @@ -3754,14 +4018,16 @@ struct ExampleAppConsole ImGui::EndPopup(); } - ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped( + "This example implements a console with basic coloring, completion and history. A more elaborate " + "implementation may want to store entries along with extra data such as timestamp, emitter, etc."); ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); // TODO: display items starting from the bottom if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); if (ImGui::SmallButton("Add Dummy Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); - if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } @@ -3781,25 +4047,38 @@ struct ExampleAppConsole Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); ImGui::Separator(); - const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); // 1 separator, 1 input text - ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); // Leave room for 1 separator + 1 InputText + // Reserve enough left-over height for 1 separator + 1 input text + const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); + ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); if (ImGui::BeginPopupContextWindow()) { if (ImGui::Selectable("Clear")) ClearLog(); ImGui::EndPopup(); } - // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); - // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items. - // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements. - // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with: - // ImGuiListClipper clipper(Items.Size); - // while (clipper.Step()) + // Display every line as a separate entry so we can change their color or add custom widgets. + // If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping + // to only process visible items. The clipper will automatically measure the height of your first item and then + // "seek" to display only items in the visible area. + // To use the clipper we can replace your standard loop: + // for (int i = 0; i < Items.Size; i++) + // With: + // ImGuiListClipper clipper(Items.Size); + // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) - // However, note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list. - // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter, - // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code! - // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list. + // - That your items are evenly spaced (same height) + // - That you have cheap random access to your elements (you can access them given their index, + // without processing all the ones before) + // You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property. + // We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices + // or offsets of items that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage + // to improve this example code! + // If your items are of variable height: + // - Split them into same height items would be simpler and facilitate random-seeking into your list. + // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); @@ -3809,12 +4088,16 @@ struct ExampleAppConsole if (!Filter.PassFilter(item)) continue; - // Normally you would store more information in your item (e.g. make Items[] an array of structure, store color/type etc.) - bool pop_color = false; - if (strstr(item, "[error]")) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); pop_color = true; } - else if (strncmp(item, "# ", 2) == 0) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.8f, 0.6f, 1.0f)); pop_color = true; } + // Normally you would store more information in your item than just a string. + // (e.g. make Items[] an array of structure, store color/type etc.) + ImVec4 color; + bool has_color = false; + if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; } + else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; } + if (has_color) + ImGui::PushStyleColor(ImGuiCol_Text, color); ImGui::TextUnformatted(item); - if (pop_color) + if (has_color) ImGui::PopStyleColor(); } if (copy_to_clipboard) @@ -3830,7 +4113,8 @@ struct ExampleAppConsole // Command-line bool reclaim_focus = false; - if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) + ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory; + if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this)) { char* s = InputBuf; Strtrim(s); @@ -3852,7 +4136,8 @@ struct ExampleAppConsole { AddLog("# %s\n", command_line); - // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. + // Insert into history. First find match and delete it so it can be pushed to the back. + // This isn't trying to be smart or optimal. HistoryPos = -1; for (int i = History.Size-1; i >= 0; i--) if (Stricmp(History[i], command_line) == 0) @@ -3889,7 +4174,8 @@ struct ExampleAppConsole ScrollToBottom = true; } - static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks + // In C++11 you'd be better off using lambdas for this sort of forwarding callbacks + static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) { ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; return console->TextEditCallback(data); @@ -3928,14 +4214,15 @@ struct ExampleAppConsole } else if (candidates.Size == 1) { - // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } else { - // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" + // Multiple matches. Complete as much as we can.. + // So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. int match_len = (int)(word_end - word_start); for (;;) { @@ -4014,8 +4301,8 @@ struct ExampleAppLog { ImGuiTextBuffer Buf; ImGuiTextFilter Filter; - ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines - bool AutoScroll; // Keep scrolling if already at the bottom + ImVector LineOffsets; // Index to lines offset. We maintain this with AddLog() calls. + bool AutoScroll; // Keep scrolling if already at the bottom. ExampleAppLog() { @@ -4082,8 +4369,8 @@ struct ExampleAppLog { // In this example we don't use the clipper when Filter is enabled. // This is because we don't have a random access on the result on our filter. - // A real application processing logs with ten of thousands of entries may want to store the result of search/filter. - // especially if the filtering function is not trivial (e.g. reg-exp). + // A real application processing logs with ten of thousands of entries may want to store the result of + // search/filter.. especially if the filtering function is not trivial (e.g. reg-exp). for (int line_no = 0; line_no < LineOffsets.Size; line_no++) { const char* line_start = buf + LineOffsets[line_no]; @@ -4096,13 +4383,17 @@ struct ExampleAppLog { // The simplest and easy way to display the entire buffer: // ImGui::TextUnformatted(buf_begin, buf_end); - // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward to skip non-visible lines. - // Here we instead demonstrate using the clipper to only process lines that are within the visible area. - // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them on your side is recommended. - // Using ImGuiListClipper requires A) random access into your data, and B) items all being the same height, + // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward + // to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are + // within the visible area. + // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them + // on your side is recommended. Using ImGuiListClipper requires + // - A) random access into your data + // - B) items all being the same height, // both of which we can handle since we an array pointing to the beginning of each line of text. - // When using the filter (in the block of code above) we don't have random access into the data to display anymore, which is why we don't use the clipper. - // Storing or skimming through the search result would make it possible (and would be recommended if you want to search through tens of thousands of entries) + // When using the filter (in the block of code above) we don't have random access into the data to display + // anymore, which is why we don't use the clipper. Storing or skimming through the search result would make + // it possible (and would be recommended if you want to search through tens of thousands of entries). ImGuiListClipper clipper; clipper.Begin(LineOffsets.Size); while (clipper.Step()) @@ -4139,12 +4430,14 @@ static void ShowExampleAppLog(bool* p_open) if (ImGui::SmallButton("[Debug] Add 5 entries")) { static int counter = 0; + const char* categories[3] = { "info", "warn", "error" }; + const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; for (int n = 0; n < 5; n++) { - const char* categories[3] = { "info", "warn", "error" }; - const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; + const char* category = categories[counter % IM_ARRAYSIZE(categories)]; + const char* word = words[counter % IM_ARRAYSIZE(words)]; log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n", - ImGui::GetFrameCount(), categories[counter % IM_ARRAYSIZE(categories)], ImGui::GetTime(), words[counter % IM_ARRAYSIZE(words)]); + ImGui::GetFrameCount(), category, ImGui::GetTime(), word); counter++; } } @@ -4174,43 +4467,47 @@ static void ShowExampleAppLayout(bool* p_open) ImGui::EndMenuBar(); } - // left + // Left static int selected = 0; - ImGui::BeginChild("left pane", ImVec2(150, 0), true); - for (int i = 0; i < 100; i++) { - char label[128]; - sprintf(label, "MyObject %d", i); - if (ImGui::Selectable(label, selected == i)) - selected = i; + ImGui::BeginChild("left pane", ImVec2(150, 0), true); + for (int i = 0; i < 100; i++) + { + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i)) + selected = i; + } + ImGui::EndChild(); } - ImGui::EndChild(); ImGui::SameLine(); - // right - ImGui::BeginGroup(); + // Right + { + ImGui::BeginGroup(); ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us - ImGui::Text("MyObject: %d", selected); - ImGui::Separator(); - if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None)) + { + if (ImGui::BeginTabItem("Description")) { - if (ImGui::BeginTabItem("Description")) - { - ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); - ImGui::EndTabItem(); - } - if (ImGui::BeginTabItem("Details")) - { - ImGui::Text("ID: 0123456789"); - ImGui::EndTabItem(); - } - ImGui::EndTabBar(); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("Details")) + { + ImGui::Text("ID: 0123456789"); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } ImGui::EndChild(); if (ImGui::Button("Revert")) {} ImGui::SameLine(); if (ImGui::Button("Save")) {} - ImGui::EndGroup(); + ImGui::EndGroup(); + } } ImGui::End(); } @@ -4219,6 +4516,47 @@ static void ShowExampleAppLayout(bool* p_open) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- +static void ShowDummyObject(const char* prefix, int uid) +{ + // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. + ImGui::PushID(uid); + ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than framed widgets, here we add vertical spacing to make the tree lines equal high. + bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + ImGui::NextColumn(); + ImGui::AlignTextToFramePadding(); + ImGui::Text("my sailor is rich"); + ImGui::NextColumn(); + if (node_open) + { + static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); // Use field index as identifier. + if (i < 2) + { + ShowDummyObject("Child", 424242); + } + else + { + // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well) + ImGui::AlignTextToFramePadding(); + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet; + ImGui::TreeNodeEx("Field", flags, "Field_%d", i); + ImGui::NextColumn(); + ImGui::SetNextItemWidth(-1); + if (i >= 5) + ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + else + ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::NextColumn(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::PopID(); +} + // Demonstrate create a simple property editor. static void ShowExampleAppPropertyEditor(bool* p_open) { @@ -4229,57 +4567,19 @@ static void ShowExampleAppPropertyEditor(bool* p_open) return; } - HelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API."); + HelpMarker( + "This example shows how you may implement a property editor using two columns.\n" + "All objects/fields data are dummies here.\n" + "Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\n" + "your cursor horizontally instead of using the Columns() API."); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); ImGui::Columns(2); ImGui::Separator(); - struct funcs - { - static void ShowDummyObject(const char* prefix, int uid) - { - ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. - ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high. - bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); - ImGui::NextColumn(); - ImGui::AlignTextToFramePadding(); - ImGui::Text("my sailor is rich"); - ImGui::NextColumn(); - if (node_open) - { - static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; - for (int i = 0; i < 8; i++) - { - ImGui::PushID(i); // Use field index as identifier. - if (i < 2) - { - ShowDummyObject("Child", 424242); - } - else - { - // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well) - ImGui::AlignTextToFramePadding(); - ImGui::TreeNodeEx("Field", ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet, "Field_%d", i); - ImGui::NextColumn(); - ImGui::SetNextItemWidth(-1); - if (i >= 5) - ImGui::InputFloat("##value", &dummy_members[i], 1.0f); - else - ImGui::DragFloat("##value", &dummy_members[i], 0.01f); - ImGui::NextColumn(); - } - ImGui::PopID(); - } - ImGui::TreePop(); - } - ImGui::PopID(); - } - }; - // Iterate dummy objects with dummy members (all the same data) for (int obj_i = 0; obj_i < 3; obj_i++) - funcs::ShowDummyObject("Object", obj_i); + ShowDummyObject("Object", obj_i); ImGui::Columns(1); ImGui::Separator(); @@ -4305,7 +4605,10 @@ static void ShowExampleAppLongText(bool* p_open) static ImGuiTextBuffer log; static int lines = 0; ImGui::Text("Printing unusually long amount of text."); - ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped\0Multiple calls to Text(), not clipped (slow)\0"); + ImGui::Combo("Test type", &test_type, + "Single call to TextUnformatted()\0" + "Multiple calls to Text(), clipped\0" + "Multiple calls to Text(), not clipped (slow)\0"); ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); if (ImGui::Button("Clear")) { log.clear(); lines = 0; } ImGui::SameLine(); @@ -4359,7 +4662,10 @@ static void ShowExampleAppAutoResize(bool* p_open) } static int lines = 10; - ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop."); + ImGui::TextUnformatted( + "Window will resize every-frame to the size of its content.\n" + "Note that you probably don't want to query the window size to\n" + "output your content because that would create a feedback loop."); ImGui::SliderInt("Number of lines", &lines, 1, 20); for (int i = 0; i < lines; i++) ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally @@ -4373,12 +4679,24 @@ static void ShowExampleAppAutoResize(bool* p_open) // Demonstrate creating a window with custom resize constraints. static void ShowExampleAppConstrainedResize(bool* p_open) { - struct CustomConstraints // Helper functions to demonstrate programmatic constraints + struct CustomConstraints { + // Helper functions to demonstrate programmatic constraints static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = (data->DesiredSize.x > data->DesiredSize.y ? data->DesiredSize.x : data->DesiredSize.y); } static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } }; + const char* test_desc[] = + { + "Resize vertical only", + "Resize horizontal only", + "Width > 100, Height > 100", + "Width 400-500", + "Height 400-500", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + static bool auto_resize = false; static int type = 0; static int display_lines = 10; @@ -4393,21 +4711,11 @@ static void ShowExampleAppConstrainedResize(bool* p_open) ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0; if (ImGui::Begin("Example: Constrained Resize", p_open, flags)) { - const char* desc[] = - { - "Resize vertical only", - "Resize horizontal only", - "Width > 100, Height > 100", - "Width 400-500", - "Height 400-500", - "Custom: Always Square", - "Custom: Fixed Steps (100)", - }; if (ImGui::Button("200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine(); if (ImGui::Button("500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine(); if (ImGui::Button("800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); } ImGui::SetNextItemWidth(200); - ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); + ImGui::Combo("Constraint", &type, test_desc, IM_ARRAYSIZE(test_desc)); ImGui::SetNextItemWidth(200); ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100); ImGui::Checkbox("Auto-resize", &auto_resize); @@ -4421,7 +4729,8 @@ static void ShowExampleAppConstrainedResize(bool* p_open) // [SECTION] Example App: Simple Overlay / ShowExampleAppSimpleOverlay() //----------------------------------------------------------------------------- -// Demonstrate creating a simple static window with no decoration + a context-menu to choose which corner of the screen to use. +// Demonstrate creating a simple static window with no decoration +// + a context-menu to choose which corner of the screen to use. static void ShowExampleAppSimpleOverlay(bool* p_open) { const float DISTANCE = 10.0f; @@ -4434,7 +4743,10 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); } ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background - if (ImGui::Begin("Example: Simple overlay", p_open, (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; + if (corner != -1) + window_flags |= ImGuiWindowFlags_NoMove; + if (ImGui::Begin("Example: Simple overlay", p_open, window_flags)) { ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)"); ImGui::Separator(); @@ -4461,7 +4773,8 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) //----------------------------------------------------------------------------- // Demonstrate using "##" and "###" in identifiers to manipulate ID generation. -// This apply to all regular items as well. Read FAQ section "How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs." for details. +// This apply to all regular items as well. +// Read FAQ section "How can I have multiple widgets with the same label?" for details. static void ShowExampleAppWindowTitles(bool*) { // By default, Windows are uniquely identified by their title. @@ -4500,10 +4813,10 @@ static void ShowExampleAppCustomRendering(bool* p_open) return; } - // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. - // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. - // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) - // In this example we are not using the maths operators! + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of + // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your + // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not + // exposed outside (to avoid messing with your types) In this example we are not using the maths operators! ImDrawList* draw_list = ImGui::GetWindowDrawList(); if (ImGui::BeginTabBar("##TabBar")) @@ -4517,17 +4830,19 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Text("Gradients"); ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); { - ImVec2 p = ImGui::GetCursorScreenPos(); + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - draw_list->AddRectFilledMultiColor(p, ImVec2(p.x + gradient_size.x, p.y + gradient_size.y), col_a, col_b, col_b, col_a); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient1", gradient_size); } { - ImVec2 p = ImGui::GetCursorScreenPos(); + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)); ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - draw_list->AddRectFilledMultiColor(p, ImVec2(p.x + gradient_size.x, p.y + gradient_size.y), col_a, col_b, col_b, col_a); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient2", gradient_size); } @@ -4598,23 +4913,25 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); - // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() - // But you can also draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). - // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). - ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! - ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available - if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; - if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; - draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(50, 50, 50, 255), IM_COL32(50, 50, 60, 255), IM_COL32(60, 60, 70, 255), IM_COL32(50, 50, 60, 255)); - draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), IM_COL32(255, 255, 255, 255)); + // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use + // IsItemHovered(). But you can also draw directly and poll mouse/keyboard by yourself. + // You can manipulate the cursor using GetCursorPos() and SetCursorPos(). + // If you only use the ImDrawList API, you can notify the owner window of its extends with SetCursorPos(max). + ImVec2 canvas_p = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f; + if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f; + draw_list->AddRectFilledMultiColor(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), IM_COL32(50, 50, 50, 255), IM_COL32(50, 50, 60, 255), IM_COL32(60, 60, 70, 255), IM_COL32(50, 50, 60, 255)); + draw_list->AddRect(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), IM_COL32(255, 255, 255, 255)); bool adding_preview = false; - ImGui::InvisibleButton("canvas", canvas_size); - ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); + ImGui::InvisibleButton("canvas", canvas_sz); + ImVec2 mouse_pos_global = ImGui::GetIO().MousePos; + ImVec2 mouse_pos_canvas = ImVec2(mouse_pos_global.x - canvas_p.x, mouse_pos_global.y - canvas_p.y); if (adding_line) { adding_preview = true; - points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_canvas); if (!ImGui::IsMouseDown(0)) adding_line = adding_preview = false; } @@ -4622,7 +4939,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) { if (!adding_line && ImGui::IsMouseClicked(0)) { - points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_canvas); adding_line = true; } if (ImGui::IsMouseClicked(1) && !points.empty()) @@ -4632,9 +4949,11 @@ static void ShowExampleAppCustomRendering(bool* p_open) points.pop_back(); } } - draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), true); // clip lines within the canvas (if we resize it, etc.) + + // Draw all lines in the canvas (with a clipping rectangle so they don't stray out of it). + draw_list->PushClipRect(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), true); for (int i = 0; i < points.Size - 1; i += 2) - draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i + 1].x, canvas_pos.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); + draw_list->AddLine(ImVec2(canvas_p.x + points[i].x, canvas_p.y + points[i].y), ImVec2(canvas_p.x + points[i + 1].x, canvas_p.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); draw_list->PopClipRect(); if (adding_preview) points.pop_back(); @@ -4672,12 +4991,12 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Simplified structure to mimic a Document model struct MyDocument { - const char* Name; // Document title - bool Open; // Set when the document is open (in this demo, we keep an array of all available documents to simplify the demo) - bool OpenPrev; // Copy of Open from last update. - bool Dirty; // Set when the document has been modified - bool WantClose; // Set when the document - ImVec4 Color; // An arbitrary variable associated to the document + const char* Name; // Document title + bool Open; // Set when open (we keep an array of all available documents to simplify demo code!) + bool OpenPrev; // Copy of Open from last update. + bool Dirty; // Set when the document has been modified + bool WantClose; // Set when the document + ImVec4 Color; // An arbitrary variable associated to the document MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f,1.0f,1.0f,1.0f)) { @@ -4741,10 +5060,11 @@ struct ExampleAppDocuments }; // [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. -// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, as opposed -// to clicking on the regular tab closing button) and stops being submitted, it will take a frame for the tab bar to notice its absence. -// During this frame there will be a gap in the tab bar, and if the tab that has disappeared was the selected one, the tab bar -// will report no selected tab during the frame. This will effectively give the impression of a flicker for one frame. +// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, +// as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for +// the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has +// disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively +// give the impression of a flicker for one frame. // We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. // Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag. static void NotifyOfDocumentsClosedElsewhere(ExampleAppDocuments& app) From 673d6df85f21e8c252bc22f4e64ed46b8423cdee Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 11:38:45 +0200 Subject: [PATCH 018/959] Demo: Clamping font scale. Added helpers in demo. Comments. Update sponsors. (#3206) --- docs/README.md | 2 +- imgui.cpp | 2 ++ imgui_demo.cpp | 34 ++++++++++++++++++++++++++-------- 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/docs/README.md b/docs/README.md index 72ebea3d..341bdcbe 100644 --- a/docs/README.md +++ b/docs/README.md @@ -194,7 +194,7 @@ Ongoing Dear ImGui development is financially supported by users and private spo - [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui/) *Double-chocolate and Salty caramel sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [DotEmu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) +- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors). diff --git a/imgui.cpp b/imgui.cpp index 86af727d..f84fb0d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6610,6 +6610,7 @@ ImVec2 ImGui::GetFontTexUvWhitePixel() void ImGui::SetWindowFontScale(float scale) { + IM_ASSERT(scale > 0.0f); ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; @@ -6818,6 +6819,7 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() ImGuiContext& g = *GImGui; // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() + // One possible reason leading to this assert is that your back-ends update inputs _AFTER_ NewFrame(). const ImGuiKeyModFlags expected_key_mod_flags = GetMergedKeyModFlags(); IM_ASSERT(g.IO.KeyMods == expected_key_mod_flags && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(expected_key_mod_flags); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3b2ceee1..42f0844a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -114,6 +114,7 @@ Index of this file: #define IM_NEWLINE "\n" #endif +// Helpers #if defined(_MSC_VER) && !defined(snprintf) #define snprintf _snprintf #endif @@ -121,6 +122,14 @@ Index of this file: #define vsnprintf _vsnprintf #endif +// Helpers macros +// We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste, +// but making an exception here as those are largely simplifying code... +// In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo. +#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B)) +#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) +#define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V)) + //----------------------------------------------------------------------------- // [SECTION] Forward Declarations, Helpers //----------------------------------------------------------------------------- @@ -709,7 +718,7 @@ static void ShowDemoWindowWidgets() // You may retain selection state inside or outside your objects in whatever format you see fit. // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end /// of the loop. May be a pointer to your own node type, etc. - static int selection_mask = (1 << 2); + static int selection_mask = (1 << 2); int node_clicked = -1; for (int i = 0; i < 6; i++) { @@ -1294,7 +1303,7 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::Text("Progress Bar"); - float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress; + float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); char buf[32]; sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); @@ -2379,7 +2388,7 @@ static void ShowDemoWindowLayout() ImGui::AlignTextToFramePadding(); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add - // other contents below the node. + // other contents below the node. bool node_open = ImGui::TreeNode("Node##2"); ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); if (node_open) @@ -3792,11 +3801,20 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::TreePop(); } - HelpMarker("Those are old settings provided for convenience.\nHowever, 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."); + // 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). + const float MIN_SCALE = 0.3f; + const float MAX_SCALE = 2.0f; + HelpMarker( + "Those are old settings provided for convenience.\n" + "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; - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.2f")) // Scale only this window - ImGui::SetWindowFontScale(window_scale); - ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.2f"); // Scale everything + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale only this window + ImGui::SetWindowFontScale(IM_MAX(window_scale, MIN_SCALE)); + if (ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale everything + io.FontGlobalScale = IM_MAX(io.FontGlobalScale, MIN_SCALE); ImGui::PopItemWidth(); ImGui::EndTabItem(); @@ -4682,7 +4700,7 @@ static void ShowExampleAppConstrainedResize(bool* p_open) struct CustomConstraints { // Helper functions to demonstrate programmatic constraints - static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = (data->DesiredSize.x > data->DesiredSize.y ? data->DesiredSize.x : data->DesiredSize.y); } + static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y); } static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } }; From 0679e0567764d5b3362628bdf1e75c608b2a1b8b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 12:14:49 +0200 Subject: [PATCH 019/959] Internals: Added code in TempInputScalar() to clamp values, NOT used by stock Drag/Float (#3209, #1829, #946, #413) --- imgui_internal.h | 8 ++++- imgui_widgets.cpp | 80 ++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 75 insertions(+), 13 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 46cca946..f20e9d52 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -715,6 +715,11 @@ struct IMGUI_API ImRect bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } }; +struct ImGuiDataTypeTempStorage +{ + ImU8 Data[8]; // Can fit any data up to ImGuiDataType_COUNT +}; + // Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). struct ImGuiDataTypeInfo { @@ -1893,11 +1898,12 @@ namespace ImGui IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format); IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); IMGUI_API bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* p_data, const char* format); + IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 200c43e4..d1509479 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1669,6 +1669,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa // - DataTypeFormatString() // - DataTypeApplyOp() // - DataTypeApplyOpFromText() +// - DataTypeClamp() // - GetMinimumStepAtDecimalPrecision // - RoundScalarWithFormat<>() //------------------------------------------------------------------------- @@ -1820,11 +1821,9 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b return false; // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all. - IM_ASSERT(data_type < ImGuiDataType_COUNT); - int data_backup[2]; - const ImGuiDataTypeInfo* type_info = ImGui::DataTypeGetInfo(data_type); - IM_ASSERT(type_info->Size <= sizeof(data_backup)); - memcpy(data_backup, p_data, type_info->Size); + const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type); + ImGuiDataTypeTempStorage data_backup; + memcpy(&data_backup, p_data, type_info->Size); if (format == NULL) format = type_info->ScanFmt; @@ -1896,7 +1895,35 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b IM_ASSERT(0); } - return memcmp(data_backup, p_data, type_info->Size) != 0; + return memcmp(&data_backup, p_data, type_info->Size) != 0; +} + +template +static bool ClampBehaviorT(T* v, T v_min, T v_max) +{ + if (*v < v_min) { *v = v_min; return true; } + if (*v > v_max) { *v = v_max; return true; } + return false; +} + +bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max) +{ + switch (data_type) + { + case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, *(const ImS8* )p_min, *(const ImS8* )p_max); + case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, *(const ImU8* )p_min, *(const ImU8* )p_max); + case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, *(const ImS16* )p_min, *(const ImS16* )p_max); + case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, *(const ImU16* )p_min, *(const ImU16* )p_max); + case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, *(const ImS32* )p_min, *(const ImS32* )p_max); + case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, *(const ImU32* )p_min, *(const ImU32* )p_max); + case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, *(const ImS64* )p_min, *(const ImS64* )p_max); + case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, *(const ImU64* )p_min, *(const ImU64* )p_max); + case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, *(const float* )p_min, *(const float* )p_max); + case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, *(const double*)p_min, *(const double*)p_max); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return false; } static float GetMinimumStepAtDecimalPrecision(int decimal_precision) @@ -2148,8 +2175,10 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, } } } + + // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active || temp_input_start) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -2599,8 +2628,10 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat } } } + + // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active || temp_input_start) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -2899,7 +2930,21 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* return value_changed; } -bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format) +// Note that Drag/Slider functions are currently NOT forwarding the min/max values clamping values! +// This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. +// However this may not be ideal for all uses, as some user code may break on out of bound values. +// In the future we should add flags to Slider/Drag to specify how to enforce min/max values with CTRL+Click. +// See GitHub issues #1829 and #3209 +// In the meanwhile, you can easily "wrap" those functions to enforce clamping, using wrapper functions, e.g. +// bool SliderFloatClamp(const char* label, float* v, float v_min, float v_max) +// { +// float v_backup = *v; +// if (!SliderFloat(label, v, v_min, v_max)) +// return false; +// *v = ImClamp(*v, v_min, v_max); +// return v_backup != *v; +// } +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) { ImGuiContext& g = *GImGui; @@ -2911,10 +2956,21 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); - bool value_changed = TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags); - if (value_changed) + bool value_changed = false; + if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) { - value_changed = DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL); + // Backup old value + size_t data_type_size = DataTypeGetInfo(data_type)->Size; + ImGuiDataTypeTempStorage data_backup; + memcpy(&data_backup, p_data, data_type_size); + + // Apply new value (or operations) then clamp + DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL); + if (p_clamp_min && p_clamp_max) + DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); + + // Only mark as edited if new value is different + value_changed = memcmp(&data_type, p_data, data_type_size) != 0; if (value_changed) MarkItemEdited(id); } From 510f301c9fef49b7a2194fa7795f0e70af0a1e23 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 18:58:29 +0200 Subject: [PATCH 020/959] Internals: Removed seemingly unnecessary size_on_first_use arg to CreateNewWindow(), extracted code into ApplyWindowSettings. --- docs/TODO.txt | 1 - imgui.cpp | 23 ++++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 474b5ce5..75438a6a 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -26,7 +26,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window: GetWindowSize() returns (0,0) when not calculated? (#1045) - window: investigate better auto-positioning for new windows. - window: top most window flag? (#2574) - - window: the size_on_first_use path of Begin() can probably be removed - window/size: manually triggered auto-fit (double-click on grip) shouldn't resize window down to viewport size? - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - window/child: background options for child windows, border option (disable rounding). diff --git a/imgui.cpp b/imgui.cpp index f84fb0d2..f7f0e1b9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -908,7 +908,7 @@ static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock static void SetCurrentWindow(ImGuiWindow* window); static void FindHoveredWindow(); -static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); +static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list); @@ -4874,7 +4874,15 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name) return FindWindowByID(id); } -static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) +static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) +{ + window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y)); + if (settings->Size.x > 0 && settings->Size.y > 0) + window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y)); + window->Collapsed = settings->Collapsed; +} + +static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); @@ -4894,12 +4902,8 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl // Retrieve settings from .ini file window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); - window->Pos = ImVec2(settings->Pos.x, settings->Pos.y); - window->Collapsed = settings->Collapsed; - if (settings->Size.x > 0 && settings->Size.y > 0) - size = ImVec2(settings->Size.x, settings->Size.y); + ApplyWindowSettings(window, settings); } - window->Size = window->SizeFull = ImFloor(size); window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) @@ -5446,10 +5450,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) ImGuiWindow* window = FindWindowByName(name); const bool window_just_created = (window == NULL); if (window_just_created) - { - ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. - window = CreateNewWindow(name, size_on_first_use, flags); - } + window = CreateNewWindow(name, flags); // Automatically disable manual moving/resizing when NoInputs is set if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) From 9ee442d3f0bc72e5172539659bfd542e6bafc9cc Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 18:00:11 +0200 Subject: [PATCH 021/959] Metrics: Added a "Settings" section with some details about persistent ini settings. InputText: Assert early on null buffer. --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 38 ++++++++++++++++++++++++++++++++++++++ imgui_widgets.cpp | 1 + 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 96cadc9b..116ee156 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,12 +50,13 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Metrics: Added a "Settings" section with some details about persistent ini settings. - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) -- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData +- Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] diff --git a/imgui.cpp b/imgui.cpp index f7f0e1b9..38185fae 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10282,6 +10282,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } + static void NodeWindowSettings(ImGuiWindowSettings* settings) + { + ImGui::Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d", + settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed); + } + static void NodeTabBar(ImGuiTabBar* tab_bar) { // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. @@ -10398,6 +10404,38 @@ void ImGui::ShowMetricsWindow(bool* p_open) } #endif // #define IMGUI_HAS_DOCK + // Settings + if (ImGui::TreeNode("Settings")) + { + if (ImGui::SmallButton("Save to disk")) + ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); + ImGui::SameLine(); + if (g.IO.IniFilename) + ImGui::Text("\"%s\"", g.IO.IniFilename); + else + ImGui::TextUnformatted(""); + ImGui::Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer); + if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) + { + for (int n = 0; n < g.SettingsHandlers.Size; n++) + ImGui::TextUnformatted(g.SettingsHandlers[n].TypeName); + ImGui::TreePop(); + } + if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) + { + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + Funcs::NodeWindowSettings(settings); + ImGui::TreePop(); + } + if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) + { + char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); + ImGui::InputTextMultiline("##Ini", buf, g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + // Misc Details if (ImGui::TreeNode("Internal state")) { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d1509479..71153c20 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3523,6 +3523,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (window->SkipItems) return false; + IM_ASSERT(buf != NULL && buf_size >= 0); IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) From b6a04d77500327a33a1b1de776aa67096075380b Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 21:10:10 +0200 Subject: [PATCH 022/959] Settings: Added Clear Settings in Metrics. (#2188) + Preserve last loaded copy in internal buffer used for save (so it can be browsed easily). --- imgui.cpp | 56 ++++++++++++++++++++++++++++++++++++------------ imgui_internal.h | 1 + 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 38185fae..d5f6d8b3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9598,6 +9598,19 @@ void ImGui::LogButtons() //----------------------------------------------------------------------------- // [SECTION] SETTINGS //----------------------------------------------------------------------------- +// - UpdateSettings() [Internal] +// - MarkIniSettingsDirty() [Internal] +// - CreateNewWindowSettings() [Internal] +// - FindWindowSettings() [Internal] +// - FindOrCreateWindowSettings() [Internal] +// - FindSettingsHandler() [Internal] +// - ClearIniSettings() [Internal] +// - LoadIniSettingsFromDisk() +// - LoadIniSettingsFromMemory() +// - SaveIniSettingsToDisk() +// - SaveIniSettingsToMemory() +// - WindowSettingsHandler_***() [Internal] +//----------------------------------------------------------------------------- // Called by NewFrame() void ImGui::UpdateSettings() @@ -9680,16 +9693,6 @@ ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) return CreateNewWindowSettings(name); } -void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) -{ - size_t file_data_size = 0; - char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); - if (!file_data) - return; - LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); - IM_FREE(file_data); -} - ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) { ImGuiContext& g = *GImGui; @@ -9700,6 +9703,25 @@ ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) return NULL; } +void ImGui::ClearIniSettings() +{ + ImGuiContext& g = *GImGui; + g.SettingsIniData.clear(); + for (int i = 0; i != g.Windows.Size; i++) + g.Windows[i]->SettingsOffset = -1; + g.SettingsWindows.clear(); +} + +void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) +{ + size_t file_data_size = 0; + char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); + if (!file_data) + return; + LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); + IM_FREE(file_data); +} + // Zero-tolerance, no error reporting, cheap .ini parsing void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) { @@ -9711,10 +9733,11 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. if (ini_size == 0) ini_size = strlen(ini_data); - char* buf = (char*)IM_ALLOC(ini_size + 1); - char* buf_end = buf + ini_size; + g.SettingsIniData.Buf.resize((int)ini_size + 1); + char* const buf = g.SettingsIniData.Buf.Data; + char* const buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); - buf[ini_size] = 0; + buf_end[0] = 0; void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; @@ -9752,8 +9775,10 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); } } - IM_FREE(buf); g.SettingsLoaded = true; + + // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) + memcpy(buf, ini_data, ini_size); } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) @@ -10407,6 +10432,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Settings if (ImGui::TreeNode("Settings")) { + if (ImGui::SmallButton("Clear")) + ImGui::ClearIniSettings(); + ImGui::SameLine(); if (ImGui::SmallButton("Save to disk")) ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); ImGui::SameLine(); diff --git a/imgui_internal.h b/imgui_internal.h index f20e9d52..67ad424a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1718,6 +1718,7 @@ namespace ImGui // Settings IMGUI_API void MarkIniSettingsDirty(); IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); + IMGUI_API void ClearIniSettings(); IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id); IMGUI_API ImGuiWindowSettings* FindOrCreateWindowSettings(const char* name); From d33021d82816a9e256301331e7ec84fd4cd7ddc2 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 21:28:17 +0200 Subject: [PATCH 023/959] Settings: Made it possible to load window .ini data mid-frame. Added clear and post-read handlers. (#2573) --- imgui.cpp | 40 ++++++++++++++++++++++++++++++++++++---- imgui_internal.h | 5 ++++- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d5f6d8b3..6fb27a5b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -917,6 +917,8 @@ static void AddWindowToSortBuffer(ImVector* out_sorted static ImRect GetViewportRect(); // Settings +static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); +static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); @@ -3941,6 +3943,8 @@ void ImGui::Initialize(ImGuiContext* context) ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Window"; ini_handler.TypeHash = ImHashStr("Window"); + ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll; + ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen; ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine; ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll; @@ -9707,9 +9711,9 @@ void ImGui::ClearIniSettings() { ImGuiContext& g = *GImGui; g.SettingsIniData.clear(); - for (int i = 0; i != g.Windows.Size; i++) - g.Windows[i]->SettingsOffset = -1; - g.SettingsWindows.clear(); + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ClearAllFn) + g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]); } void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) @@ -9727,7 +9731,8 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); - IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); + //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()"); + //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. @@ -9779,6 +9784,11 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) memcpy(buf, ini_data, ini_size); + + // Call post-read handlers + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ApplyAllFn) + g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]); } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) @@ -9814,11 +9824,33 @@ const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) return g.SettingsIniData.c_str(); } +static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Windows.Size; i++) + g.Windows[i]->SettingsOffset = -1; + g.SettingsWindows.clear(); +} + +// Apply to existing windows (if any) +static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->WantApply) + { + if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) + ApplyWindowSettings(window, settings); + settings->WantApply = false; + } +} + static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); if (!settings) settings = ImGui::CreateNewWindowSettings(name); + settings->WantApply = true; return (void*)settings; } diff --git a/imgui_internal.h b/imgui_internal.h index 67ad424a..3c209974 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -824,8 +824,9 @@ struct ImGuiWindowSettings ImVec2ih Pos; ImVec2ih Size; bool Collapsed; + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = false; } + ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = WantApply = false; } char* GetName() { return (char*)(this + 1); } }; @@ -833,6 +834,8 @@ struct ImGuiSettingsHandler { const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHashStr(TypeName) + void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' From 51e568f9dc1dec33017376a6fa6a71b9ced6cda9 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 22:46:06 +0200 Subject: [PATCH 024/959] Docking: Fix to allow basic reload of non-docking .ini data (following d33021d8) + moved settings blocks --- imgui.cpp | 113 ++++++++++++++++++++++------------------------- imgui_internal.h | 2 +- 2 files changed, 55 insertions(+), 60 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 27c71337..f0e76d5a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5206,6 +5206,8 @@ ImGuiWindow* ImGui::FindWindowByName(const char* name) static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) { + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + window->ViewportPos = main_viewport->Pos; if (settings->ViewportId) { window->ViewportId = settings->ViewportId; @@ -5217,7 +5219,6 @@ static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settin window->Collapsed = settings->Collapsed; window->DockId = settings->DockId; window->DockOrder = settings->DockOrder; - } static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) @@ -5233,6 +5234,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. ImGuiViewport* main_viewport = ImGui::GetMainViewport(); window->Pos = main_viewport->Pos + ImVec2(60, 60); + window->ViewportPos = main_viewport->Pos; // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. if (!(flags & ImGuiWindowFlags_NoSavedSettings)) @@ -5241,7 +5243,6 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) // Retrieve settings from .ini file window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); - window->ViewportPos = main_viewport->Pos; ApplyWindowSettings(window, settings); } window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values @@ -10564,8 +10565,6 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].ApplyAllFn) g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]); - - DockContextOnLoadSettings(&g); } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) @@ -10624,9 +10623,10 @@ static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandl static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { - ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); - if (!settings) - settings = ImGui::CreateNewWindowSettings(name); + ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name); + ImGuiID id = settings->ID; + *settings = ImGuiWindowSettings(); + settings->ID = id; settings->WantApply = true; return (void*)settings; } @@ -11683,6 +11683,7 @@ namespace ImGui static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count); static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id); + static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); @@ -11700,7 +11701,6 @@ namespace ImGui //----------------------------------------------------------------------------- // - DockContextInitialize() // - DockContextShutdown() -// - DockContextOnLoadSettings() // - DockContextClearNodes() // - DockContextRebuildNodes() // - DockContextUpdateUndocking() @@ -11726,6 +11726,7 @@ void ImGui::DockContextInitialize(ImGuiContext* ctx) ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Docking"; ini_handler.TypeHash = ImHashStr("Docking"); + ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; @@ -11743,13 +11744,6 @@ void ImGui::DockContextShutdown(ImGuiContext* ctx) g.DockContext = NULL; } -void ImGui::DockContextOnLoadSettings(ImGuiContext* ctx) -{ - ImGuiDockContext* dc = ctx->DockContext; - DockContextPruneUnusedSettingsNodes(ctx); - DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); -} - void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references) { IM_UNUSED(ctx); @@ -14251,6 +14245,7 @@ void ImGui::DockBuilderRemoveNode(ImGuiID node_id) DockContextRemoveNode(ctx, node, true); } +// root_id = 0 to remove all, root_id != 0 to remove child of given node. void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) { ImGuiContext* ctx = GImGui; @@ -14821,6 +14816,7 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) // - DockSettingsRenameNodeReferences() // - DockSettingsRemoveNodeReferences() // - DockSettingsFindNodeSettings() +// - DockSettingsHandler_ApplyAll() // - DockSettingsHandler_ReadOpen() // - DockSettingsHandler_ReadLine() // - DockSettingsHandler_DockNodeToSettings() @@ -14871,6 +14867,15 @@ static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* return NULL; } +static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + // Prune settings at boot time only + ImGuiDockContext* dc = ctx->DockContext; + if (ctx->Windows.Size == 0) + DockContextPruneUnusedSettingsNodes(ctx); + DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); +} + static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { if (strcmp(name, "Data") != 0) @@ -15690,52 +15695,17 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Details for Docking #ifdef IMGUI_HAS_DOCK - if (ImGui::TreeNode("Docking")) + if (ImGui::TreeNode("Dock nodes")) { ImGuiDockContext* dc = g.DockContext; ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes); - - if (ImGui::TreeNode("Dock nodes")) - { - if (ImGui::SmallButton("Clear settings")) { DockContextClearNodes(&g, 0, true); } - ImGui::SameLine(); - if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } - for (int n = 0; n < dc->Nodes.Data.Size; n++) - if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) - if (node->IsRootNode()) - Funcs::NodeDockNode(node, "Node"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Settings")) - { - if (ImGui::SmallButton("Refresh")) - SaveIniSettingsToMemory(); - ImGui::SameLine(); - if (ImGui::SmallButton("Save to disk")) - SaveIniSettingsToDisk(g.IO.IniFilename); - ImGui::Separator(); - ImGui::Text("Docked Windows:"); - for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) - if (settings->DockId != 0) - ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId); - ImGui::Separator(); - ImGui::Text("Dock Nodes:"); - for (int n = 0; n < dc->SettingsNodes.Size; n++) - { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n]; - const char* selected_tab_name = NULL; - if (settings->SelectedWindowId) - { - if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowId)) - selected_tab_name = window->Name; - else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowId)) - selected_tab_name = window_settings->GetName(); - } - ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedWindowId, selected_tab_name ? selected_tab_name : settings->SelectedWindowId ? "N/A" : ""); - } - ImGui::TreePop(); - } + if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } + ImGui::SameLine(); + if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) + if (node->IsRootNode()) + Funcs::NodeDockNode(node, "Node"); ImGui::TreePop(); } #endif // #define IMGUI_HAS_DOCK @@ -15746,6 +15716,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear")) ImGui::ClearIniSettings(); ImGui::SameLine(); + if (ImGui::SmallButton("Save to memory")) + ImGui::SaveIniSettingsToMemory(); + ImGui::SameLine(); if (ImGui::SmallButton("Save to disk")) ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); ImGui::SameLine(); @@ -15757,7 +15730,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) { for (int n = 0; n < g.SettingsHandlers.Size; n++) - ImGui::TextUnformatted(g.SettingsHandlers[n].TypeName); + ImGui::BulletText("%s", g.SettingsHandlers[n].TypeName); ImGui::TreePop(); } if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) @@ -15766,6 +15739,28 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeWindowSettings(settings); ImGui::TreePop(); } + if (ImGui::TreeNode("SettingsDocking", "Settings packed data: Docking")) + { + ImGui::Text("In SettingsWindows:"); + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->DockId != 0) + ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId); + ImGui::Text("In SettingsNodes:"); + for (int n = 0; n < g.DockContext->SettingsNodes.Size; n++) + { + ImGuiDockNodeSettings* settings = &g.DockContext->SettingsNodes[n]; + const char* selected_tab_name = NULL; + if (settings->SelectedWindowId) + { + if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowId)) + selected_tab_name = window->Name; + else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowId)) + selected_tab_name = window_settings->GetName(); + } + ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedWindowId, selected_tab_name ? selected_tab_name : settings->SelectedWindowId ? "N/A" : ""); + } + ImGui::TreePop(); + } if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); diff --git a/imgui_internal.h b/imgui_internal.h index a3b76688..2f43e9b5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2058,7 +2058,7 @@ namespace ImGui IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id = 0, ImGuiDockNodeFlags flags = 0); IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_persistent_docking_references = true); - IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the root. + IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the remaining root node (node_id). IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); IMGUI_API ImGuiID DockBuilderSplitNode(ImGuiID node_id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir); // Create 2 child nodes in this parent node. From 574ff0a280d09b5115c489f5e204ba1af13c9c0a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 23:28:29 +0200 Subject: [PATCH 025/959] Docking, Settings: Allow reload of settings data at runtime. (#2573) --- imgui.cpp | 24 ++++++++++++++++++++++-- imgui_internal.h | 3 ++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f0e76d5a..08090188 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10520,6 +10520,12 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) memcpy(buf, ini_data, ini_size); buf_end[0] = 0; + // Call pre-read handlers + // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ReadInitFn) + g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]); + void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; @@ -11683,6 +11689,7 @@ namespace ImGui static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count); static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id); + static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); @@ -11726,9 +11733,11 @@ void ImGui::DockContextInitialize(ImGuiContext* ctx) ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Docking"; ini_handler.TypeHash = ImHashStr("Docking"); - ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; + ini_handler.ClearAllFn = DockSettingsHandler_ClearAll; + ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; g.SettingsHandlers.push_back(ini_handler); } @@ -11752,7 +11761,8 @@ void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear DockBuilderRemoveNodeChildNodes(root_id); } -// This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) { IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); @@ -14867,6 +14877,15 @@ static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* return NULL; } +// Clear settings data +static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiDockContext* dc = ctx->DockContext; + dc->SettingsNodes.clear(); + DockContextClearNodes(ctx, 0, true); +} + +// Recreate dones based on settings data static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { // Prune settings at boot time only @@ -14874,6 +14893,7 @@ static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettings if (ctx->Windows.Size == 0) DockContextPruneUnusedSettingsNodes(ctx); DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); + DockContextBuildAddWindowsToNodes(ctx, 0); } static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) diff --git a/imgui_internal.h b/imgui_internal.h index 2f43e9b5..bf443573 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -855,9 +855,10 @@ struct ImGuiSettingsHandler const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHashStr(TypeName) void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data - void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) + void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order) void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' void* UserData; From 53ebd6a02f92390e402edbc1ebaf445432066e08 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 23:51:47 +0200 Subject: [PATCH 026/959] Metrics: Added Table settings block. --- imgui.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 6fb27a5b..14be81f6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10487,6 +10487,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeWindowSettings(settings); ImGui::TreePop(); } +#ifdef IMGUI_HAS_TABLE + if (ImGui::TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) + { + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + Funcs::NodeTableSettings(settings); + ImGui::TreePop(); + } +#endif if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); From c0d5b3f55a977fb3909bd80d90018a47fa5b0191 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 23:58:35 +0200 Subject: [PATCH 027/959] Fix to facilitate branch merges --- imgui.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index 14be81f6..97950b63 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10487,6 +10487,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeWindowSettings(settings); ImGui::TreePop(); } + #ifdef IMGUI_HAS_TABLE if (ImGui::TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) { @@ -10495,6 +10496,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::TreePop(); } #endif + +#ifdef IMGUI_HAS_DOCK +#endif + if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); From 3aa1684129646a7ad688d13139688beea70f27a3 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 15:59:39 +0200 Subject: [PATCH 028/959] Comments --- imgui.cpp | 9 ++++---- imgui_internal.h | 56 +++++++++++++++++++++++++----------------------- 2 files changed, 34 insertions(+), 31 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 97950b63..11d9a79d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4281,7 +4281,7 @@ void ImGui::Render() // Add ImDrawList to render ImGuiWindow* windows_to_render_top_most[2]; windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; - windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingList : NULL); + windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL); for (int n = 0; n != g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; @@ -5590,7 +5590,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. bool window_title_visible_elsewhere = false; - if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB + if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB window_title_visible_elsewhere = true; if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) { @@ -6628,6 +6628,7 @@ void ImGui::ActivateItem(ImGuiID id) g.NavNextActivateId = id; } +// Note: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there. void ImGui::PushFocusScope(ImGuiID id) { ImGuiContext& g = *GImGui; @@ -9067,8 +9068,8 @@ void ImGui::NavUpdateWindowingOverlay() if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) return; - if (g.NavWindowingList == NULL) - g.NavWindowingList = FindWindowByName("###NavWindowingList"); + if (g.NavWindowingListWindow == NULL) + g.NavWindowingListWindow = FindWindowByName("###NavWindowingList"); SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 3c209974..5a1fa677 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -14,9 +14,9 @@ Index of this file: // STB libraries includes // Context pointer // Generic helpers -// Misc data structures +// Flags, enums and data structures // Main imgui context -// Tab bar, tab item +// Tab bar, Tab item // Internal API */ @@ -431,7 +431,7 @@ struct IMGUI_API ImChunkStream }; //----------------------------------------------------------------------------- -// Misc data structures +// Flags, enums and data structures //----------------------------------------------------------------------------- enum ImGuiButtonFlags_ @@ -1011,7 +1011,7 @@ struct ImGuiNextItemData }; //----------------------------------------------------------------------------- -// Tabs +// Tab bar, Tab item //----------------------------------------------------------------------------- struct ImGuiShrinkWidthItem @@ -1111,7 +1111,7 @@ struct ImGuiContext // Gamepad/keyboard Navigation ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow' ImGuiID NavId; // Focused item for navigation - ImGuiID NavFocusScopeId; + ImGuiID NavFocusScopeId; // Identify a selection scope (selection code often wants to "clear other items" when landing on an item of the selection set) ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem() ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0 ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0 @@ -1133,8 +1133,8 @@ struct ImGuiContext bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest bool NavInitRequest; // Init request for appearing window to select first item bool NavInitRequestFromMove; - ImGuiID NavInitResultId; - ImRect NavInitResultRectRel; + ImGuiID NavInitResultId; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) + ImRect NavInitResultRectRel; // Init request result rectangle (relative to parent window) bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items bool NavMoveRequest; // Move request for this frame ImGuiNavMoveFlags NavMoveRequestFlags; @@ -1146,10 +1146,10 @@ struct ImGuiContext ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) - // Navigation: Windowing (CTRL+TAB, holding Menu button + directional pads to move/resize) - ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed top-most. - ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f - ImGuiWindow* NavWindowingList; + // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) + ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! + ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. + ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents float NavWindowingTimer; float NavWindowingHighlightAlpha; bool NavWindowingToggleLayer; @@ -1226,8 +1226,8 @@ struct ImGuiContext ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries // Capture/Logging - bool LogEnabled; - ImGuiLogType LogType; + bool LogEnabled; // Currently capturing + ImGuiLogType LogType; // Capture target ImFileHandle LogFile; // If != NULL log to stdout/ file ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. float LogLinePosY; @@ -1237,7 +1237,7 @@ struct ImGuiContext int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. // Debug Tools - bool DebugItemPickerActive; + bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker()) ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this id // Misc @@ -1322,7 +1322,7 @@ struct ImGuiContext NavMoveRequestKeyMods = ImGuiKeyModFlags_None; NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; - NavWindowingTarget = NavWindowingTargetAnim = NavWindowingList = NULL; + NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; NavWindowingToggleLayer = false; @@ -1563,8 +1563,8 @@ struct IMGUI_API ImGuiWindow ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space - bool MemoryCompacted; - int MemoryDrawListIdxCapacity; + bool MemoryCompacted; // Set when window extraneous data have been garbage collected + int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy int MemoryDrawListVtxCapacity; public: @@ -1736,7 +1736,7 @@ namespace ImGui IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect); // Basic Accessors - inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } + inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } // Get ID of last item (~~ often same ImGui::GetID(label) beforehand) inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemStatusFlags; } inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } @@ -1747,7 +1747,7 @@ namespace ImGui IMGUI_API void SetHoveredID(ImGuiID id); IMGUI_API void KeepAliveID(ImGuiID id); IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function. - IMGUI_API void PushOverrideID(ImGuiID id); // Push given value at the top of the ID stack (whereas PushID combines old and new hashes) + IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes) // Basic Helpers for widget code IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f); @@ -1762,27 +1762,27 @@ namespace ImGui IMGUI_API void PushMultiItemsWidths(int components, float width_full); IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled); IMGUI_API void PopItemFlag(); - IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) + IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly) IMGUI_API ImVec2 GetContentRegionMaxAbs(); IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); // Logging/Capture - IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. - IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer + IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. + IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer // Popups, Modals, Tooltips IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags); IMGUI_API void OpenPopupEx(ImGuiID id); IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); - IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id within current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! + IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id at current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default); - // Navigation + // Gamepad/Keyboard Navigation IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); IMGUI_API bool NavMoveRequestButNoResultYet(); IMGUI_API void NavMoveRequestCancel(); @@ -1795,8 +1795,10 @@ namespace ImGui IMGUI_API void SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id); IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel); - // Focus scope (WIP) - IMGUI_API void PushFocusScope(ImGuiID id); // Note: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there. + // Focus Scope (WIP) + // This is generally used to identify a selection set (multiple of which may be in the same window), as selection + // patterns generally need to react (e.g. clear selection) when landing on an item of the set. + IMGUI_API void PushFocusScope(ImGuiID id); IMGUI_API void PopFocusScope(); inline ImGuiID GetFocusScopeID() { ImGuiContext& g = *GImGui; return g.NavFocusScopeId; } @@ -1816,7 +1818,7 @@ namespace ImGui IMGUI_API void ClearDragDrop(); IMGUI_API bool IsDragDropPayloadBeingAccepted(); - // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables api) + // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). IMGUI_API void EndColumns(); // close columns IMGUI_API void PushColumnClipRect(int column_index); From f466cfc2caa4851ab6c99df825ea04eedabfc91f Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 16:21:00 +0200 Subject: [PATCH 029/959] Internals: shuffling some sections, added index. --- imgui_internal.h | 396 +++++++++++++++++++++++++---------------------- 1 file changed, 208 insertions(+), 188 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5a1fa677..5e8d063b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -9,15 +9,21 @@ /* Index of this file: -// Header mess -// Forward declarations -// STB libraries includes -// Context pointer -// Generic helpers -// Flags, enums and data structures -// Main imgui context -// Tab bar, Tab item -// Internal API + +// [SECTION] Header mess +// [SECTION] Forward declarations +// [SECTION] Context pointer +// [SECTION] STB libraries includes +// [SECTION] Macros +// [SECTION] Generic helpers +// [SECTION] ImDrawList support +// [SECTION] Misc flags, enums and data structures +// [SECTION] Settings support +// [SECTION] ImGuiContext (main imgui context) +// [SECTION] ImGuiWindowTempData, ImGuiWindow +// [SECTION] Tab bar, Tab item +// [SECTION] Internal API +// [SECTION] Test Engine Hooks (imgui_test_engine) */ @@ -25,7 +31,7 @@ Index of this file: #ifndef IMGUI_DISABLE //----------------------------------------------------------------------------- -// Header mess +// [SECTION] Header mess //----------------------------------------------------------------------------- #ifndef IMGUI_VERSION @@ -46,8 +52,8 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h -#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h #pragma clang diagnostic ignored "-Wold-style-cast" #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" @@ -57,20 +63,20 @@ Index of this file: #endif #elif defined(__GNUC__) #pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif // Legacy defines -#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 +#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 #error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS #endif -#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 +#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 #error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS #endif //----------------------------------------------------------------------------- -// Forward declarations +// [SECTION] Forward declarations //----------------------------------------------------------------------------- struct ImBitVector; // Store 1-bit per value @@ -115,8 +121,17 @@ typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // F typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() +//----------------------------------------------------------------------------- +// [SECTION] Context pointer +// See implementation of this variable in imgui.cpp for comments and details. +//----------------------------------------------------------------------------- + +#ifndef GImGui +extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer +#endif + //------------------------------------------------------------------------- -// STB libraries includes +// [SECTION] STB libraries includes //------------------------------------------------------------------------- namespace ImStb @@ -134,15 +149,7 @@ namespace ImStb } // namespace ImStb //----------------------------------------------------------------------------- -// Context pointer -//----------------------------------------------------------------------------- - -#ifndef GImGui -extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer -#endif - -//----------------------------------------------------------------------------- -// Macros +// [SECTION] Macros //----------------------------------------------------------------------------- // Debug Logging @@ -192,32 +199,50 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IMGUI_CDECL #endif +// Debug Tools +// Use 'Metrics->Tools->Item Picker' to break into the call-stack of a specific item. +#ifndef IM_DEBUG_BREAK +#if defined(__clang__) +#define IM_DEBUG_BREAK() __builtin_debugtrap() +#elif defined (_MSC_VER) +#define IM_DEBUG_BREAK() __debugbreak() +#else +#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger! +#endif +#endif // #ifndef IM_DEBUG_BREAK + //----------------------------------------------------------------------------- -// Generic helpers +// [SECTION] Generic helpers // Note that the ImXXX helpers functions are lower-level than ImGui functions. // ImGui functions or the ImGui context are never called/used from other ImXXX functions. //----------------------------------------------------------------------------- -// - Helpers: Misc +// - Helpers: Hashing +// - Helpers: Sorting // - Helpers: Bit manipulation // - Helpers: String, Formatting // - Helpers: UTF-8 <> wchar conversions // - Helpers: ImVec2/ImVec4 operators // - Helpers: Maths // - Helpers: Geometry -// - Helpers: Bit arrays +// - Helper: ImVec1 +// - Helper: ImVec2ih +// - Helper: ImRect +// - Helper: ImBitArray // - Helper: ImBitVector // - Helper: ImPool<> // - Helper: ImChunkStream<> //----------------------------------------------------------------------------- -// Helpers: Misc -#define ImQsort qsort +// Helpers: Hashing IMGUI_API ImU32 ImHashData(const void* data, size_t data_size, ImU32 seed = 0); IMGUI_API ImU32 ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS static inline ImU32 ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68] #endif +// Helpers: Sorting +#define ImQsort qsort + // Helpers: Color Blending IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); @@ -286,7 +311,6 @@ static inline ImU64 ImFileGetSize(ImFileHandle) static inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } static inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; } #endif - #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef FILE* ImFileHandle; IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode); @@ -354,7 +378,61 @@ IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& inline float ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; } IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy); -// Helpers: Bit arrays +// Helper: ImVec1 (1D vector) +// (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) +struct ImVec1 +{ + float x; + ImVec1() { x = 0.0f; } + ImVec1(float _x) { x = _x; } +}; + +// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) +struct ImVec2ih +{ + short x, y; + ImVec2ih() { x = y = 0; } + ImVec2ih(short _x, short _y) { x = _x; y = _y; } + explicit ImVec2ih(const ImVec2& rhs) { x = (short)rhs.x; y = (short)rhs.y; } +}; + +// Helper: ImRect (2D axis aligned bounding-box) +// NB: we can't rely on ImVec2 math operators being available here! +struct IMGUI_API ImRect +{ + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right + + ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} + ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} + ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} + ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} + + ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); } + float GetWidth() const { return Max.x - Min.x; } + float GetHeight() const { return Max.y - Min.y; } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } + void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } + void TranslateX(float dx) { Min.x += dx; Max.x += dx; } + void TranslateY(float dy) { Min.y += dy; Max.y += dy; } + void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. + void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. + void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } + bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } +}; + +// Helper: ImBitArray inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; } inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; } inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; } @@ -431,7 +509,50 @@ struct IMGUI_API ImChunkStream }; //----------------------------------------------------------------------------- -// Flags, enums and data structures +// [SECTION] ImDrawList support +//----------------------------------------------------------------------------- + +// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 12 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 +#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp((int)((IM_PI * 2.0f) / ImAcos(((_RAD) - (_MAXERROR)) / (_RAD))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) + +// ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path. +#ifndef IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER +#define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 +#endif + +// Data shared between all ImDrawList instances +// You may want to create your own instance of this if you want to use 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 + ImFont* Font; // Current/default font (optional, for simplified AddText overload) + float FontSize; // Current/default font size (optional, for simplified AddText overload) + float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() + float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc + ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() + ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) + + // [Internal] Lookup tables + ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas + ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) + + ImDrawListSharedData(); + void SetCircleSegmentMaxError(float max_error); +}; + +struct ImDrawDataBuilder +{ + ImVector Layers[2]; // Global layers for: regular, tooltip + + void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); } + void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); } + IMGUI_API void FlattenIntoSingleLayer(); +}; + +//----------------------------------------------------------------------------- +// [SECTION] Misc flags, enums and data structures //----------------------------------------------------------------------------- enum ImGuiButtonFlags_ @@ -662,59 +783,6 @@ enum ImGuiPopupPositionPolicy ImGuiPopupPositionPolicy_ComboBox }; -// 1D vector (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) -struct ImVec1 -{ - float x; - ImVec1() { x = 0.0f; } - ImVec1(float _x) { x = _x; } -}; - -// 2D vector (half-size integer) -struct ImVec2ih -{ - short x, y; - ImVec2ih() { x = y = 0; } - ImVec2ih(short _x, short _y) { x = _x; y = _y; } - explicit ImVec2ih(const ImVec2& rhs) { x = (short)rhs.x; y = (short)rhs.y; } -}; - -// 2D axis aligned bounding-box -// NB: we can't rely on ImVec2 math operators being available here -struct IMGUI_API ImRect -{ - ImVec2 Min; // Upper-left - ImVec2 Max; // Lower-right - - ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} - ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} - ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} - ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} - - ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); } - ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); } - float GetWidth() const { return Max.x - Min.x; } - float GetHeight() const { return Max.y - Min.y; } - ImVec2 GetTL() const { return Min; } // Top-left - ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right - ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left - ImVec2 GetBR() const { return Max; } // Bottom-right - bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } - bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; } - bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } - void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } - void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } - void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } - void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } - void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } - void TranslateX(float dx) { Min.x += dx; Max.x += dx; } - void TranslateY(float dy) { Min.y += dy; Max.y += dy; } - void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. - void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. - void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } - bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } -}; - struct ImGuiDataTypeTempStorage { ImU8 Data[8]; // Can fit any data up to ImGuiDataType_COUNT @@ -815,35 +883,6 @@ struct IMGUI_API ImGuiInputTextState void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } }; -// Windows data saved in imgui.ini file -// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. -// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) -struct ImGuiWindowSettings -{ - ImGuiID ID; - ImVec2ih Pos; - ImVec2ih Size; - bool Collapsed; - bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - - ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = WantApply = false; } - char* GetName() { return (char*)(this + 1); } -}; - -struct ImGuiSettingsHandler -{ - const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' - ImGuiID TypeHash; // == ImHashStr(TypeName) - void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data - void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) - void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" - void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry - void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' - void* UserData; - - ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } -}; - // Storage for current popup stack struct ImGuiPopupData { @@ -902,45 +941,6 @@ struct ImGuiColumns } }; -// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 12 -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 -#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp((int)((IM_PI * 2.0f) / ImAcos(((_RAD) - (_MAXERROR)) / (_RAD))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) - -// ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path. -#ifndef IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER -#define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 -#endif - -// Data shared between all ImDrawList instances -// You may want to create your own instance of this if you want to use 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 - ImFont* Font; // Current/default font (optional, for simplified AddText overload) - float FontSize; // Current/default font size (optional, for simplified AddText overload) - float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() - float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc - ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() - ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) - - // [Internal] Lookup tables - ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas - ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) - - ImDrawListSharedData(); - void SetCircleSegmentMaxError(float max_error); -}; - -struct ImDrawDataBuilder -{ - ImVector Layers[2]; // Global layers for: regular, tooltip - - void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); } - void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); } - IMGUI_API void FlattenIntoSingleLayer(); -}; - struct ImGuiNavMoveResult { ImGuiWindow* Window; // Best candidate window @@ -1010,27 +1010,56 @@ struct ImGuiNextItemData inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; } // Also cleared manually by ItemAdd()! }; +struct ImGuiShrinkWidthItem +{ + int Index; + float Width; +}; + +struct ImGuiPtrOrIndex +{ + void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool. + int Index; // Usually index in a main pool. + + ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } + ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } +}; + //----------------------------------------------------------------------------- -// Tab bar, Tab item +// [SECTION] Settings support //----------------------------------------------------------------------------- -struct ImGuiShrinkWidthItem +// Windows data saved in imgui.ini file +// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. +// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) +struct ImGuiWindowSettings { - int Index; - float Width; + ImGuiID ID; + ImVec2ih Pos; + ImVec2ih Size; + bool Collapsed; + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + + ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = WantApply = false; } + char* GetName() { return (char*)(this + 1); } }; -struct ImGuiPtrOrIndex +struct ImGuiSettingsHandler { - void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool. - int Index; // Usually index in a main pool. + const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' + ImGuiID TypeHash; // == ImHashStr(TypeName) + void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) + void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" + void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry + void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' + void* UserData; - ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } - ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } + ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- -// Main Dear ImGui context +// [SECTION] ImGuiContext (main imgui context) //----------------------------------------------------------------------------- struct ImGuiContext @@ -1386,7 +1415,7 @@ struct ImGuiContext }; //----------------------------------------------------------------------------- -// ImGuiWindow +// [SECTION] ImGuiWindowTempData, ImGuiWindow //----------------------------------------------------------------------------- // Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. @@ -1580,12 +1609,12 @@ public: ImGuiID GetIDFromRectangle(const ImRect& r_abs); // We don't use g.FontSize because the window may be != g.CurrentWidow. - ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } - float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } - float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; } - ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } - float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; } - ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } + float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } + float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } + float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } }; // Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data. @@ -1602,7 +1631,7 @@ struct ImGuiItemHoveredDataBackup }; //----------------------------------------------------------------------------- -// Tab bar, tab item +// [SECTION] Tab bar, Tab item //----------------------------------------------------------------------------- // Extend ImGuiTabBarFlags_ @@ -1672,8 +1701,8 @@ struct ImGuiTabBar }; //----------------------------------------------------------------------------- -// Internal API -// No guarantee of forward compatibility here. +// [SECTION] Internal API +// No guarantee of forward compatibility here! //----------------------------------------------------------------------------- namespace ImGui @@ -1944,19 +1973,10 @@ IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); 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); -// Debug Tools -// Use 'Metrics->Tools->Item Picker' to break into the call-stack of a specific item. -#ifndef IM_DEBUG_BREAK -#if defined(__clang__) -#define IM_DEBUG_BREAK() __builtin_debugtrap() -#elif defined (_MSC_VER) -#define IM_DEBUG_BREAK() __debugbreak() -#else -#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger! -#endif -#endif // #ifndef IM_DEBUG_BREAK +//----------------------------------------------------------------------------- +// [SECTION] Test Engine Hooks (imgui_test_engine) +//----------------------------------------------------------------------------- -// Test Engine Hooks (imgui_tests) //#define IMGUI_ENABLE_TEST_ENGINE #ifdef IMGUI_ENABLE_TEST_ENGINE extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); From 5f752a5ba9e835e681015375fbbb99262036eec6 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 16:30:14 +0200 Subject: [PATCH 030/959] Internals: shuffling some sections (2) --- imgui_internal.h | 191 ++++++++++++++++++++++++----------------------- 1 file changed, 98 insertions(+), 93 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5e8d063b..ca9518c5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -17,7 +17,8 @@ Index of this file: // [SECTION] Macros // [SECTION] Generic helpers // [SECTION] ImDrawList support -// [SECTION] Misc flags, enums and data structures +// [SECTION] Widgets support: flags, enums, data structures +// [SECTION] Columns support // [SECTION] Settings support // [SECTION] ImGuiContext (main imgui context) // [SECTION] ImGuiWindowTempData, ImGuiWindow @@ -552,9 +553,45 @@ struct ImDrawDataBuilder }; //----------------------------------------------------------------------------- -// [SECTION] Misc flags, enums and data structures +// [SECTION] Widgets support: flags, enums, data structures //----------------------------------------------------------------------------- +// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). +// This is going to be exposed in imgui.h when stabilized enough. +enum ImGuiItemFlags_ +{ + ImGuiItemFlags_None = 0, + ImGuiItemFlags_NoTabStop = 1 << 0, // false + ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. + ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211 + ImGuiItemFlags_NoNav = 1 << 3, // false + ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false + ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window + ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) + ImGuiItemFlags_Default_ = 0 +}; + +// Storage for LastItem data +enum ImGuiItemStatusFlags_ +{ + ImGuiItemStatusFlags_None = 0, + ImGuiItemStatusFlags_HoveredRect = 1 << 0, + ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, + ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues. + ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. + ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. + ImGuiItemStatusFlags_Deactivated = 1 << 6 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. + +#ifdef IMGUI_ENABLE_TEST_ENGINE + , // [imgui_tests only] + ImGuiItemStatusFlags_Openable = 1 << 10, // + ImGuiItemStatusFlags_Opened = 1 << 11, // + ImGuiItemStatusFlags_Checkable = 1 << 12, // + ImGuiItemStatusFlags_Checked = 1 << 13 // +#endif +}; + enum ImGuiButtonFlags_ { ImGuiButtonFlags_None = 0, @@ -597,17 +634,6 @@ enum ImGuiDragFlags_ ImGuiDragFlags_Vertical = 1 << 0 }; -enum ImGuiColumnsFlags_ -{ - // Default: 0 - ImGuiColumnsFlags_None = 0, - ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers - ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers - ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns - ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window - ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. -}; - // Extend ImGuiSelectableFlags_ enum ImGuiSelectableFlagsPrivate_ { @@ -634,42 +660,6 @@ enum ImGuiSeparatorFlags_ ImGuiSeparatorFlags_SpanAllColumns = 1 << 2 }; -// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin(). -// This is going to be exposed in imgui.h when stabilized enough. -enum ImGuiItemFlags_ -{ - ImGuiItemFlags_None = 0, - ImGuiItemFlags_NoTabStop = 1 << 0, // false - ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings. - ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211 - ImGuiItemFlags_NoNav = 1 << 3, // false - ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false - ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window - ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) - ImGuiItemFlags_Default_ = 0 -}; - -// Storage for LastItem data -enum ImGuiItemStatusFlags_ -{ - ImGuiItemStatusFlags_None = 0, - ImGuiItemStatusFlags_HoveredRect = 1 << 0, - ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, - ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) - ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues. - ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. - ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. - ImGuiItemStatusFlags_Deactivated = 1 << 6 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. - -#ifdef IMGUI_ENABLE_TEST_ENGINE - , // [imgui_tests only] - ImGuiItemStatusFlags_Openable = 1 << 10, // - ImGuiItemStatusFlags_Opened = 1 << 11, // - ImGuiItemStatusFlags_Checkable = 1 << 12, // - ImGuiItemStatusFlags_Checked = 1 << 13 // -#endif -}; - enum ImGuiTextFlags_ { ImGuiTextFlags_None = 0, @@ -897,50 +887,6 @@ struct ImGuiPopupData ImGuiPopupData() { PopupId = 0; Window = SourceWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; } }; -struct ImGuiColumnData -{ - float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) - float OffsetNormBeforeResize; - ImGuiColumnsFlags Flags; // Not exposed - ImRect ClipRect; - - ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; } -}; - -struct ImGuiColumns -{ - ImGuiID ID; - ImGuiColumnsFlags Flags; - bool IsFirstFrame; - bool IsBeingResized; - int Current; - int Count; - float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x - float LineMinY, LineMaxY; - float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() - float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() - ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns() - ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns() - ImVector Columns; - ImDrawListSplitter Splitter; - - ImGuiColumns() { Clear(); } - void Clear() - { - ID = 0; - Flags = ImGuiColumnsFlags_None; - IsFirstFrame = false; - IsBeingResized = false; - Current = 0; - Count = 1; - OffMinX = OffMaxX = 0.0f; - LineMinY = LineMaxY = 0.0f; - HostCursorPosY = 0.0f; - HostCursorMaxPosX = 0.0f; - Columns.clear(); - } -}; - struct ImGuiNavMoveResult { ImGuiWindow* Window; // Best candidate window @@ -1025,6 +971,65 @@ struct ImGuiPtrOrIndex ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } }; +//----------------------------------------------------------------------------- +// [SECTION] Columns support +//----------------------------------------------------------------------------- + +enum ImGuiColumnsFlags_ +{ + // Default: 0 + ImGuiColumnsFlags_None = 0, + ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers + ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers + ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns + ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window + ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. +}; + +struct ImGuiColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + float OffsetNormBeforeResize; + ImGuiColumnsFlags Flags; // Not exposed + ImRect ClipRect; + + ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; } +}; + +struct ImGuiColumns +{ + ImGuiID ID; + ImGuiColumnsFlags Flags; + bool IsFirstFrame; + bool IsBeingResized; + int Current; + int Count; + float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x + float LineMinY, LineMaxY; + float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() + float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() + ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns() + ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns() + ImVector Columns; + ImDrawListSplitter Splitter; + + ImGuiColumns() { Clear(); } + void Clear() + { + ID = 0; + Flags = ImGuiColumnsFlags_None; + IsFirstFrame = false; + IsBeingResized = false; + Current = 0; + Count = 1; + OffMinX = OffMaxX = 0.0f; + LineMinY = LineMaxY = 0.0f; + HostCursorPosY = 0.0f; + HostCursorMaxPosX = 0.0f; + Columns.clear(); + } +}; + //----------------------------------------------------------------------------- // [SECTION] Settings support //----------------------------------------------------------------------------- From 4f33dd15c4e28d161de406c18f2ebea649ba6b7d Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 16:55:37 +0200 Subject: [PATCH 031/959] Internals: stand-in for large branches to facilitate merging. --- imgui_internal.h | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ca9518c5..1fcd64de 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -20,9 +20,13 @@ Index of this file: // [SECTION] Widgets support: flags, enums, data structures // [SECTION] Columns support // [SECTION] Settings support +// [SECTION] Multi-select support +// [SECTION] Docking support +// [SECTION] Viewport support // [SECTION] ImGuiContext (main imgui context) // [SECTION] ImGuiWindowTempData, ImGuiWindow -// [SECTION] Tab bar, Tab item +// [SECTION] Tab bar, Tab item support +// [SECTION] Table support // [SECTION] Internal API // [SECTION] Test Engine Hooks (imgui_test_engine) @@ -1030,6 +1034,30 @@ struct ImGuiColumns } }; +//----------------------------------------------------------------------------- +// [SECTION] Multi-select support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_MULTI_SELECT +// +#endif // #ifdef IMGUI_HAS_MULTI_SELECT + +//----------------------------------------------------------------------------- +// [SECTION] Docking support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_DOCK +// +#endif // #ifdef IMGUI_HAS_DOCK + +//----------------------------------------------------------------------------- +// [SECTION] Viewport support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_VIEWPORT +// +#endif // #ifdef IMGUI_HAS_VIEWPORT + //----------------------------------------------------------------------------- // [SECTION] Settings support //----------------------------------------------------------------------------- @@ -1636,7 +1664,7 @@ struct ImGuiItemHoveredDataBackup }; //----------------------------------------------------------------------------- -// [SECTION] Tab bar, Tab item +// [SECTION] Tab bar, Tab item support //----------------------------------------------------------------------------- // Extend ImGuiTabBarFlags_ @@ -1705,6 +1733,14 @@ struct ImGuiTabBar } }; +//----------------------------------------------------------------------------- +// [SECTION] Table support +//----------------------------------------------------------------------------- + +#ifdef IMGUI_HAS_TABLE +// +#endif // #ifdef IMGUI_HAS_TABLE + //----------------------------------------------------------------------------- // [SECTION] Internal API // No guarantee of forward compatibility here! From 1e7672acf46a81e36b3cf35734c015326dd97d58 Mon Sep 17 00:00:00 2001 From: Ivan Zinkevich Date: Thu, 7 May 2020 23:50:51 +0300 Subject: [PATCH 032/959] Backends: DX12: Fixed OBJECT_DELETED_WHILE_STILL_IN_USE on viewport resizing. (#3210) Tested with detaching/attaching a viewport and resizing it. DX12 debug layer is clean. --- examples/imgui_impl_dx12.cpp | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index bbe026e4..b10e8c65 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -846,22 +846,26 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) } } +static void ImGui_WaitForPendingOperations(ImGuiViewportDataDx12* data) +{ + HRESULT hr = S_FALSE; + if (data && data->CommandQueue && data->Fence && data->FenceEvent) + { + hr = data->CommandQueue->Signal(data->Fence, ++data->FenceSignaledValue); + IM_ASSERT(hr == S_OK); + ::WaitForSingleObject(data->FenceEvent, 0); // Reset any forgotten waits + hr = data->Fence->SetEventOnCompletion(data->FenceSignaledValue, data->FenceEvent); + IM_ASSERT(hr == S_OK); + ::WaitForSingleObject(data->FenceEvent, INFINITE); + } +} + static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport) { // The main viewport (owned by the application) will always have RendererUserData == NULL since we didn't create the data for it. if (ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)viewport->RendererUserData) { - // Wait for pending operations to complete to safely release objects below - HRESULT hr; - if (data->CommandQueue && data->Fence && data->FenceEvent) - { - hr = data->CommandQueue->Signal(data->Fence, ++data->FenceSignaledValue); - IM_ASSERT(hr == S_OK); - ::WaitForSingleObject(data->FenceEvent, 0); // Reset any forgotten waits - hr = data->Fence->SetEventOnCompletion(data->FenceSignaledValue, data->FenceEvent); - IM_ASSERT(hr == S_OK); - ::WaitForSingleObject(data->FenceEvent, INFINITE); - } + ImGui_WaitForPendingOperations(data); SafeRelease(data->CommandQueue); SafeRelease(data->CommandList); @@ -887,6 +891,8 @@ static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) { ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)viewport->RendererUserData; + ImGui_WaitForPendingOperations(data); + for (UINT i = 0; i < g_numFramesInFlight; i++) SafeRelease(data->FrameCtx[i].RenderTarget); From 685ca27d84e59e1ecf520e4984bce027a0579ac6 Mon Sep 17 00:00:00 2001 From: Albert Vaca Date: Fri, 8 May 2020 17:29:14 +0200 Subject: [PATCH 033/959] Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_opengl3.cpp | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 116ee156..0b549802 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,7 @@ Other Changes: - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] +- Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) [@albertvaka] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index c60df73d..61131eb6 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 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. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader. @@ -184,6 +185,9 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) #elif defined(IMGUI_IMPL_OPENGL_ES3) if (glsl_version == NULL) glsl_version = "#version 300 es"; +#elif defined(__APPLE__) + if (glsl_version == NULL) + glsl_version = "#version 150"; #else if (glsl_version == NULL) glsl_version = "#version 130"; From 7b3d379819c487f0d5323ed7bd7c9109a2bc1d76 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 8 May 2020 18:36:05 +0200 Subject: [PATCH 034/959] FocusWindow(NULL) correctly steal active id from previous window. (#1738) amend b0a9bbf6 --- imgui.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 11d9a79d..715b5dbb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6161,19 +6161,18 @@ void ImGui::FocusWindow(ImGuiWindow* window) // Close popups if any ClosePopupsOverWindow(window, false); - // Passing NULL allow to disable keyboard focus - if (!window) - return; - // Move the root window to the top of the pile - IM_ASSERT(window->RootWindow != NULL); - ImGuiWindow* focus_front_window = window->RootWindow; // NB: In docking branch this is window->RootWindowDockStop - ImGuiWindow* display_front_window = window->RootWindow; + IM_ASSERT(window == NULL || window->RootWindow != NULL); + ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop + ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; // Steal focus on active widgets - if (focus_front_window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement may be unnecessary? Need further testing before removing it.. - if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) - ClearActiveID(); + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) + ClearActiveID(); + + // Passing NULL allow to disable keyboard focus + if (!window) + return; // Bring to front BringWindowToFocusFront(focus_front_window); From a6f4b0fd70150a7cbde03e99fda09ef7b2bfb6d6 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 11 May 2020 13:58:40 +0300 Subject: [PATCH 035/959] Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) First call to EndPopup() called NavRequestTryWrapWindow() which performed wrap-around operation while we were not done composing menu. This resulted in navigation wrapping around to first item. Since wrap-around operation is only valid in last call to EndPopup() and there is no way to know which call is last - this operation is delayed to the end of the frame. --- docs/CHANGELOG.txt | 2 + imgui.cpp | 106 +++++++++++++++++++++++++++++++-------------- imgui_internal.h | 4 ++ 3 files changed, 79 insertions(+), 33 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0b549802..ebd6f735 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,8 @@ Other Changes: Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). - Metrics: Added a "Settings" section with some details about persistent ini settings. +- Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to + BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the diff --git a/imgui.cpp b/imgui.cpp index 715b5dbb..deb7e981 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -937,6 +937,7 @@ static void NavUpdateWindowingOverlay(); static void NavUpdateMoveResult(); static float NavUpdatePageUpPageDown(); static inline void NavUpdateAnyRequestFlag(); +static void NavEndFrame(); static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand); static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id); static ImVec2 NavCalcPreferredRefPos(); @@ -4209,9 +4210,8 @@ void ImGui::EndFrame() g.CurrentWindow->Active = false; End(); - // Show CTRL+TAB list window - if (g.NavWindowingTarget != NULL) - NavUpdateWindowingOverlay(); + // Update navigation: CTRL+Tab, wrap-around requests + NavEndFrame(); // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) if (g.DragDropActive) @@ -7819,7 +7819,8 @@ void ImGui::EndPopup() IM_ASSERT(g.BeginPopupStack.Size > 0); // Make all menus and popups wrap around for now, may need to expose that policy. - NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); + if (g.NavWindow == window) + NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); // Child-popups don't need to be laid out IM_ASSERT(g.WithinEndChild == false); @@ -8298,36 +8299,11 @@ void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const Im void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags) { ImGuiContext& g = *GImGui; - if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != ImGuiNavLayer_Main) - return; - IM_ASSERT(move_flags != 0); // No points calling this with no wrapping - ImRect bb_rel = window->NavRectRel[0]; - ImGuiDir clip_dir = g.NavMoveDir; - if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) - { - bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x; - if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; } - NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); - } - if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) - { - bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x; - if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; } - NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); - } - if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) - { - bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y; - if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; } - NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); - } - if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) - { - bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y; - if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; } - NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); - } + // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire + // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. + g.NavWrapRequestWindow = window; + g.NavWrapRequestFlags = move_flags; } // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). @@ -8457,6 +8433,8 @@ static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; g.IO.WantSetMousePos = false; + g.NavWrapRequestWindow = NULL; + g.NavWrapRequestFlags = ImGuiNavMoveFlags_None; #if 0 if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); #endif @@ -8870,6 +8848,68 @@ static float ImGui::NavUpdatePageUpPageDown() return 0.0f; } +static void ImGui::NavEndFrame() +{ + ImGuiContext& g = *GImGui; + + // Show CTRL+TAB list window + if (g.NavWindowingTarget != NULL) + NavUpdateWindowingOverlay(); + + // Perform wrap-around in menus + ImGuiWindow* window = g.NavWrapRequestWindow; + ImGuiNavMoveFlags move_flags = g.NavWrapRequestFlags; + if (window != NULL && g.NavWindow == window && NavMoveRequestButNoResultYet() && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == ImGuiNavLayer_Main) + { + IM_ASSERT(move_flags != 0); // No points calling this with no wrapping + ImRect bb_rel = window->NavRectRel[0]; + + ImGuiDir clip_dir = g.NavMoveDir; + if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = + ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) + { + bb_rel.TranslateY(-bb_rel.GetHeight()); + clip_dir = ImGuiDir_Up; + } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) + { + bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x; + if (move_flags & ImGuiNavMoveFlags_WrapX) + { + bb_rel.TranslateY(+bb_rel.GetHeight()); + clip_dir = ImGuiDir_Down; + } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = + ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) + { + bb_rel.TranslateX(-bb_rel.GetWidth()); + clip_dir = ImGuiDir_Left; + } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) + { + bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y; + if (move_flags & ImGuiNavMoveFlags_WrapY) + { + bb_rel.TranslateX(+bb_rel.GetWidth()); + clip_dir = ImGuiDir_Right; + } + NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); + } + } +} + static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; diff --git a/imgui_internal.h b/imgui_internal.h index 1fcd64de..7dd635e2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1207,6 +1207,8 @@ struct ImGuiContext ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) + ImGuiWindow* NavWrapRequestWindow; // Window which requested trying nav wrap-around. + ImGuiNavMoveFlags NavWrapRequestFlags; // Wrap-around operation flags. // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! @@ -1383,6 +1385,8 @@ struct ImGuiContext NavMoveRequestForward = ImGuiNavForward_None; NavMoveRequestKeyMods = ImGuiKeyModFlags_None; NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None; + NavWrapRequestWindow = NULL; + NavWrapRequestFlags = ImGuiNavMoveFlags_None; NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; From 6636cb9f2f9dd607a93b8e46a4cb2255703851e3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 11 May 2020 17:29:50 +0200 Subject: [PATCH 036/959] Viewports: Don't set ImGuiViewportFlags_NoRendererClear when ImGuiWindowFlags_NoBackground is set. (#3213) --- imgui.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e1f51a77..db1fb892 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6236,7 +6236,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) UpdateViewportPlatformMonitor(window->Viewport); // Update common viewport flags - ImGuiViewportFlags viewport_flags = (window->Viewport->Flags) & ~(ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration); + const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; + ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; if (flags & ImGuiWindowFlags_Tooltip) viewport_flags |= ImGuiViewportFlags_TopMost; @@ -6266,7 +6267,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear; // We also tell the back-end that clearing the platform window won't be necessary, as our window is filling the viewport and we have disabled BgAlpha - viewport_flags |= ImGuiViewportFlags_NoRendererClear; + if (!(flags & ImGuiWindowFlags_NoBackground)) + viewport_flags &= ~ImGuiViewportFlags_NoRendererClear; + window->Viewport->Flags = viewport_flags; } From c46b79846c18d131f00ee299c811bb7afd125e66 Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Sat, 9 May 2020 22:18:10 -0700 Subject: [PATCH 037/959] Metrics: Fix metrics crash with viewports. --- imgui.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index db1fb892..f16aa3d3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15318,10 +15318,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) return ImRect(); } - static void NodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, int elem_offset, bool show_mesh, bool show_aabb) + static void NodeDrawCmdShowMeshAndBoundingBox(ImDrawList* fg_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, int elem_offset, bool show_mesh, bool show_aabb) { IM_ASSERT(show_mesh || show_aabb); - ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // Draw wire-frame version of all triangles @@ -15350,6 +15349,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) fg_draw_list->Flags = backup_flags; } + // Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport. static void NodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, ImDrawList* draw_list, const char* label) { bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); @@ -15388,7 +15388,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (ImGui::IsItemHovered() && (show_drawcmd_mesh || show_drawcmd_aabb) && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, show_drawcmd_mesh, show_drawcmd_aabb); + NodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, elem_offset, show_drawcmd_mesh, show_drawcmd_aabb); if (!pcmd_node_open) continue; @@ -15407,7 +15407,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); ImGui::Selectable(buf); if (ImGui::IsItemHovered() && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, true, false); + NodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, elem_offset, true, false); // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. From 6b80bd9cc3114c18f05b9fae544676233464f547 Mon Sep 17 00:00:00 2001 From: Maru Date: Sun, 10 May 2020 07:01:54 +0900 Subject: [PATCH 038/959] Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) https://en.wikipedia.org/wiki/Hangul_Syllables --- docs/CHANGELOG.txt | 1 + imgui_draw.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ebd6f735..6730d29f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 1df83d12..f566cbc5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2340,7 +2340,7 @@ const ImWchar* ImFontAtlas::GetGlyphRangesKorean() { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3131, 0x3163, // Korean alphabets - 0xAC00, 0xD79D, // Korean characters + 0xAC00, 0xD7A3, // Korean characters 0, }; return &ranges[0]; From 03ea87ea287a7391603bcf85a441412d973f65f1 Mon Sep 17 00:00:00 2001 From: Chris Savoie Date: Fri, 8 May 2020 13:02:15 -0700 Subject: [PATCH 039/959] Backends, Win32: Request monitor update when dpi awarness is enabled to make sure they have the correct dpi settings. --- examples/imgui_impl_win32.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index b7a38785..207e54fe 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -473,6 +473,9 @@ typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWAR // Helper function to enable DPI awareness without setting up a manifest void ImGui_ImplWin32_EnableDpiAwareness() { + // Make sure monitors will be updated with latest correct scaling + g_WantUpdateMonitors = true; + // if (IsWindows10OrGreater()) // This needs a manifest to succeed. Instead we try to grab the function pointer! { static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process From 5fdfa32ccea2493f7ffc4801f2837199eabe1de5 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 May 2020 15:42:29 +0200 Subject: [PATCH 040/959] Update README.md --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index 341bdcbe..e8fa16f1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -194,7 +194,7 @@ Ongoing Dear ImGui development is financially supported by users and private spo - [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui/) *Double-chocolate and Salty caramel sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) +- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors). From 476daf9aac1b49f91a3c370eed4085c96e1725a5 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 May 2020 20:28:34 +0200 Subject: [PATCH 041/959] Settings: Added ReadInitFn pre-load handler. (docking branch already has it, so it'll probably conflict with same contents) --- imgui.cpp | 43 +++++++++++++++++++++++++------------------ imgui_internal.h | 3 ++- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index deb7e981..726b05f5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -918,9 +918,9 @@ static ImRect GetViewportRect(); // Settings static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); -static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); +static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); // Platform Dependents default implementation for IO functions @@ -3945,9 +3945,9 @@ void ImGui::Initialize(ImGuiContext* context) ini_handler.TypeName = "Window"; ini_handler.TypeHash = ImHashStr("Window"); ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll; - ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen; ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll; g.SettingsHandlers.push_back(ini_handler); } @@ -9784,6 +9784,12 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) memcpy(buf, ini_data, ini_size); buf_end[0] = 0; + // Call pre-read handlers + // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) + for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) + if (g.SettingsHandlers[handler_n].ReadInitFn) + g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]); + void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; @@ -9872,24 +9878,12 @@ static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandl g.SettingsWindows.clear(); } -// Apply to existing windows (if any) -static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) -{ - ImGuiContext& g = *ctx; - for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) - if (settings->WantApply) - { - if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) - ApplyWindowSettings(window, settings); - settings->WantApply = false; - } -} - static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { - ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); - if (!settings) - settings = ImGui::CreateNewWindowSettings(name); + ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name); + ImGuiID id = settings->ID; + *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry + settings->ID = id; settings->WantApply = true; return (void*)settings; } @@ -9904,6 +9898,19 @@ static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } +// Apply to existing windows (if any) +static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) + if (settings->WantApply) + { + if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) + ApplyWindowSettings(window, settings); + settings->WantApply = false; + } +} + static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { // Gather data from windows that were active during this session diff --git a/imgui_internal.h b/imgui_internal.h index 7dd635e2..2802f519 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1082,9 +1082,10 @@ struct ImGuiSettingsHandler const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHashStr(TypeName) void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data - void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) + void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order) void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry + void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' void* UserData; From 1cd32d3afe8cc70338e02652795ce7a62fe680ea Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 May 2020 00:15:14 +0200 Subject: [PATCH 042/959] Docking: moving small docking context to imgui_internal.h, removed unnecessary indirection, renaming. --- imgui.cpp | 111 ++++++++++++++++++++--------------------------- imgui_internal.h | 14 ++++-- 2 files changed, 59 insertions(+), 66 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f16aa3d3..5cc867de 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4164,7 +4164,6 @@ void ImGui::Initialize(ImGuiContext* context) g.PlatformIO.Viewports.push_back(g.Viewports[0]); // Extensions - IM_ASSERT(g.DockContext == NULL); DockContextInitialize(&g); #endif // #ifdef IMGUI_HAS_DOCK @@ -4203,7 +4202,6 @@ void ImGui::Shutdown(ImGuiContext* context) SetCurrentContext(backup_context); // Shutdown extensions - IM_ASSERT(g.DockContext != NULL); DockContextShutdown(&g); // Clear everything else @@ -11626,15 +11624,6 @@ struct ImGuiDockNodeSettings ImGuiDockNodeSettings() { ID = ParentNodeId = ParentWindowId = SelectedWindowId = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } }; -struct ImGuiDockContext -{ - ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes - ImVector Requests; - ImVector SettingsNodes; - bool WantFullRebuild; - ImGuiDockContext() { WantFullRebuild = false; } -}; - //----------------------------------------------------------------------------- // Docking: Forward Declarations //----------------------------------------------------------------------------- @@ -11731,8 +11720,6 @@ namespace ImGui void ImGui::DockContextInitialize(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - IM_ASSERT(g.DockContext == NULL); - g.DockContext = IM_NEW(ImGuiDockContext)(); // Add .ini handle for persistent docking data ImGuiSettingsHandler ini_handler; @@ -11749,13 +11736,10 @@ void ImGui::DockContextInitialize(ImGuiContext* ctx) void ImGui::DockContextShutdown(ImGuiContext* ctx) { - ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) IM_DELETE(node); - IM_DELETE(g.DockContext); - g.DockContext = NULL; } void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references) @@ -11771,11 +11755,11 @@ void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) { IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; SaveIniSettingsToMemory(); ImGuiID root_id = 0; // Rebuild all DockContextClearNodes(ctx, root_id, false); - DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); DockContextBuildAddWindowsToNodes(ctx, root_id); } @@ -11783,7 +11767,7 @@ void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) { if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0) @@ -11827,7 +11811,7 @@ void ImGui::DockContextUpdateUndocking(ImGuiContext* ctx) void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; @@ -11847,7 +11831,7 @@ void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id) { - return (ImGuiDockNode*)ctx->DockContext->Nodes.GetVoidPtr(id); + return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id); } ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx) @@ -11871,14 +11855,14 @@ static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id) // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id); ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id); - ctx->DockContext->Nodes.SetVoidPtr(node->ID, node); + ctx->DockContext.Nodes.SetVoidPtr(node->ID, node); return node; } static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID); IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node); @@ -11925,16 +11909,16 @@ struct ImGuiDockContextPruneNodeData static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; IM_ASSERT(g.Windows.Size == 0); ImPool pool; - pool.Reserve(dc->SettingsNodes.Size); + pool.Reserve(dc->NodesSettings.Size); // Count child nodes and compute RootID - for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++) + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0; pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID; if (settings->ParentNodeId) @@ -11943,9 +11927,9 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) // Count reference to dock ids from dockspaces // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() - for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++) + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; if (settings->ParentWindowId != 0) if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId)) if (window_settings->DockId) @@ -11965,9 +11949,9 @@ static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) } // Prune - for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++) + for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { - ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID); if (data->CountWindows > 1) continue; @@ -12059,7 +12043,7 @@ void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDo req.DockSplitDir = split_dir; req.DockSplitRatio = split_ratio; req.DockSplitOuter = split_outer; - ctx->DockContext->Requests.push_back(req); + ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window) @@ -12067,7 +12051,7 @@ void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window) ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Undock; req.UndockTargetWindow = window; - ctx->DockContext->Requests.push_back(req); + ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) @@ -12075,12 +12059,12 @@ void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Undock; req.UndockTargetNode = node; - ctx->DockContext->Requests.push_back(req); + ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node) { - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; for (int n = 0; n < dc->Requests.Size; n++) if (dc->Requests[n].DockTargetNode == node) dc->Requests[n].Type = ImGuiDockRequestType_None; @@ -13725,12 +13709,12 @@ void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG if (child_0) { - ctx->DockContext->Nodes.SetVoidPtr(child_0->ID, NULL); + ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL); IM_DELETE(child_0); } if (child_1) { - ctx->DockContext->Nodes.SetVoidPtr(child_1->ID, NULL); + ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL); IM_DELETE(child_1); } } @@ -14264,7 +14248,7 @@ void ImGui::DockBuilderRemoveNode(ImGuiID node_id) void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) { ImGuiContext* ctx = GImGui; - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL; if (root_id && root_node == NULL) @@ -14875,29 +14859,29 @@ static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id) { // FIXME-OPT - ImGuiDockContext* dc = ctx->DockContext; - for (int n = 0; n < dc->SettingsNodes.Size; n++) - if (dc->SettingsNodes[n].ID == id) - return &dc->SettingsNodes[n]; + ImGuiDockContext* dc = &ctx->DockContext; + for (int n = 0; n < dc->NodesSettings.Size; n++) + if (dc->NodesSettings[n].ID == id) + return &dc->NodesSettings[n]; return NULL; } // Clear settings data static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { - ImGuiDockContext* dc = ctx->DockContext; - dc->SettingsNodes.clear(); + ImGuiDockContext* dc = &ctx->DockContext; + dc->NodesSettings.clear(); DockContextClearNodes(ctx, 0, true); } -// Recreate dones based on settings data +// Recreate nodes based on settings data static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { // Prune settings at boot time only - ImGuiDockContext* dc = ctx->DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (ctx->Windows.Size == 0) DockContextPruneUnusedSettingsNodes(ctx); - DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size); + DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); DockContextBuildAddWindowsToNodes(ctx, 0); } @@ -14943,11 +14927,10 @@ static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettings if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; } if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; } if (sscanf(line, " Selected=0x%08X%n", &node.SelectedWindowId,&r) == 1) { line += r; } - ImGuiDockContext* dc = ctx->DockContext; if (node.ParentNodeId != 0) if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId)) node.Depth = parent_settings->Depth + 1; - dc->SettingsNodes.push_back(node); + ctx->DockContext.NodesSettings.push_back(node); } static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth) @@ -14964,7 +14947,7 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo node_settings.Pos = ImVec2ih(node->Pos); node_settings.Size = ImVec2ih(node->Size); node_settings.SizeRef = ImVec2ih(node->SizeRef); - dc->SettingsNodes.push_back(node_settings); + dc->NodesSettings.push_back(node_settings); if (node->ChildNodes[0]) DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1); if (node->ChildNodes[1]) @@ -14974,29 +14957,29 @@ static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDo static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { ImGuiContext& g = *ctx; - ImGuiDockContext* dc = g.DockContext; + ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; // Gather settings data // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) - dc->SettingsNodes.resize(0); - dc->SettingsNodes.reserve(dc->Nodes.Data.Size); + dc->NodesSettings.resize(0); + dc->NodesSettings.reserve(dc->Nodes.Data.Size); for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (node->IsRootNode()) DockSettingsHandler_DockNodeToSettings(dc, node, 0); int max_depth = 0; - for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++) - max_depth = ImMax((int)dc->SettingsNodes[node_n].Depth, max_depth); + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) + max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth); // Write to text buffer buf->appendf("[%s][Data]\n", handler->TypeName); - for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++) + for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) { const int line_start_pos = buf->size(); (void)line_start_pos; - const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n]; + const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n]; buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file buf->appendf(" ID=0x%08X", node_settings->ID); if (node_settings->ParentNodeId) @@ -15722,7 +15705,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("Dock nodes")) { - ImGuiDockContext* dc = g.DockContext; + ImGuiDockContext* dc = &g.DockContext; ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes); if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ImGui::SameLine(); @@ -15777,14 +15760,15 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("SettingsDocking", "Settings packed data: Docking")) { + ImGuiDockContext* dc = &g.DockContext; ImGui::Text("In SettingsWindows:"); for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (settings->DockId != 0) ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId); ImGui::Text("In SettingsNodes:"); - for (int n = 0; n < g.DockContext->SettingsNodes.Size; n++) + for (int n = 0; n < dc->NodesSettings.Size; n++) { - ImGuiDockNodeSettings* settings = &g.DockContext->SettingsNodes[n]; + ImGuiDockNodeSettings* settings = &dc->NodesSettings[n]; const char* selected_tab_name = NULL; if (settings->SelectedWindowId) { @@ -15871,8 +15855,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Overlay: Display Docking info if (show_docking_nodes && g.IO.KeyCtrl) { - for (int n = 0; n < g.DockContext->Nodes.Data.Size; n++) - if (ImGuiDockNode* node = (ImGuiDockNode*)g.DockContext->Nodes.Data[n].val_p) + ImGuiDockContext* dc = &g.DockContext; + for (int n = 0; n < dc->Nodes.Data.Size; n++) + if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) { ImGuiDockNode* root_node = DockNodeGetRootNode(node); if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos)) diff --git a/imgui_internal.h b/imgui_internal.h index 489e5011..54d731ca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -94,6 +94,7 @@ struct ImGuiColumns; // Storage data for a columns set struct ImGuiContext; // Main Dear ImGui context struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiDockContext; // Docking system context +struct ImGuiDockRequest; // Docking system dock/undock queued request struct ImGuiDockNode; // Docking system node (hold a list of Windows OR two child dock nodes) struct ImGuiDockNodeSettings; // Storage for a dock node in .ini file (we preserve those even if the associated dock node isn't active during the session) struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() @@ -1161,6 +1162,15 @@ struct ImGuiDockNode ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } }; +struct ImGuiDockContext +{ + ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes + ImVector Requests; + ImVector NodesSettings; + bool WantFullRebuild; + ImGuiDockContext() { WantFullRebuild = false; } +}; + #endif // #ifdef IMGUI_HAS_DOCK //----------------------------------------------------------------------------- @@ -1443,7 +1453,7 @@ struct ImGuiContext // Extensions // FIXME: We could provide an API to register one slot in an array held in ImGuiContext? - ImGuiDockContext* DockContext; + ImGuiDockContext DockContext; // Settings bool SettingsLoaded; @@ -1597,8 +1607,6 @@ struct ImGuiContext PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX); PlatformImePosViewport = 0; - DockContext = NULL; - SettingsLoaded = false; SettingsDirtyTimer = 0.0f; From 39c978f499018bedc62257f2be18957e76f3990a Mon Sep 17 00:00:00 2001 From: "Mr. Metric" Date: Fri, 15 May 2020 01:51:51 -0700 Subject: [PATCH 043/959] Fix typo/bug introduced by 0679e056 (#3231, #3209, #1829, #946, #413) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 71153c20..e509c039 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2970,7 +2970,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); // Only mark as edited if new value is different - value_changed = memcmp(&data_type, p_data, data_type_size) != 0; + value_changed = memcmp(&data_backup, p_data, data_type_size) != 0; if (value_changed) MarkItemEdited(id); } From 3b3af6b73136a03dfcdb84872fc08542900a1aa8 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 May 2020 16:11:42 +0200 Subject: [PATCH 044/959] Docking: Fix extraneous function declaration (#3236) + moved some other declarations in imgui_internal to facilitate moving docking code. --- imgui.cpp | 17 +++++++---------- imgui_internal.h | 10 ++++++---- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fcebd5c0..31b5e10e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -921,7 +921,6 @@ static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For u //------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window); -static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); @@ -7137,7 +7136,7 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co window->Collapsed = collapsed; } -static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) +void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) { IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters window->HitTestHoleSize = ImVec2ih(size); @@ -11679,7 +11678,6 @@ namespace ImGui static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx); static ImGuiDockNode* DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id); static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window); - static void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_refs); // Use root_id==0 to clear all static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count); static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all @@ -11707,7 +11705,6 @@ namespace ImGui static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired); static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos); static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; } - static int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } static int DockNodeGetTabOrder(ImGuiWindow* window); // ImGuiDockNode tree manipulations @@ -11781,11 +11778,11 @@ void ImGui::DockContextShutdown(ImGuiContext* ctx) IM_DELETE(node); } -void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references) +void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs) { IM_UNUSED(ctx); IM_ASSERT(ctx == GImGui); - DockBuilderRemoveNodeDockedWindows(root_id, clear_persistent_docking_references); + DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs); DockBuilderRemoveNodeChildNodes(root_id); } @@ -14351,12 +14348,12 @@ void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) } } -void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persistent_docking_references) +void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs) { // Clear references in settings ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; - if (clear_persistent_docking_references) + if (clear_settings_refs) { for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) { @@ -14379,8 +14376,8 @@ void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persi { const ImGuiID backup_dock_id = window->DockId; IM_UNUSED(backup_dock_id); - DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_references); - if (!clear_persistent_docking_references) + DockContextProcessUndockWindow(ctx, window, clear_settings_refs); + if (!clear_settings_refs) IM_ASSERT(window->DockId == backup_dock_id); } } diff --git a/imgui_internal.h b/imgui_internal.h index 9737578c..f7a2fbca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1978,6 +1978,7 @@ namespace ImGui IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); + IMGUI_API void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window); @@ -2107,7 +2108,7 @@ namespace ImGui // (some functions are only declared in imgui.cpp, see Docking section) IMGUI_API void DockContextInitialize(ImGuiContext* ctx); IMGUI_API void DockContextShutdown(ImGuiContext* ctx); - IMGUI_API void DockContextOnLoadSettings(ImGuiContext* ctx); + IMGUI_API void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs); // Use root_id==0 to clear all IMGUI_API void DockContextRebuildNodes(ImGuiContext* ctx); IMGUI_API void DockContextUpdateUndocking(ImGuiContext* ctx); IMGUI_API void DockContextUpdateDocking(ImGuiContext* ctx); @@ -2116,8 +2117,9 @@ namespace ImGui IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos); - inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } - inline ImGuiDockNode* GetWindowDockNode() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockNode; } + inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } + inline int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } + inline ImGuiDockNode* GetWindowDockNode() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockNode; } IMGUI_API bool GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window); IMGUI_API void BeginDocked(ImGuiWindow* window, bool* p_open); IMGUI_API void BeginDockableDragDropSource(ImGuiWindow* window); @@ -2138,7 +2140,7 @@ namespace ImGui inline ImGuiDockNode* DockBuilderGetCentralNode(ImGuiID node_id) { ImGuiDockNode* node = DockBuilderGetNode(node_id); if (!node) return NULL; return DockNodeGetRootNode(node)->CentralNode; } IMGUI_API ImGuiID DockBuilderAddNode(ImGuiID node_id = 0, ImGuiDockNodeFlags flags = 0); IMGUI_API void DockBuilderRemoveNode(ImGuiID node_id); // Remove node and all its child, undock all windows - IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_persistent_docking_references = true); + IMGUI_API void DockBuilderRemoveNodeDockedWindows(ImGuiID node_id, bool clear_settings_refs = true); IMGUI_API void DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the remaining root node (node_id). IMGUI_API void DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos); IMGUI_API void DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size); From 417ac68f82912ae4291e8e9b05abf38877a64b83 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 May 2020 11:55:36 +0200 Subject: [PATCH 045/959] Internals: AddPolyline: Add spaces for consistency, renaming. --- imgui_draw.cpp | 56 +++++++++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f566cbc5..2dfccf07 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -627,13 +627,12 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (points_count < 2) return; - const ImVec2 uv = _Data->TexUvWhitePixel; - + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; int count = points_count; if (!closed) count = points_count-1; - const bool thick_line = thickness > 1.0f; + const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) { // Anti-aliased stroke @@ -704,9 +703,9 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Add vertices for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; - _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; - _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; + _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; _VtxWritePtr += 3; } } @@ -715,22 +714,23 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; if (!closed) { + const int points_last = points_count - 1; temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); - temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); - temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); - temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); - temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); } // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; - unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment + const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -753,12 +753,12 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 out_vtx[3].y = points[i2].y - dm_out_y; // Add indexes - _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); - _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); - _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); - _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); - _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); - _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr += 18; idx1 = idx2; @@ -767,10 +767,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Add vertices for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; - _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; - _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; - _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans; _VtxWritePtr += 4; } } @@ -795,14 +795,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dx *= (thickness * 0.5f); dy *= (thickness * 0.5f); - _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; - _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; - _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; - _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col; _VtxWritePtr += 4; - _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); - _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3); _IdxWritePtr += 6; _VtxCurrentIdx += 4; } From 615e9ae34537df5324df2f71253eafd887a848d1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 18 May 2020 15:08:47 +0200 Subject: [PATCH 046/959] Docking: Fix undocking (#3243), amend 7b3d3798 (#1738) --- imgui.cpp | 15 ++++++++++----- imgui_widgets.cpp | 5 +++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 31b5e10e..bec67413 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6796,9 +6796,14 @@ void ImGui::FocusWindow(ImGuiWindow* window) IM_ASSERT(window == NULL || window->RootWindow != NULL); ImGuiWindow* focus_front_window = window ? window->RootWindowDockStop : NULL; ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; - - // Steal focus on active widgets - if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window) + ImGuiDockNode* dock_node = window ? window->DockNode : NULL; + bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow); + + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) + // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window && !active_id_window_is_dock_node_host) ClearActiveID(); // Passing NULL allow to disable keyboard focus @@ -6807,8 +6812,8 @@ void ImGui::FocusWindow(ImGuiWindow* window) window->LastFrameJustFocused = g.FrameCount; // Select in dock node - if (window->DockNode && window->DockNode->TabBar) - window->DockNode->TabBar->SelectedTabId = window->DockNode->TabBar->NextSelectedTabId = window->ID; + if (dock_node && dock_node->TabBar) + dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->ID; // Bring to front BringWindowToFocusFront(focus_front_window); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 74df4865..2c1c04e1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7289,6 +7289,11 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->NextSelectedTabId = id; hovered |= (g.HoveredId == id); + // Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() + // will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. + if (held && docked_window && g.ActiveId == id && g.ActiveIdIsJustActivated) + g.ActiveIdWindow = docked_window; + // Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered) if (!held) SetItemAllowOverlap(); From 75bbbda645c650a52783e8bd5c49da4b6905d81e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 May 2020 11:44:00 +0200 Subject: [PATCH 047/959] Examples: Update comments to get SDL2 package with msys2's pacman (#3251) --- examples/example_sdl_opengl2/Makefile | 2 +- examples/example_sdl_opengl3/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/example_sdl_opengl2/Makefile b/examples/example_sdl_opengl2/Makefile index ce29a249..9c57337e 100644 --- a/examples/example_sdl_opengl2/Makefile +++ b/examples/example_sdl_opengl2/Makefile @@ -8,7 +8,7 @@ # Mac OS X: # brew install sdl2 # MSYS2: -# pacman -S mingw-w64-i686-SDL +# pacman -S mingw-w64-i686-SDL2 # #CXX = g++ diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index ada77197..e8b2f566 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -8,7 +8,7 @@ # Mac OS X: # brew install sdl2 # MSYS2: -# pacman -S mingw-w64-i686-SDL +# pacman -S mingw-w64-i686-SDL2 # #CXX = g++ From f44962c01a0e5f5fdf9652cb28e775838fe0dbbc Mon Sep 17 00:00:00 2001 From: Espyo Date: Wed, 20 May 2020 16:48:21 +0100 Subject: [PATCH 048/959] Backends: Allegro: Don't call AddInputCharacter if the pressed key has no character. (#3252) --- examples/imgui_impl_allegro5.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 76f74a3f..2c7df9a9 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -357,7 +357,8 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT *ev) return true; case ALLEGRO_EVENT_KEY_CHAR: if (ev->keyboard.display == g_Display) - io.AddInputCharacter((unsigned int)ev->keyboard.unichar); + if (ev->keyboard.unichar != 0) + io.AddInputCharacter((unsigned int)ev->keyboard.unichar); return true; case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_UP: From c8cde28cf3fb5d1e86faa80edf9b2c48ccc2f8dc Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 20 May 2020 17:56:08 +0200 Subject: [PATCH 049/959] IO: AddInputCharacters function ignore 0 input. (#3252) Amend ef13d954 + c8ea0a01 (#2541, #2538, #2815) --- imgui.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 726b05f5..6a984849 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1142,17 +1142,21 @@ ImGuiIO::ImGuiIO() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(unsigned int c) { - InputQueueCharacters.push_back(c > 0 && c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); + if (c != 0) + InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); } // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so // we should save the high surrogate. void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c) { + if (c == 0 && InputQueueSurrogate == 0) + return; + if ((c & 0xFC00) == 0xD800) // High surrogate, must save { if (InputQueueSurrogate != 0) - InputQueueCharacters.push_back(0xFFFD); + InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID); InputQueueSurrogate = c; return; } @@ -1177,7 +1181,7 @@ void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) { unsigned int c = 0; utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL); - if (c > 0) + if (c != 0) InputQueueCharacters.push_back((ImWchar)c); } } From d29157ce584e731114ff09d448120e094307304f Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 24 May 2020 12:32:31 +0200 Subject: [PATCH 050/959] Moved static array with non-trivial constructors outside of function seems to remove requirement of linking with libstdc++ on some compilers. --- imgui.cpp | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6a984849..97b15411 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5064,6 +5064,21 @@ static const ImGuiResizeGripDef resize_grip_def[4] = { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused) }; +struct ImGuiResizeBorderDef +{ + ImVec2 InnerDir; + ImVec2 CornerPosN1, CornerPosN2; + float OuterAngle; +}; + +static const ImGuiResizeBorderDef resize_border_def[4] = +{ + { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top + { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right + { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom + { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left +}; + static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) { ImRect rect = window->Rect(); @@ -5229,19 +5244,6 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) int border_held = window->ResizeBorderHeld; if (border_held != -1) { - struct ImGuiResizeBorderDef - { - ImVec2 InnerDir; - ImVec2 CornerPosN1, CornerPosN2; - float OuterAngle; - }; - static const ImGuiResizeBorderDef resize_border_def[4] = - { - { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top - { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right - { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom - { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left - }; const ImGuiResizeBorderDef& def = resize_border_def[border_held]; ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle); From 39d17ca07f14d3e37b8e6a85ee65bc078abf023e Mon Sep 17 00:00:00 2001 From: Nicolas Burrus Date: Mon, 25 May 2020 07:34:12 +0200 Subject: [PATCH 051/959] Examples: Apple: catch events from the right and other mouse buttons when using Cocoa. (#3260) --- docs/CHANGELOG.txt | 6 +++-- .../Shared/ViewController.mm | 24 +++++++++++++++++++ examples/example_apple_opengl2/main.mm | 24 ++++++++++++------- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6730d29f..78719031 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,8 @@ Other Changes: - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] +- Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when + drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the @@ -62,8 +64,8 @@ Other Changes: - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] -- Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when - drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm + not forwarding right and center mouse clicks. (#3260) [@nburrus] ----------------------------------------------------------------------- diff --git a/examples/example_apple_metal/Shared/ViewController.mm b/examples/example_apple_metal/Shared/ViewController.mm index 73040add..3c79cc1c 100644 --- a/examples/example_apple_metal/Shared/ViewController.mm +++ b/examples/example_apple_metal/Shared/ViewController.mm @@ -72,14 +72,38 @@ ImGui_ImplOSX_HandleEvent(event, self.view); } +- (void)rightMouseDown:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseDown:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + - (void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } +- (void)rightMouseUp:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseUp:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + - (void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } +- (void)rightMouseDragged:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseDragged:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + - (void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index e8f2768b..7cbf3409 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -139,14 +139,22 @@ } // Forward Mouse/Keyboard events to dear imgui OSX back-end. It returns true when imgui is expecting to use the event. --(void)keyUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)keyDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)flagsChanged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)keyUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)keyDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)flagsChanged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } +-(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } @end From 43f79aa21069485f27bf5dee3f9977464fd746e3 Mon Sep 17 00:00:00 2001 From: Nicolas Burrus Date: Mon, 25 May 2020 08:27:17 +0200 Subject: [PATCH 052/959] Backends: OSX: import the glfw workaround to avoid missing mouse clicks. (#3261) --- examples/imgui_impl_osx.mm | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 54b23d07..221fa562 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -14,6 +14,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-05-25: Inputs: Added a fix for missing trackpad clicks when done with "soft tap". // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-10-11: Inputs: Fix using Backspace key. // 2019-07-21: Re-added clipboard handlers as they are not enabled by default in core imgui.cpp (reverted 2019-05-18 change). @@ -27,6 +28,8 @@ static CFAbsoluteTime g_Time = 0.0; static NSCursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {}; static bool g_MouseCursorHidden = false; +static bool g_MouseJustPressed[5] = { false, false, false, false, false }; +static bool g_MouseDown[5] = { false, false, false, false, false }; // Undocumented methods for creating cursors. @interface NSCursor() @@ -121,9 +124,17 @@ void ImGui_ImplOSX_Shutdown() { } -static void ImGui_ImplOSX_UpdateMouseCursor() +static void ImGui_ImplOSX_UpdateMouseCursorAndButtons() { ImGuiIO& io = ImGui::GetIO(); + + for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown) && i < IM_ARRAYSIZE(g_MouseJustPressed); i++) + { + // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. + io.MouseDown[i] = g_MouseJustPressed[i] || g_MouseDown[i]; + g_MouseJustPressed[i] = false; + } + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return; @@ -167,7 +178,7 @@ void ImGui_ImplOSX_NewFrame(NSView* view) io.DeltaTime = current_time - g_Time; g_Time = current_time; - ImGui_ImplOSX_UpdateMouseCursor(); + ImGui_ImplOSX_UpdateMouseCursorAndButtons(); } static int mapCharacterToKey(int c) @@ -197,16 +208,19 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(io.MouseDown)) - io.MouseDown[button] = true; + if (button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed)) + { + g_MouseJustPressed[button] = true; + g_MouseDown[button] = true; + } return io.WantCaptureMouse; } if (event.type == NSEventTypeLeftMouseUp || event.type == NSEventTypeRightMouseUp || event.type == NSEventTypeOtherMouseUp) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(io.MouseDown)) - io.MouseDown[button] = false; + if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown)) + g_MouseDown[button] = false; return io.WantCaptureMouse; } From 9c209d5a9070f8d2dfc3a311a15064daf2f81518 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 11:42:20 +0200 Subject: [PATCH 053/959] Minor amend 9028088 (#3261) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_glfw.cpp | 2 +- examples/imgui_impl_osx.mm | 15 ++++++--------- imgui.h | 2 +- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 78719031..3528c1e1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,7 @@ Other Changes: - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] +- Backends: OSX: Added workaround to avoid fast mouse clicks. (#3261, #1992, #2525) [@nburrus] - Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm not forwarding right and center mouse clicks. (#3260) [@nburrus] diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index c496232c..ef63c81f 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -68,7 +68,7 @@ enum GlfwClientApi static GLFWwindow* g_Window = NULL; // Main window static GlfwClientApi g_ClientApi = GlfwClientApi_Unknown; static double g_Time = 0.0; -static bool g_MouseJustPressed[5] = { false, false, false, false, false }; +static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {}; static GLFWcursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {}; static bool g_InstalledCallbacks = false; diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 221fa562..90501624 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -28,8 +28,8 @@ static CFAbsoluteTime g_Time = 0.0; static NSCursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {}; static bool g_MouseCursorHidden = false; -static bool g_MouseJustPressed[5] = { false, false, false, false, false }; -static bool g_MouseDown[5] = { false, false, false, false, false }; +static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {}; +static bool g_MouseDown[ImGuiMouseButton_COUNT] = {}; // Undocumented methods for creating cursors. @interface NSCursor() @@ -126,9 +126,9 @@ void ImGui_ImplOSX_Shutdown() static void ImGui_ImplOSX_UpdateMouseCursorAndButtons() { + // Update buttons ImGuiIO& io = ImGui::GetIO(); - - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown) && i < IM_ARRAYSIZE(g_MouseJustPressed); i++) + for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) { // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[i] = g_MouseJustPressed[i] || g_MouseDown[i]; @@ -208,11 +208,8 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(g_MouseJustPressed)) - { - g_MouseJustPressed[button] = true; - g_MouseDown[button] = true; - } + if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown)) + g_MouseDown[button] = g_MouseJustPressed[button] = true; return io.WantCaptureMouse; } diff --git a/imgui.h b/imgui.h index 788f74c9..1a8d7a40 100644 --- a/imgui.h +++ b/imgui.h @@ -1488,7 +1488,7 @@ struct ImGuiIO //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.) - bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends. bool KeyCtrl; // Keyboard modifier pressed: Control From a056603d8b8e2fd7f151844999cc077ac628097b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 12:05:11 +0200 Subject: [PATCH 054/959] Backends: Vulkan: Rename internal helper ImGui_ImplVulkanH_CreateWindow to ImGui_ImplVulkanH_CreateOrResizeWindow --- examples/example_glfw_vulkan/main.cpp | 11 ++++++----- examples/example_sdl_vulkan/main.cpp | 11 ++++++----- examples/imgui_impl_vulkan.cpp | 3 ++- examples/imgui_impl_vulkan.h | 2 +- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 910d4738..15ec2068 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -48,8 +48,9 @@ static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { - if (err == 0) return; - printf("VkResult %d\n", err); + if (err == 0) + return; + fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) abort(); } @@ -58,7 +59,7 @@ static void check_vk_result(VkResult err) static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments - fprintf(stderr, "[vulkan] ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); + fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } #endif // IMGUI_VULKAN_DEBUG_REPORT @@ -225,7 +226,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } static void CleanupVulkan() @@ -459,7 +460,7 @@ int main(int, char**) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); g_MainWindowData.FrameIndex = 0; } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index c4e529e1..53975516 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -40,8 +40,9 @@ static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { - if (err == 0) return; - printf("VkResult %d\n", err); + if (err == 0) + return; + fprintf(stderr, "[vulkan] Error: VkResult = %d\n", err); if (err < 0) abort(); } @@ -50,7 +51,7 @@ static void check_vk_result(VkResult err) static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments - fprintf(stderr, "[vulkan] ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); + fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } #endif // IMGUI_VULKAN_DEBUG_REPORT @@ -217,7 +218,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface // Create SwapChain, RenderPass, Framebuffer, etc. IM_ASSERT(g_MinImageCount >= 2); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); } static void CleanupVulkan() @@ -456,7 +457,7 @@ int main(int, char**) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); g_MainWindowData.FrameIndex = 0; } diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 652476c7..93c3b404 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -1155,7 +1155,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V } } -void ImGui_ImplVulkanH_CreateWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) +// Create or resize window +void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) { (void)instance; ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index c85b5f28..0eb772e7 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -72,7 +72,7 @@ struct ImGui_ImplVulkanH_Frame; struct ImGui_ImplVulkanH_Window; // Helpers -IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); +IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); From bb2529dd48f01d550afb00c3eff61a255e110282 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 12:23:49 +0200 Subject: [PATCH 055/959] Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends. --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_sdl.cpp | 3 +++ 2 files changed, 5 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3528c1e1..2ad7a085 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,8 @@ Other Changes: drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) +- Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, + making more render/clipping code use an early out path. - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) [@albertvaka] diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 9fd2cc48..695ac810 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -17,6 +17,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends. // 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2). // 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state). // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. @@ -348,6 +349,8 @@ void ImGui_ImplSDL2_NewFrame(SDL_Window* window) int w, h; int display_w, display_h; SDL_GetWindowSize(window, &w, &h); + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) + w = h = 0; SDL_GL_GetDrawableSize(window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) From 6b688561aa8f2b83a591c93c7d75d07a7beb24dd Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 25 May 2020 13:25:22 +0300 Subject: [PATCH 056/959] CI: Test building without C++ runtime on GCC/Clang. --- .github/workflows/build.yml | 15 +++++++++++++++ docs/CHANGELOG.txt | 5 ++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 03641749..8edef47b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -288,6 +288,14 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (without c++ runtime, Clang) + run: | + echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp + echo '#define IMGUI_DISABLE_DEMO_WINDOWS' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + clang++ -I. -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 @@ -324,6 +332,13 @@ jobs: echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp clang++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + - name: Build example_null (without c++ runtime) + run: | + echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp + clang++ -I. -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2ad7a085..da94c890 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,9 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, + static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). + Fixed a static contructor which led to this dependency on some compiler setups (unclear which). - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, @@ -67,7 +70,7 @@ Other Changes: - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Backends: OSX: Added workaround to avoid fast mouse clicks. (#3261, #1992, #2525) [@nburrus] -- Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm +- Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm not forwarding right and center mouse clicks. (#3260) [@nburrus] From 0fe5170bc400b789dcb3038eb0ead9d540927dfd Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 16:28:55 +0200 Subject: [PATCH 057/959] Viewports: Report minimized viewports as zero DisplaySize to be consistent with main branch + comments (#1542) --- imgui.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index bec67413..f580bc22 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4363,6 +4363,13 @@ void ImDrawDataBuilder::FlattenIntoSingleLayer() static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector* draw_lists) { + // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode, + // and to allow applications/back-ends to easily skip rendering. + // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure. + // This is because the work has been done already, and its wasted! We should fix that and add optimizations for + // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline. + const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0; + ImDrawData* draw_data = &viewport->DrawDataP; viewport->DrawData = draw_data; // Make publicly accessible draw_data->Valid = true; @@ -4370,7 +4377,7 @@ static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVectorCmdListsCount = draw_lists->Size; draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; draw_data->DisplayPos = viewport->Pos; - draw_data->DisplaySize = viewport->Size; + draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size; draw_data->FramebufferScale = ImGui::GetIO().DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis? draw_data->OwnerViewport = viewport; for (int n = 0; n < draw_lists->Size; n++) From a06eb833590478276a3c186a7b66a9cf5082ebf4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 15:31:33 +0200 Subject: [PATCH 058/959] Examples: GLFW+Vulkan, SDL+Vulkan: Fix for handling of minimized windows. (#3259) --- docs/CHANGELOG.txt | 1 + examples/example_glfw_vulkan/main.cpp | 20 ++++++++++++-------- examples/example_sdl_vulkan/main.cpp | 23 +++++++++++++++-------- examples/imgui_impl_vulkan.cpp | 1 + 4 files changed, 29 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index da94c890..dff65283 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,7 @@ Other Changes: - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] - Backends: OSX: Added workaround to avoid fast mouse clicks. (#3261, #1992, #2525) [@nburrus] +- Examples: GLFW+Vulkan, SDL+Vulkan: Fix for handling of minimized windows. (#3259) - Examples: Apple: Fixed example_apple_metal and example_apple_opengl2 using imgui_impl_osx.mm not forwarding right and center mouse clicks. (#3260) [@nburrus] diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 15ec2068..3ce1984a 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -248,7 +248,7 @@ static void CleanupVulkanWindow() ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } -static void FrameRender(ImGui_ImplVulkanH_Window* wd) +static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { VkResult err; @@ -286,8 +286,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); } - // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); + // Record dear imgui primitives into command buffer + ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -456,7 +456,8 @@ int main(int, char**) // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); - if (g_SwapChainRebuild) + // Resize swap chain? + if (g_SwapChainRebuild && g_SwapChainResizeWidth > 0 && g_SwapChainResizeHeight > 0) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); @@ -508,10 +509,13 @@ int main(int, char**) // Rendering ImGui::Render(); - memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); - FrameRender(wd); - - FramePresent(wd); + ImDrawData* draw_data = ImGui::GetDrawData(); + const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); + if (!is_minimized) + { + FrameRender(wd, draw_data); + FramePresent(wd); + } } // Cleanup diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 53975516..9eaea945 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -240,7 +240,7 @@ static void CleanupVulkanWindow() ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); } -static void FrameRender(ImGui_ImplVulkanH_Window* wd) +static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) { VkResult err; @@ -278,8 +278,8 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd) vkCmdBeginRenderPass(fd->CommandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); } - // Record Imgui Draw Data and draw funcs into command buffer - ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), fd->CommandBuffer); + // Record dear imgui primitives into command buffer + ImGui_ImplVulkan_RenderDrawData(draw_data, fd->CommandBuffer); // Submit command buffer vkCmdEndRenderPass(fd->CommandBuffer); @@ -447,13 +447,17 @@ int main(int, char**) done = true; if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) { + // Note: your own application may rely on SDL_WINDOWEVENT_MINIMIZED/SDL_WINDOWEVENT_RESTORED to skip updating all-together. + // Here ImGui_ImplSDL2_NewFrame() will set io.DisplaySize to zero which will disable rendering but let application run. + // Please note that you can't Present into a minimized window. g_SwapChainResizeWidth = (int)event.window.data1; g_SwapChainResizeHeight = (int)event.window.data2; g_SwapChainRebuild = true; } } - if (g_SwapChainRebuild) + // Resize swap chain? + if (g_SwapChainRebuild && g_SwapChainResizeWidth > 0 && g_SwapChainResizeHeight > 0) { g_SwapChainRebuild = false; ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); @@ -505,10 +509,13 @@ int main(int, char**) // Rendering ImGui::Render(); - memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); - FrameRender(wd); - - FramePresent(wd); + ImDrawData* draw_data = ImGui::GetDrawData(); + const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); + if (!is_minimized) + { + FrameRender(wd, draw_data); + FramePresent(wd); + } } // Cleanup diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 93c3b404..c65b2db0 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -999,6 +999,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; + wd->Swapchain = NULL; err = vkDeviceWaitIdle(device); check_vk_result(err); From 5ddf60d8ce57ad119833003f9afd777c0b1a3a74 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 25 May 2020 18:28:25 +0200 Subject: [PATCH 059/959] Commit to facilitate branches merges --- imgui.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 97b15411..68b50827 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10158,8 +10158,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Debugging enums enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" }; - enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersDesired, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type - const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersDesired", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; + enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type + const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; // State static bool show_windows_rects = false; @@ -10433,7 +10433,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) } }; - // Tools if (ImGui::TreeNode("Tools")) { @@ -10504,7 +10503,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeTable(g.Tables.GetByIndex(n)); ImGui::TreePop(); } -#endif // #define IMGUI_HAS_TABLE +#endif // #ifdef IMGUI_HAS_TABLE // Details for Docking #ifdef IMGUI_HAS_DOCK @@ -10512,7 +10511,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) { ImGui::TreePop(); } -#endif // #define IMGUI_HAS_DOCK +#endif // #ifdef IMGUI_HAS_DOCK // Settings if (ImGui::TreeNode("Settings")) @@ -10548,10 +10547,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) Funcs::NodeTableSettings(settings); ImGui::TreePop(); } -#endif +#endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK -#endif +#endif // #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { @@ -10617,14 +10616,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGuiTable* table = g.Tables.GetByIndex(table_n); } } -#endif // #define IMGUI_HAS_TABLE +#endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK // Overlay: Display Docking info if (show_docking_nodes && g.IO.KeyCtrl) { } -#endif // #define IMGUI_HAS_DOCK +#endif // #ifdef IMGUI_HAS_DOCK ImGui::End(); } From 3f26a07ee1813cecaa87253436149e28fc11dc4e Mon Sep 17 00:00:00 2001 From: Giovanni Funchal Date: Thu, 21 May 2020 12:49:06 +0100 Subject: [PATCH 060/959] Backends: OpenGL: Fixed loader auto-detection to not interfere with ES2/ES3 defines. (#3246) --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_opengl3.cpp | 20 ------------ examples/imgui_impl_opengl3.h | 57 ++++++++++++++++++++------------- 3 files changed, 36 insertions(+), 42 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dff65283..96d439be 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,7 @@ Other Changes: - Backends: OpenGL: Fixed handling of GL 4.5+ glClipControl(GL_UPPER_LEFT) by inverting the projection matrix top and bottom values. (#3143, #3146) [@u3shit] - Backends: OpenGL: On OSX, if unspecified by app, made default GLSL version 150. (#3199) [@albertvaka] +- Backends: OpenGL: Fixed loader auto-detection to not interfere with ES2/ES3 defines. (#3246) [@funchal] - Backends: Vulkan: Fixed error in if initial frame has no vertices. (#3177) - Backends: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData structure didn't have any vertices. (#2697) [@kudaba] diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 61131eb6..3ad04a41 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -79,27 +79,7 @@ #else #include // intptr_t #endif -#if defined(__APPLE__) -#include "TargetConditionals.h" -#endif -// Auto-enable GLES on matching platforms -#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) -#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) -#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" -#elif defined(__EMSCRIPTEN__) -#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" -#endif -#endif - -#if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) -#undef IMGUI_IMPL_OPENGL_LOADER_GL3W -#undef IMGUI_IMPL_OPENGL_LOADER_GLEW -#undef IMGUI_IMPL_OPENGL_LOADER_GLAD -#undef IMGUI_IMPL_OPENGL_LOADER_GLBINDING2 -#undef IMGUI_IMPL_OPENGL_LOADER_GLBINDING3 -#undef IMGUI_IMPL_OPENGL_LOADER_CUSTOM -#endif // GL includes #if defined(IMGUI_IMPL_OPENGL_ES2) diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index d55935a1..07d35219 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -12,7 +12,7 @@ // https://github.com/ocornut/imgui // About Desktop OpenGL function loaders: -// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. +// Modern Desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. // Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad). // You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own. @@ -36,36 +36,49 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); -// Specific OpenGL versions +// Specific OpenGL ES versions //#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten //#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android -// Desktop OpenGL: attempt to detect default GL loader based on available header files. +// Attempt to auto-detect the default Desktop GL loader based on available header files. // If auto-detection fails or doesn't select the same GL loader file as used by your application, // you are likely to get a crash in ImGui_ImplOpenGL3_Init(). -// You can explicitly select a loader by using '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. -#if !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ +// You can explicitly select a loader by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. +#if !defined(IMGUI_IMPL_OPENGL_ES2) \ + && !defined(IMGUI_IMPL_OPENGL_ES3) \ + && !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) - #if defined(__has_include) - #if __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLEW - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLAD - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GL3W - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING3 - #elif __has_include() - #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING2 - #else - #error "Cannot detect OpenGL loader!" - #endif - #else - #define IMGUI_IMPL_OPENGL_LOADER_GL3W // Default to GL3W - #endif + +// Try to detect GLES on matching platforms +#if defined(__APPLE__) +#include "TargetConditionals.h" #endif +#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) +#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" +#elif defined(__EMSCRIPTEN__) +#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" +// Otherwise try to detect supported Desktop OpenGL loaders.. +#elif defined(__has_include) +#if __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLEW +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLAD +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GL3W +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +#else + #error "Cannot detect OpenGL loader!" +#endif +#else + #define IMGUI_IMPL_OPENGL_LOADER_GL3W // Default to GL3W embedded in our repository +#endif + +#endif From 41e8837f5948fae98f5fb1892f0e408aa806a2f2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jun 2020 18:13:54 +0200 Subject: [PATCH 061/959] Comments, adding some spacing in ImVec2() constructors. --- imgui.cpp | 10 +++++----- imgui.h | 35 ++++++++++++++++++----------------- imgui_demo.cpp | 8 ++++---- imgui_draw.cpp | 2 +- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 10 +++++----- 6 files changed, 36 insertions(+), 35 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 68b50827..82de5dfb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -505,7 +505,7 @@ CODE - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. - - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))' + - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))' - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. @@ -5083,10 +5083,10 @@ static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_ { ImRect rect = window->Rect(); if (thickness == 0.0f) rect.Max -= ImVec2(1,1); - if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top - if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right - if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom - if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left + if (border_n == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top + if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right + if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom + if (border_n == 3) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); } // Left IM_ASSERT(0); return ImRect(); } diff --git a/imgui.h b/imgui.h index 1a8d7a40..824c98de 100644 --- a/imgui.h +++ b/imgui.h @@ -268,9 +268,10 @@ namespace ImGui // Windows // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. - // - You may append multiple times to the same window during the same frame. // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, // which clicking will set the boolean to false when clicked. + // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. + // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, @@ -285,8 +286,8 @@ namespace ImGui // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. // Always call a matching EndChild() for each BeginChild() call, regardless of its return value [as with Begin: this is due to legacy reason and inconsistent with most BeginXXX functions apart from the regular Begin() which behaves like BeginChild().] - IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); - IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); IMGUI_API void EndChild(); // Windows Utilities @@ -302,7 +303,7 @@ namespace ImGui IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) // Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). - IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints. IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() @@ -310,7 +311,7 @@ namespace ImGui IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin() IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. - 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 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); // 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(). @@ -433,17 +434,17 @@ namespace ImGui // Widgets: Main // - Most widgets return true when the value has been changed or when pressed/selected // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. - IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); - 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)); // <0 frame_padding uses default frame padding settings. 0 for no padding + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); + 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)); // <0 frame_padding uses default frame padding settings. 0 for no padding IMGUI_API bool Checkbox(const char* label, bool* v); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer - IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1, 0), const char* overlay = NULL); IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses // Widgets: Combo Box @@ -498,7 +499,7 @@ namespace ImGui // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0); IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0); @@ -519,7 +520,7 @@ namespace ImGui IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); - IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed. + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a colored square/button, hover for details, return true when pressed. IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. // Widgets: Trees @@ -545,14 +546,14 @@ namespace ImGui // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. - IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height - IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. // Widgets: List Boxes // - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them. IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); - IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards. + IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards. IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true! @@ -1487,7 +1488,7 @@ struct ImGuiIO // Input - Fill before calling NewFrame() //------------------------------------------------------------------ - ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.) + ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends. @@ -2158,7 +2159,7 @@ struct ImFontAtlasCustomRect 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() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } + ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; } bool IsPacked() const { return X != 0xFFFF; } }; @@ -2239,7 +2240,7 @@ struct ImFontAtlas // Read docs/FONTS.txt 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)); + IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0)); const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } // [Internal] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 42f0844a..8cece7be 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2676,7 +2676,7 @@ static void ShowDemoWindowLayout() } if (show_child) { - ImGui::BeginChild("child", ImVec2(0,0), true); + ImGui::BeginChild("child", ImVec2(0, 0), true); ImGui::EndChild(); } ImGui::End(); @@ -4373,7 +4373,7 @@ struct ExampleAppLog Filter.Draw("Filter", -100.0f); ImGui::Separator(); - ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); + ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar); if (clear) Clear(); @@ -4646,7 +4646,7 @@ static void ShowExampleAppLongText(bool* p_open) case 1: { // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); ImGuiListClipper clipper(lines); while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) @@ -4656,7 +4656,7 @@ static void ShowExampleAppLongText(bool* p_open) } case 2: // Multiple calls to Text(), not clipped (slow) - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); for (int i = 0; i < lines; i++) ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); ImGui::PopStyleVar(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2dfccf07..057ddb65 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2873,7 +2873,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons const float line_height = size; const float scale = size / FontSize; - ImVec2 text_size = ImVec2(0,0); + ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; const bool word_wrap_enabled = (wrap_width > 0.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 2802f519..96e7b19e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1597,7 +1597,7 @@ struct IMGUI_API ImGuiWindow ImGuiCond SetWindowSizeAllowFlags; // store acceptable condition flags for SetNextWindowSize() use. ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use. ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) - ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0,0) when positioning from top-left corner; ImVec2(0.5f,0.5f) for centering; ImVec2(1,1) for bottom right. + ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right. ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. @@ -1920,7 +1920,7 @@ namespace ImGui // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); 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 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 RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); @@ -1946,7 +1946,7 @@ namespace ImGui // Widgets IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); - IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); + IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e509c039..07be3b36 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1225,7 +1225,7 @@ void ImGui::Spacing() ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - ItemSize(ImVec2(0,0)); + ItemSize(ImVec2(0, 0)); } void ImGui::Dummy(const ImVec2& size) @@ -1249,7 +1249,7 @@ void ImGui::NewLine() const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; window->DC.LayoutType = ImGuiLayoutType_Vertical; if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. - ItemSize(ImVec2(0,0)); + ItemSize(ImVec2(0, 0)); else ItemSize(ImVec2(0.0f, g.FontSize)); window->DC.LayoutType = backup_layout_type; @@ -1611,7 +1611,7 @@ bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(voi // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here. if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)) - SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); + SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) return false; @@ -3182,7 +3182,7 @@ bool ImGui::InputDouble(const char* label, double* v, double step, double step_f bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() - return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); + return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); } bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) @@ -3217,7 +3217,7 @@ static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* t const float line_height = g.FontSize; const float scale = line_height / font->FontSize; - ImVec2 text_size = ImVec2(0,0); + ImVec2 text_size = ImVec2(0, 0); float line_width = 0.0f; const ImWchar* s = text_begin; From 5e976e9b0584878b5503fd86e81795c14981d1de Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 3 Jun 2020 22:04:14 +0200 Subject: [PATCH 062/959] Title capitalization (#3280) --- docs/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/README.md b/docs/README.md index e8fa16f1..5536c5bc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,8 +1,8 @@ -dear imgui +Dear ImGui ===== [![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) -(This library is available under a free and permissive license, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using dear imgui, please consider reaching out.) +(This library is available under a free and permissive license, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out.) Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts:
  _E-mail: contact @ dearimgui dot org_ @@ -86,7 +86,7 @@ Dear ImGui allows you to **create elaborate tools** as well as very short-lived Check out the Wiki's [About the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#About-the-IMGUI-paradigm) section if you want to understand the core principles behind the IMGUI paradigm. An IMGUI tries to minimize superfluous state duplication, state synchronization and state retention from the user's point of view. It is less error prone (less code and less bugs) than traditional retained-mode interfaces, and lends itself to create dynamic user interfaces. -Dear ImGui outputs vertex buffers and command lists that you can easily render in your application. The number of draw calls and state changes required to render them is fairly small. Because Dear ImGui doesn't know or touch graphics state directly, you can call its functions anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate dear imgui with your existing codebase. +Dear ImGui outputs vertex buffers and command lists that you can easily render in your application. The number of draw calls and state changes required to render them is fairly small. Because Dear ImGui doesn't know or touch graphics state directly, you can call its functions anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate Dear ImGui with your existing codebase. _A common misunderstanding is to mistake immediate mode gui for immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes as the gui functions are called. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely._ @@ -178,7 +178,7 @@ How to help **How can I help financing further development of Dear ImGui?** -Your contributions are keeping this project alive. The library is available under a free and permissive license, but continued maintenance and development are a full-time endeavor and I would like to grow the team. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using dear imgui, please consider reaching out for invoiced technical support and maintenance contracts. Thank you! +Your contributions are keeping this project alive. The library is available under a free and permissive license, but continued maintenance and development are a full-time endeavor and I would like to grow the team. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out for invoiced technical support and maintenance contracts. Thank you! Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts:
  _E-mail: contact @ dearimgui dot org_ From 53dfccbe4b047539ed4a173fbfd95bf2f5856ea2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Jun 2020 17:53:41 +0200 Subject: [PATCH 063/959] imgui_freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. (#618) --- docs/CHANGELOG.txt | 1 + misc/freetype/imgui_freetype.cpp | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 96d439be..e7ff09d7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,7 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). Fixed a static contructor which led to this dependency on some compiler setups (unclear which). diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 69108e3e..20a3be0e 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -13,6 +13,7 @@ // - v0.60: (2019/01/10) re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding. // - v0.61: (2019/01/15) added support for imgui allocators + added FreeType only override function SetAllocatorFunctions(). // - v0.62: (2019/02/09) added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!) +// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. // Gamma Correct Blending: // FreeType assumes blending in linear space rather than gamma space. @@ -467,7 +468,6 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i]; const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint); - IM_ASSERT(metrics != NULL); if (metrics == NULL) continue; @@ -559,6 +559,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns 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); From 79fbab543d229c8526d4d05078028f7fa0656c7b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 4 Jun 2020 18:59:04 +0200 Subject: [PATCH 064/959] Minor fix to avoid undefined behavior sanitizer triggering (#3276) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 82de5dfb..b74f44cf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3516,7 +3516,7 @@ static void ImGui::UpdateMouseInputs() ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; - g.IO.MouseClickedTime[i] = -DBL_MAX; // so the third click isn't turned into a double-click + g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" so the third click isn't turned into a double-click } else { From 6eb66fbef3f6c65b9612170fae2ea150b6082b7a Mon Sep 17 00:00:00 2001 From: Mark Jansen Date: Fri, 5 Jun 2020 01:23:18 +0200 Subject: [PATCH 065/959] Backends: Win32: Cache the result of a windows version check. (#3283) This is not expected to change while the application is running :) --- examples/imgui_impl_win32.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index ae18eb6e..57d6e3ed 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -417,7 +417,8 @@ void ImGui_ImplWin32_EnableDpiAwareness() float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { UINT xdpi = 96, ydpi = 96; - if (IsWindows8Point1OrGreater()) + static BOOL bIsWindows8Point1OrGreater = IsWindows8Point1OrGreater(); + if (bIsWindows8Point1OrGreater) { static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor")) From dc49b14e2983547a165e5dc43edcee0e51b496c8 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 5 Jun 2020 14:47:49 +0300 Subject: [PATCH 066/959] Misc: Fix examples of using other OpenGL3 bindings in Makefiles. --- examples/example_glfw_opengl3/Makefile | 9 ++++++--- examples/example_sdl_opengl3/Makefile | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/examples/example_glfw_opengl3/Makefile b/examples/example_glfw_opengl3/Makefile index 7696eaae..3bc72b6f 100644 --- a/examples/example_glfw_opengl3/Makefile +++ b/examples/example_glfw_opengl3/Makefile @@ -35,7 +35,8 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glew ## (This assumes a system-wide installation) -# CXXFLAGS += -lGLEW -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# LIBS += -lGLEW ## Using OpenGL loader: glad # SOURCES += ../libs/glad/src/glad.c @@ -44,9 +45,11 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# LIBS += -lglbinding ## or the older version 2.x -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# LIBS += -lglbinding ##--------------------------------------------------------------------- ## BUILD FLAGS PER PLATFORM diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index e8b2f566..41826741 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -35,7 +35,8 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glew ## (This assumes a system-wide installation) -# CXXFLAGS += -lGLEW -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLEW +# LIBS += -lGLEW ## Using OpenGL loader: glad # SOURCES += ../libs/glad/src/glad.c @@ -44,9 +45,11 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING3 +# LIBS += -lglbinding ## or the older version 2.x -# CXXFLAGS += -lglbinding -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_LOADER_GLBINDING2 +# LIBS += -lglbinding ##--------------------------------------------------------------------- ## BUILD FLAGS PER PLATFORM From 5af8a8c7e83e735a1640d9347aa31c94d10e71fa Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 5 Jun 2020 13:04:55 +0300 Subject: [PATCH 067/959] CI: Extra warnings for builds with Clang. Backends: OpenGL3: Fix sign conversion warnings. --- examples/example_null/Makefile | 7 +++++-- examples/imgui_impl_opengl3.cpp | 26 +++++++++++++------------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 0ccee11b..15c547a5 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -40,7 +40,10 @@ endif ifeq ($(UNAME_S), Linux) #LINUX ECHO_MESSAGE = "Linux" ifneq ($(WITH_EXTRA_WARNINGS), 0) - CXXFLAGS += -Wextra -pedantic + CXXFLAGS += -Wextra -Wpedantic + ifeq ($(shell $(CXX) -v 2>&1 | grep -c "clang version"), 1) + CXXFLAGS += -Wshadow -Wsign-conversion + endif endif CFLAGS = $(CXXFLAGS) endif @@ -56,7 +59,7 @@ endif ifeq ($(findstring MINGW,$(UNAME_S)),MINGW) ECHO_MESSAGE = "MinGW" ifneq ($(WITH_EXTRA_WARNINGS), 0) - CXXFLAGS += -Wextra -pedantic + CXXFLAGS += -Wextra -Wpedantic endif CFLAGS = $(CXXFLAGS) endif diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 3ad04a41..028a704b 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -132,8 +132,8 @@ static GLuint g_GlVersion = 0; // Extracted at runtime usin static char g_GlslVersionString[32] = ""; // Specified by user or detected based on compile time GL settings. static GLuint g_FontTexture = 0; static GLuint g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; -static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location -static int g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location +static GLint g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; // Uniforms location +static GLuint g_AttribLocationVtxPos = 0, g_AttribLocationVtxUV = 0, g_AttribLocationVtxColor = 0; // Vertex attributes location static unsigned int g_VboHandle = 0, g_ElementsHandle = 0; // Functions @@ -144,7 +144,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) GLint major, minor; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); - g_GlVersion = major * 100 + minor * 10; + g_GlVersion = (GLuint)(major * 100 + minor * 10); #else g_GlVersion = 200; // GLES 2 #endif @@ -292,14 +292,14 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Backup GL state GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); glActiveTexture(GL_TEXTURE0); - GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); - GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); + GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); #ifdef GL_SAMPLER_BINDING - GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler); + GLuint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); #endif - GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_ES2 - GLint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array_object); + GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object); #endif #ifdef GL_POLYGON_MODE GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); @@ -336,8 +336,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) const ImDrawList* cmd_list = draw_data->CmdLists[n]; // Upload vertex/index buffers - glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); + glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { @@ -643,9 +643,9 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); - g_AttribLocationVtxPos = glGetAttribLocation(g_ShaderHandle, "Position"); - g_AttribLocationVtxUV = glGetAttribLocation(g_ShaderHandle, "UV"); - g_AttribLocationVtxColor = glGetAttribLocation(g_ShaderHandle, "Color"); + g_AttribLocationVtxPos = (GLuint)glGetAttribLocation(g_ShaderHandle, "Position"); + g_AttribLocationVtxUV = (GLuint)glGetAttribLocation(g_ShaderHandle, "UV"); + g_AttribLocationVtxColor = (GLuint)glGetAttribLocation(g_ShaderHandle, "Color"); // Create buffers glGenBuffers(1, &g_VboHandle); From 78d5ccfb9012bdf9e25317aa11fc79e7e639c8fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 16:44:31 +0200 Subject: [PATCH 068/959] ImDrawList: PushColumnsBackground(): Fixed incorrect assert. (#3163) --- imgui_widgets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 07be3b36..2ba7c6b4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7553,7 +7553,7 @@ void ImGui::PushColumnsBackground() int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); IM_UNUSED(cmd_size); - IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd + IM_ASSERT(cmd_size >= window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } void ImGui::PopColumnsBackground() From e22e3f300af3b913e3209bde2a9dff91ed637807 Mon Sep 17 00:00:00 2001 From: thedmd Date: Sat, 6 Jun 2020 16:37:07 +0200 Subject: [PATCH 069/959] ImDrawList: Fixed an issue when draw command merging or cancelling while crossing the VtxOffset boundary would lead to draw command being emitted with wrong VtxOffset value. (#3129, #3163, #3232) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 2 +- imgui_draw.cpp | 32 ++++++++++++++++++++++---------- 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e7ff09d7..54e5a113 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,9 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- ImDrawList: Fixed an issue when draw command merging or cancelling while crossing the VtxOffset + boundary would lead to draw command being emitted with wrong VtxOffset value. (#3129, #3163, #3232) + [@thedmd, @Shironekoben, @sergeyn, @ocornut] - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). diff --git a/imgui.cpp b/imgui.cpp index b74f44cf..0c2156d5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10267,7 +10267,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; char buf[300]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd: %4d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 057ddb65..0e56b3f4 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -460,11 +460,17 @@ void ImDrawList::UpdateClipRect() } // Try to merge with previous command if it matches, else use current command - ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; - if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) - CmdBuffer.pop_back(); - else - curr_cmd->ClipRect = curr_clip_rect; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + { + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + } + + curr_cmd->ClipRect = curr_clip_rect; } void ImDrawList::UpdateTextureID() @@ -479,11 +485,17 @@ void ImDrawList::UpdateTextureID() } // Try to merge with previous command if it matches, else use current command - ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; - if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) - CmdBuffer.pop_back(); - else - curr_cmd->TextureId = curr_texture_id; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + { + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->UserCallback == NULL) + { + CmdBuffer.pop_back(); + return; + } + } + + curr_cmd->TextureId = curr_texture_id; } #undef GetCurrentClipRect From 003153b3acbbb0022d35ea7fba4155c6706d801e Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 19:52:41 +0200 Subject: [PATCH 070/959] ImDrawList: Tweaks to make style consistent (using pointers, same local names). Added comments. Should be no-op. --- imgui.cpp | 8 ++++---- imgui.h | 20 ++++++++++---------- imgui_draw.cpp | 22 +++++++++++----------- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0c2156d5..01ceafe9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4077,15 +4077,15 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list) { - if (draw_list->CmdBuffer.empty()) + if (draw_list->CmdBuffer.Size == 0) return; // Remove trailing command if unused - ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); - if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) + ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.back(); + if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL) { draw_list->CmdBuffer.pop_back(); - if (draw_list->CmdBuffer.empty()) + if (draw_list->CmdBuffer.Size == 0) return; } diff --git a/imgui.h b/imgui.h index 824c98de..ebad93cb 100644 --- a/imgui.h +++ b/imgui.h @@ -1878,13 +1878,13 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c // is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. struct ImDrawCmd { - unsigned int ElemCount; // 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[]. - ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates - ImTextureID TextureId; // 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. - unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bit indices. - unsigned int IdxOffset; // Start offset in index buffer. Always equal to sum of ElemCount drawn so far. - ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. - void* UserCallbackData; // The draw callback code can access this. + 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[]. + 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. + unsigned int VtxOffset; // 4 // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bit indices. + unsigned int IdxOffset; // 4 // Start offset in index buffer. Always equal to sum of ElemCount drawn so far. + ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // 4-8 // The draw callback code can access this. ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; } }; @@ -1984,7 +1984,7 @@ struct ImDrawList ImVector _ClipRectStack; // [Internal] ImVector _TextureIdStack; // [Internal] ImVector _Path; // [Internal] current path building - ImDrawListSplitter _Splitter; // [Internal] for channels api + ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); } @@ -2048,13 +2048,13 @@ struct ImDrawList // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) // - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place! - // Prefer using your own persistent copy of ImDrawListSplitter as you can stack them. + // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. inline void ChannelsSplit(int count) { _Splitter.Split(this, count); } inline void ChannelsMerge() { _Splitter.Merge(this); } inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } - // Internal helpers + // [Internal helpers] // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void Clear(); IMGUI_API void ClearFreeMemory(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0e56b3f4..91de2ae6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -434,14 +434,14 @@ void ImDrawList::AddDrawCmd() void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { - ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; - if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; + if (!curr_cmd || curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) { AddDrawCmd(); - current_cmd = &CmdBuffer.back(); + curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; } - current_cmd->UserCallback = callback; - current_cmd->UserCallbackData = callback_data; + curr_cmd->UserCallback = callback; + curr_cmd->UserCallbackData = callback_data; AddDrawCmd(); // Force a new command after us (see comment below) } @@ -452,7 +452,7 @@ void ImDrawList::UpdateClipRect() { // If current command is used with different settings we need to add a new command const ImVec4 curr_clip_rect = GetCurrentClipRect(); - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); @@ -477,7 +477,7 @@ void ImDrawList::UpdateTextureID() { // If current command is used with different settings we need to add a new command const ImTextureID curr_texture_id = GetCurrentTextureId(); - ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); @@ -559,8 +559,8 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) AddDrawCmd(); } - ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size - 1]; - draw_cmd.ElemCount += idx_count; + ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount += idx_count; int vtx_buffer_old_size = VtxBuffer.Size; VtxBuffer.resize(vtx_buffer_old_size + vtx_count); @@ -576,8 +576,8 @@ void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) { IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); - ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size - 1]; - draw_cmd.ElemCount -= idx_count; + ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + draw_cmd->ElemCount -= idx_count; VtxBuffer.shrink(VtxBuffer.Size - vtx_count); IdxBuffer.shrink(IdxBuffer.Size - idx_count); } From 0320e7257babeac02337771e1249317b44664a85 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 20:25:56 +0200 Subject: [PATCH 071/959] ImDrawList: Small refactor to create empty command when beginning the frame, allowing to simplify some functions. + Missing clearing two fields in ClearFreeMemory() (was hamrless) --- imgui.cpp | 6 +++--- imgui.h | 5 +++-- imgui_draw.cpp | 18 +++++++++++------- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 01ceafe9..07a832c4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3777,11 +3777,11 @@ void ImGui::NewFrame() if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; - g.BackgroundDrawList.Clear(); + g.BackgroundDrawList.ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); - g.ForegroundDrawList.Clear(); + g.ForegroundDrawList.ResetForNewFrame(); g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.ForegroundDrawList.PushClipRectFullScreen(); @@ -5860,7 +5860,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // DRAWING // Setup draw list and outer clipping rectangle - window->DrawList->Clear(); + window->DrawList->ResetForNewFrame(); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); diff --git a/imgui.h b/imgui.h index ebad93cb..7906ae07 100644 --- a/imgui.h +++ b/imgui.h @@ -1987,7 +1987,8 @@ struct ImDrawList ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) - ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); } + ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; Flags = ImDrawListFlags_None; _VtxCurrentOffset = _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } + ~ImDrawList() { ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, 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(); @@ -2056,7 +2057,7 @@ struct ImDrawList // [Internal helpers] // NB: all primitives needs to be reserved via PrimReserve() beforehand! - IMGUI_API void Clear(); + IMGUI_API void ResetForNewFrame(); IMGUI_API void ClearFreeMemory(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 91de2ae6..d5844dbe 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -376,12 +376,13 @@ void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) } } -void ImDrawList::Clear() +// Initialize before use in a new frame. We always have a command ready in the buffer. +void ImDrawList::ResetForNewFrame() { CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); - Flags = _Data ? _Data->InitialFlags : ImDrawListFlags_None; + Flags = _Data->InitialFlags; _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; @@ -390,6 +391,7 @@ void ImDrawList::Clear() _TextureIdStack.resize(0); _Path.resize(0); _Splitter.Clear(); + CmdBuffer.push_back(ImDrawCmd()); } void ImDrawList::ClearFreeMemory() @@ -397,6 +399,8 @@ void ImDrawList::ClearFreeMemory() CmdBuffer.clear(); IdxBuffer.clear(); VtxBuffer.clear(); + Flags = ImDrawListFlags_None; + _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -434,8 +438,8 @@ void ImDrawList::AddDrawCmd() void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; - if (!curr_cmd || curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) { AddDrawCmd(); curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -452,8 +456,8 @@ void ImDrawList::UpdateClipRect() { // If current command is used with different settings we need to add a new command const ImVec4 curr_clip_rect = GetCurrentClipRect(); - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; - if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; @@ -477,7 +481,7 @@ void ImDrawList::UpdateTextureID() { // If current command is used with different settings we need to add a new command const ImTextureID curr_texture_id = GetCurrentTextureId(); - ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size - 1] : NULL; + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); From 41f47c853bf300024a70482f3de76c6f2b68833c Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 20:35:29 +0200 Subject: [PATCH 072/959] ImDrawList: Amend 0320e72 removed an unnecessary test. --- imgui_draw.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d5844dbe..97a5c9f7 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -482,7 +482,7 @@ void ImDrawList::UpdateTextureID() // If current command is used with different settings we need to add a new command const ImTextureID curr_texture_id = GetCurrentTextureId(); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; From f6120f8e16eefcdb37b63974e6915a3dd35414be Mon Sep 17 00:00:00 2001 From: ocornut Date: Sat, 6 Jun 2020 21:31:31 +0200 Subject: [PATCH 073/959] ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#259 --- docs/CHANGELOG.txt | 12 +++++++----- imgui_draw.cpp | 1 + 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 54e5a113..5f9f7b16 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,9 +56,11 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] -- ImDrawList: Fixed an issue when draw command merging or cancelling while crossing the VtxOffset - boundary would lead to draw command being emitted with wrong VtxOffset value. (#3129, #3163, #3232) +- ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the + VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current + VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). @@ -555,11 +557,11 @@ Other Changes: - Log/Capture: Fixed BeginTabItem() label not being included in a text log/capture. - ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bit indices. The renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' to enable - this, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. + this, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. (#2591) This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not support 32-bit indices. Most examples back-ends have been modified to support the VtxOffset field. - ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. - This is provided for convenience and consistency with VtxOffset. + This is provided for convenience and consistency with VtxOffset. (#2591) - ImDrawCallback: Allow to override the signature of ImDrawCallback by #define-ing it. This is meant to facilitate custom rendering back-ends passing local render-specific data to the draw callback. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. Combine @@ -571,7 +573,7 @@ Other Changes: dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] - Examples/Backends: DirectX9/10/11/12, Metal, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes - (64k+ vertices) with 16-bit indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. + (64k+ vertices) with 16-bit indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. (#2591) - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 97a5c9f7..e3455812 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1359,6 +1359,7 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) ImDrawCmd draw_cmd; draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); draw_cmd.TextureId = draw_list->_TextureIdStack.back(); + draw_cmd.VtxOffset = draw_list->_VtxCurrentOffset; _Channels[i]._CmdBuffer.push_back(draw_cmd); } } From 57191fe3d088b4895bbee75e8622413a4deeed90 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 14:17:49 +0200 Subject: [PATCH 074/959] Comments about limiting WindowRounding to a reasonable size. --- imgui.cpp | 7 ++++++- imgui.h | 2 +- imgui_internal.h | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 07a832c4..95dc22a6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1008,7 +1008,7 @@ ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window - WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. WindowMinSize = ImVec2(32,32); // Minimum window size WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text @@ -5757,8 +5757,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Pos = ImFloor(window->Pos); // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + // Large values tend to lead to variety of artifacts and are not recommended. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; + // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts. + //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f); + // Apply window focus (new and reactivated windows are moved to front) bool want_focus = false; if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) diff --git a/imgui.h b/imgui.h index 7906ae07..8fcd5416 100644 --- a/imgui.h +++ b/imgui.h @@ -1371,7 +1371,7 @@ struct ImGuiStyle { float Alpha; // Global alpha applies to everything in Dear ImGui. ImVec2 WindowPadding; // Padding within a window. - float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints(). ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. diff --git a/imgui_internal.h b/imgui_internal.h index 96e7b19e..7b15e63f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1561,7 +1561,7 @@ struct IMGUI_API ImGuiWindow ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). ImVec2 WindowPadding; // Window padding at the time of Begin(). - float WindowRounding; // Window rounding at the time of Begin(). + float WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. float WindowBorderSize; // Window border size at the time of Begin(). int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)! ImGuiID MoveId; // == window->GetID("#MOVE") From a6bb047baba31c3a4038b9f1b06977e7c0feb08e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 15:22:44 +0200 Subject: [PATCH 075/959] ImDrawList: Store header/current ImDrawCmd in instance to simplify merging code. Amend 0320e72, toward #3163, #3129 --- imgui.h | 16 ++++---- imgui_draw.cpp | 102 +++++++++++++++++++++++-------------------------- 2 files changed, 57 insertions(+), 61 deletions(-) diff --git a/imgui.h b/imgui.h index 8fcd5416..45f3aa7c 100644 --- a/imgui.h +++ b/imgui.h @@ -1874,19 +1874,21 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) // Typically, 1 command = 1 GPU draw call (unless command is a callback) -// Pre 1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' -// is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// - VtxOffset/IdxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, +// those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. +// Pre-1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. +// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). struct ImDrawCmd { - 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[]. 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. - unsigned int VtxOffset; // 4 // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bit indices. + 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. Always equal to sum of ElemCount drawn so far. + 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[]. ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // 4-8 // The draw callback code can access this. - ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; } + ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed }; // Vertex index, default to 16-bit @@ -1977,17 +1979,17 @@ struct ImDrawList // [Internal, used while building lists] const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) const char* _OwnerName; // Pointer to owner window's name for debugging - unsigned int _VtxCurrentOffset; // [Internal] Always 0 unless 'Flags & ImDrawListFlags_AllowVtxOffset'. unsigned int _VtxCurrentIdx; // [Internal] Generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. 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) ImVector _ClipRectStack; // [Internal] ImVector _TextureIdStack; // [Internal] ImVector _Path; // [Internal] current path building + ImDrawCmd _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!) // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) - ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; Flags = ImDrawListFlags_None; _VtxCurrentOffset = _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } + ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; Flags = ImDrawListFlags_None; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } ~ImDrawList() { ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, 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) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e3455812..43daede2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -379,11 +379,17 @@ void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) // Initialize before use in a new frame. We always have a command ready in the buffer. void ImDrawList::ResetForNewFrame() { + // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. + // (those should be IM_STATIC_ASSERT() in theory but with our pre C++11 setup the whole check doesn't compile with GCC) + IM_ASSERT(IM_OFFSETOF(ImDrawCmd, ClipRect) == 0); + IM_ASSERT(IM_OFFSETOF(ImDrawCmd, TextureId) == sizeof(ImVec4)); + IM_ASSERT(IM_OFFSETOF(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID)); + CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); Flags = _Data->InitialFlags; - _VtxCurrentOffset = 0; + memset(&_CmdHeader, 0, sizeof(_CmdHeader)); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -400,7 +406,6 @@ void ImDrawList::ClearFreeMemory() IdxBuffer.clear(); VtxBuffer.clear(); Flags = ImDrawListFlags_None; - _VtxCurrentOffset = 0; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; @@ -420,16 +425,12 @@ ImDrawList* ImDrawList::CloneOutput() const return dst; } -// Using macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug builds -#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : _Data->ClipRectFullscreen) -#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : (ImTextureID)NULL) - void ImDrawList::AddDrawCmd() { ImDrawCmd draw_cmd; - draw_cmd.ClipRect = GetCurrentClipRect(); - draw_cmd.TextureId = GetCurrentTextureId(); - draw_cmd.VtxOffset = _VtxCurrentOffset; + draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy() + draw_cmd.TextureId = _CmdHeader.TextureId; + draw_cmd.VtxOffset = _CmdHeader.VtxOffset; draw_cmd.IdxOffset = IdxBuffer.Size; IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); @@ -450,68 +451,62 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) AddDrawCmd(); // Force a new command after us (see comment below) } +// Compare ClipRect, TextureId and VtxOffset with a single memcmp() +#define ImDrawCmd_HeaderSize (IM_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 + // Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. // The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. void ImDrawList::UpdateClipRect() { // If current command is used with different settings we need to add a new command - const ImVec4 curr_clip_rect = GetCurrentClipRect(); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; } // Try to merge with previous command if it matches, else use current command - if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL) { - ImDrawCmd* prev_cmd = curr_cmd - 1; - if (memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) - { - CmdBuffer.pop_back(); - return; - } + CmdBuffer.pop_back(); + return; } - curr_cmd->ClipRect = curr_clip_rect; + curr_cmd->ClipRect = _CmdHeader.ClipRect; } void ImDrawList::UpdateTextureID() { // If current command is used with different settings we need to add a new command - const ImTextureID curr_texture_id = GetCurrentTextureId(); ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) || curr_cmd->UserCallback != NULL) { AddDrawCmd(); return; } // Try to merge with previous command if it matches, else use current command - if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1) + ImDrawCmd* prev_cmd = curr_cmd - 1; + if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL) { - ImDrawCmd* prev_cmd = curr_cmd - 1; - if (prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->VtxOffset == _VtxCurrentOffset && prev_cmd->UserCallback == NULL) - { - CmdBuffer.pop_back(); - return; - } + CmdBuffer.pop_back(); + return; } - curr_cmd->TextureId = curr_texture_id; + curr_cmd->TextureId = _CmdHeader.TextureId; } -#undef GetCurrentClipRect -#undef GetCurrentTextureId - // 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) void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) { ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); - if (intersect_with_current_clip_rect && _ClipRectStack.Size) + if (intersect_with_current_clip_rect) { - ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + ImVec4 current = _CmdHeader.ClipRect; if (cr.x < current.x) cr.x = current.x; if (cr.y < current.y) cr.y = current.y; if (cr.z > current.z) cr.z = current.z; @@ -521,6 +516,7 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_ cr.w = ImMax(cr.y, cr.w); _ClipRectStack.push_back(cr); + _CmdHeader.ClipRect = cr; UpdateClipRect(); } @@ -531,21 +527,22 @@ void ImDrawList::PushClipRectFullScreen() void ImDrawList::PopClipRect() { - IM_ASSERT(_ClipRectStack.Size > 0); _ClipRectStack.pop_back(); + _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1]; UpdateClipRect(); } void ImDrawList::PushTextureID(ImTextureID texture_id) { _TextureIdStack.push_back(texture_id); + _CmdHeader.TextureId = texture_id; UpdateTextureID(); } void ImDrawList::PopTextureID() { - IM_ASSERT(_TextureIdStack.Size > 0); _TextureIdStack.pop_back(); + _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1]; UpdateTextureID(); } @@ -558,7 +555,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { - _VtxCurrentOffset = VtxBuffer.Size; + _CmdHeader.VtxOffset = VtxBuffer.Size; _VtxCurrentIdx = 0; AddDrawCmd(); } @@ -1235,9 +1232,9 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, if (font_size == 0.0f) font_size = _Data->FontSize; - IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. - ImVec4 clip_rect = _ClipRectStack.back(); + ImVec4 clip_rect = _CmdHeader.ClipRect; if (cpu_fine_clip_rect) { clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); @@ -1258,7 +1255,7 @@ void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, cons if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; if (push_texture_id) PushTextureID(user_texture_id); @@ -1274,7 +1271,7 @@ void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, con if ((col & IM_COL32_A_MASK) == 0) return; - const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + const bool push_texture_id = user_texture_id != _CmdHeader.TextureId; if (push_texture_id) PushTextureID(user_texture_id); @@ -1357,19 +1354,12 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) if (_Channels[i]._CmdBuffer.Size == 0) { ImDrawCmd draw_cmd; - draw_cmd.ClipRect = draw_list->_ClipRectStack.back(); - draw_cmd.TextureId = draw_list->_TextureIdStack.back(); - draw_cmd.VtxOffset = draw_list->_VtxCurrentOffset; + ImDrawCmd_HeaderCopy(&draw_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset _Channels[i]._CmdBuffer.push_back(draw_cmd); } } } -static inline bool CanMergeDrawCommands(ImDrawCmd* a, ImDrawCmd* b) -{ - return memcmp(&a->ClipRect, &b->ClipRect, sizeof(a->ClipRect)) == 0 && a->TextureId == b->TextureId && a->VtxOffset == b->VtxOffset && !a->UserCallback && !b->UserCallback; -} - void ImDrawListSplitter::Merge(ImDrawList* draw_list) { // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. @@ -1390,12 +1380,16 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) ImDrawChannel& ch = _Channels[i]; if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0) ch._CmdBuffer.pop_back(); - if (ch._CmdBuffer.Size > 0 && last_cmd != NULL && CanMergeDrawCommands(last_cmd, &ch._CmdBuffer[0])) + if (ch._CmdBuffer.Size > 0 && last_cmd != NULL) { - // Merge previous channel last draw command with current channel first draw command if matching. - last_cmd->ElemCount += ch._CmdBuffer[0].ElemCount; - idx_offset += ch._CmdBuffer[0].ElemCount; - ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges. + ImDrawCmd* next_cmd = &ch._CmdBuffer[0]; + if (ImDrawCmd_HeaderCompare(last_cmd, next_cmd) == 0 && last_cmd->UserCallback == NULL && next_cmd->UserCallback == NULL) + { + // Merge previous channel last draw command with current channel first draw command if matching. + last_cmd->ElemCount += next_cmd->ElemCount; + idx_offset += next_cmd->ElemCount; + ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges. + } } if (ch._CmdBuffer.Size > 0) last_cmd = &ch._CmdBuffer.back(); From 117d57df5bdddeaea8a286de8879879f5436a067 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 18:21:10 +0200 Subject: [PATCH 076/959] ImDrawList: Additional comments and extracted bits into ImDrawList::PopUnusedDrawCmd() --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 12 +++--------- imgui.h | 1 + imgui_draw.cpp | 19 ++++++++++++++++--- 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5f9f7b16..6ab1019d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,8 @@ Other Changes: [@thedmd, @Shironekoben, @sergeyn, @ocornut] - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after + a callback draw command would incorrectly override the callback draw command. - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). diff --git a/imgui.cpp b/imgui.cpp index 95dc22a6..1b190a6e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4077,18 +4077,12 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list) { + // Remove trailing command if unused. + // Technically we could return directly instead of popping, but this make things looks neat in Metrics window as well. + draw_list->PopUnusedDrawCmd(); if (draw_list->CmdBuffer.Size == 0) return; - // Remove trailing command if unused - ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.back(); - if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL) - { - draw_list->CmdBuffer.pop_back(); - if (draw_list->CmdBuffer.Size == 0) - return; - } - // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. // May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); diff --git a/imgui.h b/imgui.h index 45f3aa7c..de4faf28 100644 --- a/imgui.h +++ b/imgui.h @@ -2061,6 +2061,7 @@ struct ImDrawList // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void ResetForNewFrame(); IMGUI_API void ClearFreeMemory(); + IMGUI_API void PopUnusedDrawCmd(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 43daede2..fb25fecb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -437,6 +437,17 @@ void ImDrawList::AddDrawCmd() CmdBuffer.push_back(draw_cmd); } +// Pop trailing draw command (used before merging or presenting to user) +// Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL +void ImDrawList::PopUnusedDrawCmd() +{ + if (CmdBuffer.Size == 0) + return; + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); +} + void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -1362,13 +1373,12 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) void ImDrawListSplitter::Merge(ImDrawList* draw_list) { - // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + // Note that we never use or rely on _Channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. if (_Count <= 1) return; SetCurrentChannel(draw_list, 0); - if (draw_list->CmdBuffer.Size != 0 && draw_list->CmdBuffer.back().ElemCount == 0) - draw_list->CmdBuffer.pop_back(); + draw_list->PopUnusedDrawCmd(); // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; @@ -1378,8 +1388,11 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) for (int i = 1; i < _Count; i++) { ImDrawChannel& ch = _Channels[i]; + + // Equivalent of PopUnusedDrawCmd() for this channel's cmdbuffer and except we don't need to test for UserCallback. if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0) ch._CmdBuffer.pop_back(); + if (ch._CmdBuffer.Size > 0 && last_cmd != NULL) { ImDrawCmd* next_cmd = &ch._CmdBuffer[0]; From e35a813d5767397d211644385f0dee95df54acca Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 18:35:13 +0200 Subject: [PATCH 077/959] ImDrawList: Separating PrimXXX sections from more internals helper in the header file. --- imgui.h | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index de4faf28..70675189 100644 --- a/imgui.h +++ b/imgui.h @@ -2057,19 +2057,22 @@ struct ImDrawList inline void ChannelsMerge() { _Splitter.Merge(this); } inline void ChannelsSetCurrent(int n) { _Splitter.SetCurrentChannel(this, n); } - // [Internal helpers] - // NB: all primitives needs to be reserved via PrimReserve() beforehand! - IMGUI_API void ResetForNewFrame(); - IMGUI_API void ClearFreeMemory(); - IMGUI_API void PopUnusedDrawCmd(); + // Advanced: Primitives allocations + // - We render triangles (three vertices) + // - All primitives needs to be reserved via PrimReserve() beforehand. IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimUnreserve(int idx_count, int vtx_count); IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); - inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } - inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } - inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index + + // [Internal helpers] + IMGUI_API void ResetForNewFrame(); + IMGUI_API void ClearFreeMemory(); + IMGUI_API void PopUnusedDrawCmd(); IMGUI_API void UpdateClipRect(); IMGUI_API void UpdateTextureID(); }; From b1f2eacdf3b7ce64decbfd2e5e30819d05cf2ee1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 18:38:23 +0200 Subject: [PATCH 078/959] ImDrawList: Prefixed internal functions with underscore, renamed UpdateClipRect() to _OnChangedClipRect(), UpdateTextureID() -> _OnChangedTextureID() --- imgui.cpp | 14 +++++++------- imgui.h | 12 ++++++------ imgui_draw.cpp | 24 ++++++++++++------------ 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1b190a6e..43e71366 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2994,7 +2994,7 @@ void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window) window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity; window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity; window->IDStack.clear(); - window->DrawList->ClearFreeMemory(); + window->DrawList->_ClearFreeMemory(); window->DC.ChildWindows.clear(); window->DC.ItemFlagsStack.clear(); window->DC.ItemWidthStack.clear(); @@ -3777,11 +3777,11 @@ void ImGui::NewFrame() if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; - g.BackgroundDrawList.ResetForNewFrame(); + g.BackgroundDrawList._ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); - g.ForegroundDrawList.ResetForNewFrame(); + g.ForegroundDrawList._ResetForNewFrame(); g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.ForegroundDrawList.PushClipRectFullScreen(); @@ -4019,8 +4019,8 @@ void ImGui::Shutdown(ImGuiContext* context) g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); - g.BackgroundDrawList.ClearFreeMemory(); - g.ForegroundDrawList.ClearFreeMemory(); + g.BackgroundDrawList._ClearFreeMemory(); + g.ForegroundDrawList._ClearFreeMemory(); g.TabBars.Clear(); g.CurrentTabBarStack.clear(); @@ -4079,7 +4079,7 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d { // Remove trailing command if unused. // Technically we could return directly instead of popping, but this make things looks neat in Metrics window as well. - draw_list->PopUnusedDrawCmd(); + draw_list->_PopUnusedDrawCmd(); if (draw_list->CmdBuffer.Size == 0) return; @@ -5859,7 +5859,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // DRAWING // Setup draw list and outer clipping rectangle - window->DrawList->ResetForNewFrame(); + window->DrawList->_ResetForNewFrame(); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); diff --git a/imgui.h b/imgui.h index 70675189..b6c91a03 100644 --- a/imgui.h +++ b/imgui.h @@ -1991,7 +1991,7 @@ struct ImDrawList // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; Flags = ImDrawListFlags_None; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } - ~ImDrawList() { ClearFreeMemory(); } + ~ImDrawList() { _ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, 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(); @@ -2070,11 +2070,11 @@ 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 // [Internal helpers] - IMGUI_API void ResetForNewFrame(); - IMGUI_API void ClearFreeMemory(); - IMGUI_API void PopUnusedDrawCmd(); - IMGUI_API void UpdateClipRect(); - IMGUI_API void UpdateTextureID(); + IMGUI_API void _ResetForNewFrame(); + IMGUI_API void _ClearFreeMemory(); + IMGUI_API void _PopUnusedDrawCmd(); + IMGUI_API void _OnChangedClipRect(); + IMGUI_API void _OnChangedTextureID(); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index fb25fecb..d0ea99fb 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -377,7 +377,7 @@ void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) } // Initialize before use in a new frame. We always have a command ready in the buffer. -void ImDrawList::ResetForNewFrame() +void ImDrawList::_ResetForNewFrame() { // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. // (those should be IM_STATIC_ASSERT() in theory but with our pre C++11 setup the whole check doesn't compile with GCC) @@ -400,7 +400,7 @@ void ImDrawList::ResetForNewFrame() CmdBuffer.push_back(ImDrawCmd()); } -void ImDrawList::ClearFreeMemory() +void ImDrawList::_ClearFreeMemory() { CmdBuffer.clear(); IdxBuffer.clear(); @@ -439,7 +439,7 @@ void ImDrawList::AddDrawCmd() // Pop trailing draw command (used before merging or presenting to user) // Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL -void ImDrawList::PopUnusedDrawCmd() +void ImDrawList::_PopUnusedDrawCmd() { if (CmdBuffer.Size == 0) return; @@ -469,7 +469,7 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) // Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. // The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. -void ImDrawList::UpdateClipRect() +void ImDrawList::_OnChangedClipRect() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -490,7 +490,7 @@ void ImDrawList::UpdateClipRect() curr_cmd->ClipRect = _CmdHeader.ClipRect; } -void ImDrawList::UpdateTextureID() +void ImDrawList::_OnChangedTextureID() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -528,7 +528,7 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_ _ClipRectStack.push_back(cr); _CmdHeader.ClipRect = cr; - UpdateClipRect(); + _OnChangedClipRect(); } void ImDrawList::PushClipRectFullScreen() @@ -540,21 +540,21 @@ void ImDrawList::PopClipRect() { _ClipRectStack.pop_back(); _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1]; - UpdateClipRect(); + _OnChangedClipRect(); } void ImDrawList::PushTextureID(ImTextureID texture_id) { _TextureIdStack.push_back(texture_id); _CmdHeader.TextureId = texture_id; - UpdateTextureID(); + _OnChangedTextureID(); } void ImDrawList::PopTextureID() { _TextureIdStack.pop_back(); _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1]; - UpdateTextureID(); + _OnChangedTextureID(); } // Reserve space for a number of vertices and indices. @@ -1378,7 +1378,7 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) return; SetCurrentChannel(draw_list, 0); - draw_list->PopUnusedDrawCmd(); + draw_list->_PopUnusedDrawCmd(); // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command. int new_cmd_buffer_count = 0; @@ -1427,8 +1427,8 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } } draw_list->_IdxWritePtr = idx_write; - draw_list->UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. - draw_list->UpdateTextureID(); + draw_list->_OnChangedClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. + draw_list->_OnChangedTextureID(); _Count = 1; } From 3bef743df464c5dbbf527981c7f50be7a0f7f719 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 19:06:55 +0200 Subject: [PATCH 079/959] ImDrawList: Clarifying and guarateeing that CmdBuffer.back()->UserCallback should be always be NULL. --- imgui_draw.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index d0ea99fb..0af2c3c5 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -451,7 +451,8 @@ void ImDrawList::_PopUnusedDrawCmd() void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if (curr_cmd->ElemCount != 0 || curr_cmd->UserCallback != NULL) + IM_ASSERT(curr_cmd->UserCallback == NULL); + if (curr_cmd->ElemCount != 0) { AddDrawCmd(); curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; @@ -473,11 +474,12 @@ void ImDrawList::_OnChangedClipRect() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + if (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0) { AddDrawCmd(); return; } + IM_ASSERT(curr_cmd->UserCallback == NULL); // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = curr_cmd - 1; @@ -494,11 +496,12 @@ void ImDrawList::_OnChangedTextureID() { // If current command is used with different settings we need to add a new command ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - if ((curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) || curr_cmd->UserCallback != NULL) + if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId) { AddDrawCmd(); return; } + IM_ASSERT(curr_cmd->UserCallback == NULL); // Try to merge with previous command if it matches, else use current command ImDrawCmd* prev_cmd = curr_cmd - 1; @@ -1427,6 +1430,11 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } } draw_list->_IdxWritePtr = idx_write; + + // Ensure there's always a non-callback draw command trailing the command-buffer + if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL) + draw_list->AddDrawCmd(); + draw_list->_OnChangedClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. draw_list->_OnChangedTextureID(); _Count = 1; @@ -1437,6 +1445,7 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) IM_ASSERT(idx >= 0 && idx < _Count); if (_Current == idx) return; + // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap() memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer)); memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer)); From 84862ec78e0c2a249c94575a4ee39105e4061e68 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 20:53:11 +0200 Subject: [PATCH 080/959] ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where changing channels with different TextureId, VtxOffset would incorrectly apply new settings to draw channels. (#3129, #3163) --- docs/CHANGELOG.txt | 3 +++ imgui_draw.cpp | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ab1019d..1ae96e46 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,9 @@ Other Changes: - ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where changing channels with different + TextureId, VtxOffset would incorrectly apply new settings to draw channels. (#3129, #3163) + [@ocornut, @thedmd, @Shironekoben] - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0af2c3c5..94f223ba 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1435,8 +1435,13 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL) draw_list->AddDrawCmd(); - draw_list->_OnChangedClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. - draw_list->_OnChangedTextureID(); + // 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 + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); + _Count = 1; } @@ -1453,6 +1458,13 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx]._CmdBuffer, sizeof(draw_list->CmdBuffer)); memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx]._IdxBuffer, sizeof(draw_list->IdxBuffer)); draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size; + + // 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 + else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) + draw_list->AddDrawCmd(); } //----------------------------------------------------------------------------- From 9b3ce494fdee20f56ee672febe2f9d737a3927cc Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 8 Jun 2020 22:38:19 +0200 Subject: [PATCH 081/959] Columns: Lower overhead on column switches and switching to background channel (some stress tests in debug builds went 3->2 ms). (#125) This change benefits Columns but was primarily made with Tables in mind. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 7 ++++++- imgui_internal.h | 1 + imgui_widgets.cpp | 29 +++++++++++++++++++++++++---- 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1ae96e46..459bf25c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,6 +46,8 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) +- Columns: Lower overhead on column switches and switching to background channel (some of our stress + tests in debug builds went 3->2 ms). Benefits Columns but was primarily made with Tables in mind! - Style: Added style.TabMinWidthForUnselectedCloseButton settings. Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). diff --git a/imgui.cpp b/imgui.cpp index 43e71366..fd84ed03 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4167,7 +4167,12 @@ static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_da } } -// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +// - When using this function it is sane to ensure that float are perfectly rounded to integer values, +// so that e.g. (int)(max.x-min.x) in user's render produce correct result. +// - 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 a more +// specialized code path to added extraneous updates of the underlying ImDrawCmd. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/imgui_internal.h b/imgui_internal.h index 7b15e63f..b07c5568 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -435,6 +435,7 @@ struct IMGUI_API ImRect void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } + ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } }; // Helper: ImBitArray diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ba7c6b4..7d5bc5cf 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7549,6 +7549,11 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop + //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PushColumnsBackground()\n"); + window->DrawList->_CmdHeader.ClipRect = columns->HostClipRect.ToVec4(); + columns->Splitter.SetCurrentChannel(window->DrawList, 0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); @@ -7562,6 +7567,12 @@ void ImGui::PopColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop + //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PopColumnsBackground()\n"); + ImVec4 pop_clip_rect = window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 2]; + window->DrawList->_CmdHeader.ClipRect = pop_clip_rect; + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); PopClipRect(); } @@ -7684,11 +7695,22 @@ void ImGui::NextColumn() return; } PopItemWidth(); - PopClipRect(); + + // Next column + if (++columns->Current == columns->Count) + columns->Current = 0; + + // As a small optimization, to avoid doing PopClipRect() + SetCurrentChannel() + PushClipRect() + // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), + // We use a shortcut: we override ClipRect in window and drawlist's CmdHeader + SetCurrentChannel(). + ImGuiColumnData* column = &columns->Columns[columns->Current]; + window->ClipRect = column->ClipRect; + window->DrawList->_CmdHeader.ClipRect = column->ClipRect.ToVec4(); + //PopClipRect(); const float column_padding = g.Style.ItemSpacing.x; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (++columns->Current < columns->Count) + if (columns->Current > 0) { // Columns 1+ ignore IndentX (by canceling it out) // FIXME-COLUMNS: Unnecessary, could be locked? @@ -7701,7 +7723,6 @@ void ImGui::NextColumn() // Column 0 honor IndentX window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); columns->Splitter.SetCurrentChannel(window->DrawList, 1); - columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -7709,7 +7730,7 @@ void ImGui::NextColumn() window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = 0.0f; - PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? + //PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. float offset_0 = GetColumnOffset(columns->Current); From a72754886f703fd73048afc86c3eb1fce844e259 Mon Sep 17 00:00:00 2001 From: Scott Date: Tue, 9 Jun 2020 16:10:37 +0200 Subject: [PATCH 082/959] Docs: Initial draft of fonts documentation (#2861) --- docs/{FONTS.txt => FONTS.md} | 282 ++++++++++++++++------------------- 1 file changed, 127 insertions(+), 155 deletions(-) rename docs/{FONTS.txt => FONTS.md} (59%) diff --git a/docs/FONTS.txt b/docs/FONTS.md similarity index 59% rename from docs/FONTS.txt rename to docs/FONTS.md index e3690f14..9f5c7d7f 100644 --- a/docs/FONTS.txt +++ b/docs/FONTS.md @@ -1,85 +1,134 @@ -dear imgui -FONTS DOCUMENTATION - -Also read https://www.dearimgui.org/faq for more fonts related infos. +## Fonts The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), -a 13 pixels high, pixel-perfect font used by default. -We embed it font in source code so you can use Dear ImGui without any file system access. +a 13 pixels high, pixel-perfect font used by default. We embed it font in source code so you can use Dear ImGui without any file system access. -You may also load external .TTF/.OTF files. -The files in this folder are suggested fonts, provided as a convenience. +You may also load external .TTF/.OTF files. The files in this folder are suggested fonts, provided as a convenience. -Please read the FAQ: https://www.dearimgui.org/faq -Please use the Discord server: http://discord.dearimgui.org and not the Github issue tracker for basic font loading questions. +Fonts are rasterized in a single texture at the time of calling either of +- `io.Fonts->GetTexDataAsAlpha8()` ---------------------------------------- - INDEX: ---------------------------------------- +- `GetTexDataAsRGBA32()/Build()` -- Readme First / FAQ -- Fonts Loading Instructions -- Using Icons -- Using FreeType rasterizer -- Building Custom Glyph Ranges -- Using custom colorful icons -- Embedding Fonts in Source Code -- Credits/Licences for fonts included in repository -- Fonts Links +**Please read the FAQ:** https://www.dearimgui.org/faq +Please use the Discord server: http://discord.dearimgui.org and not the GitHub issue tracker for basic font loading questions. --------------------------------------- - README FIRST / FAQ +| Index | +|:---------------------------------------| +| [Readme First](#readme-first) | +| [Using Icons](#using-icons) | +| [Fonts Loading Instructions](#font-loading-instructions) | +| [FreeType Rasterizer, Small Font Sizes](#freeType-rasterizer-small-font-sizes) | +| [Building Custom Glyph Ranges](#building-custom-glyph-ranges) | +| [Using Custom Colorful Icons](#using-custom-colorful-icons) | +| [Embedding Fonts In Source Code](#embedding-fonts-in-source-code) | +| [Credits/Licenses For Fonts Included In This Folder](#creditslicenses-for-fonts-included-in-this-folder) | +| [Font Links](#font-links) | + + --------------------------------------- + ## Readme First - You can use the style editor ImGui::ShowStyleEditor() in the "Fonts" section to browse your fonts and understand what's going on if you have an issue. -- Fonts are rasterized in a single texture at the time of calling either of io.Fonts->GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build(). -- Make sure your font ranges data are persistent and available at the time the font atlas is being built. +- Make sure your font ranges data are persistent (available during the call to GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build(). - Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.: + ``` u8"hello" u8"こんにちは" // this will be encoded as UTF-8 -- If you want to include a backslash \ character in your string literal, you need to double them e.g. "folder\\filename". - Read FAQ for details. + ``` +- If you want to include a backslash \ character in your string literal, you need to double them e.g. "folder\\\filename". --------------------------------------- - FONTS LOADING INSTRUCTIONS ---------------------------------------- + ## Using Icons -Load default font: +- Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. +- A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth. +- To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: + https://github.com/juliettef/IconFontCppHeaders + +**The C++11 version of those files uses the u8"" utf-8 encoding syntax + \u** + + ` #define ICON_FA_SEARCH u8"\uf002" ` +**The pre-C++11 version has the values directly encoded as utf-8:** + + ` #define ICON_FA_SEARCH "\xEF\x80\x82" ` + +Example Setup: +```cpp + // Merge icons into default tool font + #include "IconsFontAwesome.h" ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontDefault(); -Load .TTF/.OTF file with: + ImFontConfig config; + config.MergeMode = true; + config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced + static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; + io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); +``` +Example Usage: +```cpp + // Usage, e.g. + ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); + ImGui::Button(ICON_FA_SEARCH " Search"); + // C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" + // ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" +``` +See Links below for other icons fonts and related tools. - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); -Load multiple fonts: +--------------------------------------- + ## Font Loading Instructions +Load default font: +```cpp + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontDefault(); +``` +Load .TTF/.OTF file with: +```cpp ImGuiIO& io = ImGui::GetIO(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); // Select font at runtime - ImGui::Text("Hello"); // use the default font (which is the first loaded font) + ImGui::Text("Hello"); // use the default font (which is the first loaded font) ImGui::PushFont(font2); ImGui::Text("Hello with another font"); ImGui::PopFont(); - +``` For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally): - +```cpp ImFontConfig config; config.OversampleH = 2; config.OversampleV = 1; config.GlyphExtraSpacing.x = 1.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); +``` +**Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample)** -Combine two fonts into one: +- If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. +- The typical result of failing to upload a texture is if every glyphs appears as white rectangles. +- In particular, using a large range such as GetGlyphRangesChineseSimplifiedCommon() is not recommended unless you set OversampleH/OversampleV to 1 and use a small font size. +- Mind the fact that some graphics drivers have texture size limitation. +- If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. + +Some solutions: + + 1. Reduce glyphs ranges by calculating them from source localization data. + You can use ImFontGlyphRangesBuilder for this purpose, this will be the biggest win! + 2. You may reduce oversampling, e.g. config.OversampleH = config.OversampleV = 1, this will largely reduce your texture size. + 3. Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function). + 4. Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two. +Combine two fonts into one: +```cpp // Load a first font ImFont* font = io.Fonts->AddFontDefault(); @@ -92,28 +141,9 @@ Combine two fonts into one: io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); io.Fonts->Build(); - -Font atlas is too large? - -- If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. -- The typical result of failing to upload a texture is if every glyphs appears as white rectangles. -- In particular, using a large range such as GetGlyphRangesChineseSimplifiedCommon() is not recommended - unless you set OversampleH/OversampleV to 1 and use a small font size. -- Mind the fact that some graphics drivers have texture size limitation. -- If you are building a PC application, mind the fact that users may run on hardware with lower specs than yours. - -Some solutions: - - - 1) Reduce glyphs ranges by calculating them from source localization data. - You can use ImFontGlyphRangesBuilder for this purpose, this will be the biggest win! - - 2) You may reduce oversampling, e.g. config.OversampleH = config.OversampleV = 1, this will largely reduce your texture size. - - 3) Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function). - - 4) Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two. - - Read about oversampling here: https://github.com/nothings/stb/blob/master/tests/oversample - - +``` Add a fourth parameter to bake specific font ranges only: - +```cpp // Basic Latin, Extended Latin io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); @@ -122,79 +152,31 @@ Add a fourth parameter to bake specific font ranges only: // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); - -See "BUILDING CUSTOM GLYPH RANGES" section to create your own ranges. +``` +See [Building Custom Glyph Ranges](#building-custom-glyph-ranges) section to create your own ranges. Offset font vertically by altering the io.Font->DisplayOffset value: - +```cpp ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); font->DisplayOffset.y = 1; // Render 1 pixel down +``` - ---------------------------------------- - USING ICONS --------------------------------------- + ## Freetype Rasterizer, Small Font Sizes -Using an icon font (such as FontAwesome: http://fontawesome.io or OpenFontIcons. https://github.com/traverseda/OpenFontIcons) -is an easy and practical way to use icons in your Dear ImGui application. -A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without -having to change fonts back and forth. - -To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: - - https://github.com/juliettef/IconFontCppHeaders - -Those files contains a bunch of named #define which you can use to refer to specific icons of the font, e.g.: - - #define ICON_FA_MUSIC "\xef\x80\x81" - #define ICON_FA_SEARCH "\xef\x80\x82" - -Example Setup: +- Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. +- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder. +- FreeType supports auto-hinting which tends to improve the readability of small fonts. - // Merge icons into default tool font - #include "IconsFontAwesome.h" - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontDefault(); - - ImFontConfig config; - config.MergeMode = true; - config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced - static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; - io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); - -Example Usage: - - // Usage, e.g. - ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); - ImGui::Button(ICON_FA_SEARCH " Search"); - -Important to understand: C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" -ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" - -See Links below for other icons fonts and related tools. +**Note** +- This code currently creates textures that are unoptimally too large (could be fixed with some work). +- Also note that correct sRGB space blending will have an important effect on your font rendering quality. --------------------------------------- - FREETYPE RASTERIZER, SMALL FONT SIZES ---------------------------------------- - -Dear ImGui uses imstb_truetype.h to rasterize fonts (with optional oversampling). -This technique and its implementation are not ideal for fonts rendered at _small sizes_, which may appear a -little blurry or hard to read. - -There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder. - -FreeType supports auto-hinting which tends to improve the readability of small fonts. -Note that this code currently creates textures that are unoptimally too large (could be fixed with some work). -Also note that correct sRGB space blending will have an important effect on your font rendering quality. - - ---------------------------------------- - BUILDING CUSTOM GLYPH RANGES ---------------------------------------- - -You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input. -For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. + ## Building Custom Glyph Ranges +You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. +```cpp ImVector ranges; ImFontGlyphRangesBuilder builder; builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) @@ -204,21 +186,18 @@ For example: for a game where your script is known, if you can feed your entire io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. +``` - ---------------------------------------- - USING CUSTOM COLORFUL ICONS --------------------------------------- +## Using Custom Colorful Icons -(This is a BETA api, use if you are familiar with dear imgui and with your rendering back-end) - -You can use the ImFontAtlas::AddCustomRect() and ImFontAtlas::AddCustomRectFontGlyph() api to register rectangles -that will be packed into the font atlas texture. Register them before building the atlas, then call Build(). -You can then use ImFontAtlas::GetCustomRectByIndex(int) to query the position/size of your rectangle within the -texture, and blit/copy any graphics data of your choice into those rectangles. +**(This is a BETA api, use if you are familiar with dear imgui and with your rendering back-end)** -Pseudo-code: +- You can use the ImFontAtlas::AddCustomRect() and ImFontAtlas::AddCustomRectFontGlyph() api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build(). +- You can then use ImFontAtlas::GetCustomRectByIndex(int) to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles. +#### Pseudo-code: +``` // Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font ImFont* font = io.Fonts->AddFontDefault(); int rect_ids[2]; @@ -247,29 +226,25 @@ Pseudo-code: } } } +``` - ---------------------------------------- - EMBEDDING FONTS IN SOURCE CODE --------------------------------------- + ## Embedding Fonts In Source Code -Compile and use 'binary_to_compressed_c.cpp' to create a compressed C style array that you can embed in source code. -See the documentation in binary_to_compressed_c.cpp for instruction on how to use the tool. -You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see README). -The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the -actual binary will be about 20% bigger. +- Compile and use 'binary\_to\_compressed\_c.cpp' to create a compressed C style array that you can embed in source code. +- See the documentation in binary\_to\_compressed\_c.cpp for instruction on how to use the tool. +- You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see README). +- The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the actual binary will be about 20% bigger. Then load the font with: - ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); -or: - ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); + ` ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); ` +or + `ImFont* font = io.Fonts- AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); + ` --------------------------------------- - CREDITS/LICENSES FOR FONTS INCLUDED IN REPOSITORY ---------------------------------------- - -Some fonts are available in the misc/fonts/ folder: + ## Credits/Licenses For Fonts Included In This Folder Roboto-Medium.ttf @@ -309,10 +284,9 @@ Karla-Regular.ttf --------------------------------------- - FONTS LINKS ---------------------------------------- + ## Font Links -ICON FONTS +#### ICON FONTS C/C++ header for icon fonts (#define with code points to use in source code string literals) https://github.com/juliettef/IconFontCppHeaders @@ -332,7 +306,7 @@ ICON FONTS IcoMoon - Custom Icon font builder https://icomoon.io/app -REGULAR FONTS +#### REGULAR FONTS Google Noto Fonts (worldwide languages) https://www.google.com/get/noto/ @@ -343,17 +317,15 @@ REGULAR FONTS (Japanese) M+ fonts by Coji Morishita are free http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html -MONOSPACE FONTS (PIXEL PERFECT) +#### MONOSPACE FONTS - Proggy Fonts, by Tristan Grimmer + (Pixel Perfect) Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net - Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) + (Pixel Perfect) Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font Also include .inl file to use directly in dear imgui. -MONOSPACE FONTS (REGULAR) - Google Noto Mono Fonts https://www.google.com/get/noto/ From 40b799023b6dc3820c9040df55723d8d4a801897 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Jun 2020 16:29:00 +0200 Subject: [PATCH 083/959] Docs: Update fonts.md (#2861) + update all references to FONTS.txt --- docs/FAQ.md | 8 +- docs/FONTS.md | 479 +++++++++++----------- examples/example_allegro5/main.cpp | 2 +- examples/example_emscripten/main.cpp | 2 +- examples/example_glfw_opengl2/main.cpp | 2 +- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_glfw_vulkan/main.cpp | 2 +- examples/example_glut_opengl2/main.cpp | 2 +- examples/example_marmalade/main.cpp | 2 +- examples/example_sdl_directx11/main.cpp | 2 +- examples/example_sdl_opengl2/main.cpp | 2 +- examples/example_sdl_opengl3/main.cpp | 2 +- examples/example_sdl_vulkan/main.cpp | 2 +- examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- examples/example_win32_directx12/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 2 +- imgui.cpp | 2 +- imgui.h | 4 +- imgui_demo.cpp | 12 +- 20 files changed, 271 insertions(+), 264 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 6c140760..15e2cd73 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -454,7 +454,7 @@ Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear img (Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.) -(Read the [docs/FONTS.txt](https://github.com/ocornut/imgui/blob/master/docs/FONTS.txt) file for more details about font loading.) +(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file for more details about font loading.) New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash "\\": @@ -473,9 +473,9 @@ io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. You may want to see `ImFontConfig::GlyphMinAdvanceX` to make your icon look monospace to facilitate alignment. -(Read the [docs/FONTS.txt](https://github.com/ocornut/imgui/blob/master/docs/FONTS.txt) file for more details about icons font loading.) +(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file for more details about icons font loading.) With some extra effort, you may use colorful icon by registering custom rectangle space inside the font atlas, -and copying your own graphics data into it. See docs/FONTS.txt about using the AddCustomRectFontGlyph API. +and copying your own graphics data into it. See docs/FONTS.md about using the AddCustomRectFontGlyph API. ##### [Return to Index](#index) @@ -483,7 +483,7 @@ and copying your own graphics data into it. See docs/FONTS.txt about using the A ### Q: How can I load multiple fonts? Use the font atlas to pack them into a single texture: -(Read the [docs/FONTS.txt](https://github.com/ocornut/imgui/blob/master/docs/FONTS.txt) file and the code in ImFontAtlas for more details.) +(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file and the code in ImFontAtlas for more details.) ```cpp ImGuiIO& io = ImGui::GetIO(); diff --git a/docs/FONTS.md b/docs/FONTS.md index 9f5c7d7f..d2f40f2b 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -1,272 +1,306 @@ -## Fonts +## Dear ImGui: Using Fonts -The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), -a 13 pixels high, pixel-perfect font used by default. We embed it font in source code so you can use Dear ImGui without any file system access. - -You may also load external .TTF/.OTF files. The files in this folder are suggested fonts, provided as a convenience. - -Fonts are rasterized in a single texture at the time of calling either of +(You may browse this document at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer.) -- `io.Fonts->GetTexDataAsAlpha8()` - -- `GetTexDataAsRGBA32()/Build()` +The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), +a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions. -**Please read the FAQ:** https://www.dearimgui.org/faq -Please use the Discord server: http://discord.dearimgui.org and not the GitHub issue tracker for basic font loading questions. +You may also load external .TTF/.OTF files. +In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience. +**Read the FAQ:** https://www.dearimgui.org/faq (there is a Fonts section!) ---------------------------------------- -| Index | -|:---------------------------------------| -| [Readme First](#readme-first) | -| [Using Icons](#using-icons) | -| [Fonts Loading Instructions](#font-loading-instructions) | -| [FreeType Rasterizer, Small Font Sizes](#freeType-rasterizer-small-font-sizes) | -| [Building Custom Glyph Ranges](#building-custom-glyph-ranges) | -| [Using Custom Colorful Icons](#using-custom-colorful-icons) | -| [Embedding Fonts In Source Code](#embedding-fonts-in-source-code) | -| [Credits/Licenses For Fonts Included In This Folder](#creditslicenses-for-fonts-included-in-this-folder) | -| [Font Links](#font-links) | +**Use the Discord server**: http://discord.dearimgui.org and not the GitHub issue tracker for basic font loading questions. +## Index +- [Readme First](#readme-first) +- [Fonts Loading Instructions](#font-loading-instructions) +- [Using Icons](#using-icons) +- [Using FreeType Rasterizer](#using-freetype-rasterizer) +- [Using Custom Glyph Ranges](#using-custom-glyph-ranges) +- [Using Custom Colorful Icons](#using-custom-colorful-icons) +- [Using Font Data Embedded In Source Code](#using-font-data-embedded-in-source-code) +- [About filenames](#about-filenames) +- [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository) +- [Font Links](#font-links) --------------------------------------- ## Readme First -- You can use the style editor ImGui::ShowStyleEditor() in the "Fonts" section to browse your fonts - and understand what's going on if you have an issue. -- Make sure your font ranges data are persistent (available during the call to GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build(). -- Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.: - ``` - u8"hello" - u8"こんにちは" // this will be encoded as UTF-8 - ``` -- If you want to include a backslash \ character in your string literal, you need to double them e.g. "folder\\\filename". - +- All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas. ---------------------------------------- - ## Using Icons +- You can use the style editor `ImGui::ShowStyleEditor()` in the "Fonts" section to browse your fonts and understand what's going on if you have an issue. You can also reach it in `Demo->Tools->Style Editor->Fonts`: -- Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. -- A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth. -- To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: - https://github.com/juliettef/IconFontCppHeaders +![imgui_capture_0008](https://user-images.githubusercontent.com/8225057/84162822-1a731f00-aa71-11ea-9b6b-89c2332aa161.png) -**The C++11 version of those files uses the u8"" utf-8 encoding syntax + \u** +- Make sure your font ranges data are persistent (available during the calls to `GetTexDataAsAlpha8()`/`GetTexDataAsRGBA32()/`Build()`. - ` #define ICON_FA_SEARCH u8"\uf002" ` +- Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.: +```cpp +u8"hello" +u8"こんにちは" // this will be encoded as UTF-8 +``` -**The pre-C++11 version has the values directly encoded as utf-8:** +##### [Return to Index](#index) - ` #define ICON_FA_SEARCH "\xEF\x80\x82" ` +## Font Loading Instructions -Example Setup: +**Load default font:** ```cpp - // Merge icons into default tool font - #include "IconsFontAwesome.h" - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontDefault(); - - ImFontConfig config; - config.MergeMode = true; - config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced - static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; - io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontDefault(); ``` -Example Usage: + +**Load .TTF/.OTF file with:** ```cpp - // Usage, e.g. - ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); - ImGui::Button(ICON_FA_SEARCH " Search"); - // C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" - // ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ``` -See Links below for other icons fonts and related tools. +If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully. +**Load multiple fonts:** +```cpp +ImGuiIO& io = ImGui::GetIO(); +ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); +ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); + +// Select font at runtime +ImGui::Text("Hello"); // use the default font (which is the first loaded font) +ImGui::PushFont(font2); +ImGui::Text("Hello with another font"); +ImGui::PopFont(); +``` ---------------------------------------- - ## Font Loading Instructions +**For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** +```cpp +ImFontConfig config; +config.OversampleH = 2; +config.OversampleV = 1; +config.GlyphExtraSpacing.x = 1.0f; +ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); +``` -Load default font: +**Combine multiple fonts into one:** ```cpp - ImGuiIO& io = ImGui::GetIO(); - io.Fonts->AddFontDefault(); +// Load a first font +ImFont* font = io.Fonts->AddFontDefault(); + +// Add character ranges and merge into the previous font +// The ranges array is not copied by the AddFont* functions and is used lazily +// so ensure it is available at the time of building or calling GetTexDataAsRGBA32(). +static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope. +ImFontConfig config; +config.MergeMode = true; +io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge into first font +io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); // Merge into first font +io.Fonts->Build(); ``` -Load .TTF/.OTF file with: + +**Add a fourth parameter to bake specific font ranges only:** ```cpp - ImGuiIO& io = ImGui::GetIO(); - ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); - ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); - - // Select font at runtime - ImGui::Text("Hello"); // use the default font (which is the first loaded font) - ImGui::PushFont(font2); - ImGui::Text("Hello with another font"); - ImGui::PopFont(); +// Basic Latin, Extended Latin +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); + +// Default + Selection of 2500 Ideographs used by Simplified Chinese +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); + +// Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); ``` -For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally): +See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges. + +**Offset font vertically by altering the `io.Font->DisplayOffset` value:** ```cpp - ImFontConfig config; - config.OversampleH = 2; - config.OversampleV = 1; - config.GlyphExtraSpacing.x = 1.0f; - ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); +ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); +font->DisplayOffset.y = 1; // Render 1 pixel down ``` -**Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample)** -- If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. -- The typical result of failing to upload a texture is if every glyphs appears as white rectangles. -- In particular, using a large range such as GetGlyphRangesChineseSimplifiedCommon() is not recommended unless you set OversampleH/OversampleV to 1 and use a small font size. +**Font Atlas too large?** + +- If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. The typical result of failing to upload a texture is if every glyphs appears as white rectangles. +- In particular, using a large range such as `GetGlyphRangesChineseSimplifiedCommon()` is not recommended unless you set `OversampleH`/`OversampleV` to 1 and use a small font size. - Mind the fact that some graphics drivers have texture size limitation. - If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. Some solutions: - 1. Reduce glyphs ranges by calculating them from source localization data. - You can use ImFontGlyphRangesBuilder for this purpose, this will be the biggest win! - 2. You may reduce oversampling, e.g. config.OversampleH = config.OversampleV = 1, this will largely reduce your texture size. - 3. Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function). - 4. Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two. +1. Reduce glyphs ranges by calculating them from source localization data. + You can use the `ImFontGlyphRangesBuilder` for this purpose, this will be the biggest win! +2. You may reduce oversampling, e.g. `font_config.OversampleH = font_config.OversampleV = 1`, this will largely reduce your texture size. +3. Set `io.Fonts.TexDesiredWidth` to specify a texture width to minimize texture height (see comment in `ImFontAtlas::Build()` function). +4. Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. +5. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample). -Combine two fonts into one: -```cpp - // Load a first font - ImFont* font = io.Fonts->AddFontDefault(); - - // Add character ranges and merge into the previous font - // The ranges array is not copied by the AddFont* functions and is used lazily - // so ensure it is available at the time of building or calling GetTexDataAsRGBA32(). - static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope. - ImFontConfig config; - config.MergeMode = true; - io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); - io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); - io.Fonts->Build(); -``` -Add a fourth parameter to bake specific font ranges only: -```cpp - // Basic Latin, Extended Latin - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); +##### [Return to Index](#index) + +## Using Icons + +Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. +A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth. - // Default + Selection of 2500 Ideographs used by Simplified Chinese - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); +To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: https://github.com/juliettef/IconFontCppHeaders. + +So you can use `ICON_FA_SEARCH` as a string that will render as a "Search" icon. - // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs - io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); +Example Setup: +```cpp +// Merge icons into default tool font +#include "IconsFontAwesome.h" +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontDefault(); + +ImFontConfig config; +config.MergeMode = true; +config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced +static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; +io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); ``` -See [Building Custom Glyph Ranges](#building-custom-glyph-ranges) section to create your own ranges. -Offset font vertically by altering the io.Font->DisplayOffset value: +Example Usage: ```cpp - ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); - font->DisplayOffset.y = 1; // Render 1 pixel down +// Usage, e.g. +ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); +ImGui::Button(ICON_FA_SEARCH " Search"); +// C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" +// ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" ``` +See Links below for other icons fonts and related tools. ---------------------------------------- - ## Freetype Rasterizer, Small Font Sizes +Here's an application using icons ("Avoyd", https://www.avoyd.com): +![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg) + +##### [Return to Index](#index) + +## Using FreeType Rasterizer - Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. -- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder. +- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. - FreeType supports auto-hinting which tends to improve the readability of small fonts. +- Read documentation in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. +- Correct sRGB space blending will have an important effect on your font rendering quality. -**Note** -- This code currently creates textures that are unoptimally too large (could be fixed with some work). -- Also note that correct sRGB space blending will have an important effect on your font rendering quality. +##### [Return to Index](#index) +## Using Custom Glyph Ranges ---------------------------------------- - ## Building Custom Glyph Ranges - -You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. +You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. ```cpp - ImVector ranges; - ImFontGlyphRangesBuilder builder; - builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) - builder.AddChar(0x7262); // Add a specific character - builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges - builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) - - io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); - io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. +ImVector ranges; +ImFontGlyphRangesBuilder builder; +builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) +builder.AddChar(0x7262); // Add a specific character +builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges +builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) + +io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); +io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. ``` ---------------------------------------- +##### [Return to Index](#index) + ## Using Custom Colorful Icons **(This is a BETA api, use if you are familiar with dear imgui and with your rendering back-end)** -- You can use the ImFontAtlas::AddCustomRect() and ImFontAtlas::AddCustomRectFontGlyph() api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build(). -- You can then use ImFontAtlas::GetCustomRectByIndex(int) to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles. +- You can use the `ImFontAtlas::AddCustomRect()` and `ImFontAtlas::AddCustomRectFontGlyph()` api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`. +- You can then use `ImFontAtlas::GetCustomRectByIndex(int)` to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles. +- This API is beta because it is likely to change in order to support multi-dpi (multiple viewports on multiple monitors with varying DPI scale). #### Pseudo-code: -``` - // Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font - ImFont* font = io.Fonts->AddFontDefault(); - int rect_ids[2]; - rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1); - rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1); - - // Build atlas - io.Fonts->Build(); - - // Retrieve texture in RGBA format - unsigned char* tex_pixels = NULL; - int tex_width, tex_height; - io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); - - for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) - { - int rect_id = rects_ids[rect_n]; - if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) - { - // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!) - for (int y = 0; y < rect->Height; y++) - { - ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X); - for (int x = rect->Width; x > 0; x--) - *p++ = IM_COL32(255, 0, 0, 255); - } - } - } +```cpp +// Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font +ImFont* font = io.Fonts->AddFontDefault(); +int rect_ids[2]; +rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1); +rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1); + +// Build atlas +io.Fonts->Build(); + +// Retrieve texture in RGBA format +unsigned char* tex_pixels = NULL; +int tex_width, tex_height; +io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); + +for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) +{ + int rect_id = rects_ids[rect_n]; + if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) + { + // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!) + for (int y = 0; y < rect->Height; y++) + { + ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X); + for (int x = rect->Width; x > 0; x--) + *p++ = IM_COL32(255, 0, 0, 255); + } + } +} ``` ---------------------------------------- - ## Embedding Fonts In Source Code +##### [Return to Index](#index) + +## Using Font Data Embedded In Source Code -- Compile and use 'binary\_to\_compressed\_c.cpp' to create a compressed C style array that you can embed in source code. -- See the documentation in binary\_to\_compressed\_c.cpp for instruction on how to use the tool. -- You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see README). +- Compile and use [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) to create a compressed C style array that you can embed in source code. +- See the documentation in [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) for instruction on how to use the tool. +- You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see [README](https://github.com/ocornut/imgui/blob/master/docs/README.md)). - The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the actual binary will be about 20% bigger. Then load the font with: - ` ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); ` +```cpp +ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); +``` or - `ImFont* font = io.Fonts- AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); - ` +```cpp +ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); +``` +##### [Return to Index](#index) ---------------------------------------- - ## Credits/Licenses For Fonts Included In This Folder +## About filenames -Roboto-Medium.ttf +**Please note that many new C/C++ users have issues their files _because the filename they provide is wrong_.** + +Two things to watch for: +- Make sure your IDE/debugger settings starts your executable from the right working directory. In Visual Studio you can change your working directory in project `Properties > General > Debugging > Working Directory`. People assume that their execution will start from the root folder of the project, where by default it oftens start from the folder where object or executable files are stored. +```cpp +// Relative filename depends on your Working Directory when running your program! +io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); + +// Load from the parent folder of your Working Directory +io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); +``` +- In C/C++ and most programming languages if you want to use a backslash `\` within a string literal, you need to write it double backslash `\\`. At it happens, Windows uses backslashes as a path separator, so be mindful. +```cpp +io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!! +io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT +``` +In some situations, you may also use `/` path separator under Windows. + +##### [Return to Index](#index) + +## Credits/Licenses For Fonts Included In Repository + +Some fonts files are available in the `misc/fonts/` folder: +``` +Roboto-Medium.ttf Apache License 2.0 - by Christian Robertson + by Christian Robetson https://fonts.google.com/specimen/Roboto Cousine-Regular.ttf - by Steve Matteson Digitized data copyright (c) 2010 Google Corporation. Licensed under the SIL Open Font License, Version 1.1 https://fonts.google.com/specimen/Cousine DroidSans.ttf - Copyright (c) Steve Matteson Apache License, version 2.0 https://www.fontsquirrel.com/fonts/droid-sans ProggyClean.ttf - Copyright (c) 2004, 2005 Tristan Grimmer MIT License recommended loading setting: Size = 13.0, DisplayOffset.Y = +1 @@ -281,68 +315,41 @@ ProggyTiny.ttf Karla-Regular.ttf Copyright (c) 2012, Jonathan Pinhorn SIL OPEN FONT LICENSE Version 1.1 +``` +##### [Return to Index](#index) ---------------------------------------- - ## Font Links +## Font Links #### ICON FONTS - C/C++ header for icon fonts (#define with code points to use in source code string literals) - https://github.com/juliettef/IconFontCppHeaders - - FontAwesome - https://fortawesome.github.io/Font-Awesome - - OpenFontIcons - https://github.com/traverseda/OpenFontIcons - - Google Icon Fonts - https://design.google.com/icons/ - - Kenney Icon Font (Game Controller Icons) - https://github.com/nicodinh/kenney-icon-font - - IcoMoon - Custom Icon font builder - https://icomoon.io/app +- C/C++ header for icon fonts (#define with code points to use in source code string literals) https://github.com/juliettef/IconFontCppHeaders +- FontAwesome https://fortawesome.github.io/Font-Awesome +- OpenFontIcons https://github.com/traverseda/OpenFontIcons +- Google Icon Fonts https://design.google.com/icons/ +- Kenney Icon Font (Game Controller Icons) https://github.com/nicodinh/kenney-icon-font +- IcoMoon - Custom Icon font builder https://icomoon.io/app #### REGULAR FONTS - Google Noto Fonts (worldwide languages) - https://www.google.com/get/noto/ - - Open Sans Fonts - https://fonts.google.com/specimen/Open+Sans - - (Japanese) M+ fonts by Coji Morishita are free - http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html +- Google Noto Fonts (worldwide languages) https://www.google.com/get/noto/ +- Open Sans Fonts https://fonts.google.com/specimen/Open+Sans +- (Japanese) M+ fonts by Coji Morishita http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html #### MONOSPACE FONTS - (Pixel Perfect) Proggy Fonts, by Tristan Grimmer - http://www.proggyfonts.net or http://upperbounds.net - - (Pixel Perfect) Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) - https://github.com/kmar/Sweet16Font - Also include .inl file to use directly in dear imgui. - - Google Noto Mono Fonts - https://www.google.com/get/noto/ - - Typefaces for source code beautification - https://github.com/chrissimpkins/codeface - - Programmation fonts - http://s9w.github.io/font_compare/ - - Inconsolata - http://www.levien.com/type/myfonts/inconsolata.html - - Adobe Source Code Pro: Monospaced font family for user interface and coding environments - https://github.com/adobe-fonts/source-code-pro +Pixel Perfect: +- Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net +- Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font (also include an .inl file to use directly in dear imgui.) - Monospace/Fixed Width Programmer's Fonts - http://www.lowing.org/fonts/ +Regular: +- Google Noto Mono Fonts https://www.google.com/get/noto/ +- Typefaces for source code beautification https://github.com/chrissimpkins/codeface +- Programmation fonts http://s9w.github.io/font_compare/ +- Inconsolata http://www.levien.com/type/myfonts/inconsolata.html +- Adobe Source Code Pro: Monospaced font family for ui & coding environments https://github.com/adobe-fonts/source-code-pro +- Monospace/Fixed Width Programmer's Fonts http://www.lowing.org/fonts/ +Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing). - Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing). +##### [Return to Index](#index) diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 5a026840..c32125b6 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -40,7 +40,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index f0eb3a2b..6867b4cd 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -81,7 +81,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details. //io.Fonts->AddFontDefault(); diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index a50b4637..411062fa 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -59,7 +59,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 8df734bd..6a3592f1 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -119,7 +119,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 3ce1984a..80763a01 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -401,7 +401,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index d36c1f84..997eeaef 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -125,7 +125,7 @@ int main(int argc, char** argv) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_marmalade/main.cpp b/examples/example_marmalade/main.cpp index 82435f20..9f2ef798 100644 --- a/examples/example_marmalade/main.cpp +++ b/examples/example_marmalade/main.cpp @@ -34,7 +34,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp index eadf8ff7..61a93070 100644 --- a/examples/example_sdl_directx11/main.cpp +++ b/examples/example_sdl_directx11/main.cpp @@ -69,7 +69,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index ff54ec41..fcd9ae32 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -57,7 +57,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index ae794ef4..3146084d 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -114,7 +114,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 9eaea945..0a2ea9ee 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -385,7 +385,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 41833cb5..f6b8b215 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -62,7 +62,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 05de7433..2cc36a7f 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -62,7 +62,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 8642ad45..6ea896bc 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -96,7 +96,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 33123625..c8ad69f1 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -60,7 +60,7 @@ int main(int, char**) // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); diff --git a/imgui.cpp b/imgui.cpp index fd84ed03..2d740d1b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -769,7 +769,7 @@ CODE Q: How can I easily use icons in my application? Q: How can I load multiple fonts? Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? - >> See https://www.dearimgui.org/faq and docs/FONTS.txt + >> See https://www.dearimgui.org/faq (docs/FAQ.md) docs/FONTS.md Q&A: Concerns ============= diff --git a/imgui.h b/imgui.h index b6c91a03..3f25e81e 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.77 WIP" -#define IMGUI_VERSION_NUM 17601 +#define IMGUI_VERSION_NUM 17602 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -2244,7 +2244,7 @@ struct ImFontAtlas // After calling Build(), you can query the rectangle position and render your pixels. // 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. - // Read docs/FONTS.txt for more details about using colorful icons. + // 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)); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8cece7be..ace91fd0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -152,7 +152,7 @@ static void ShowExampleAppCustomRendering(bool* p_open); static void ShowExampleMenuFile(); // Helper to display a little (?) mark which shows a tooltip when hovered. -// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.txt) +// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) static void HelpMarker(const char* desc) { ImGui::TextDisabled("(?)"); @@ -861,7 +861,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("UTF-8 Text")) { // UTF-8 test with Japanese characters - // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.txt for details.) + // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8 // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you // can save your source files as 'UTF-8 without signature'). @@ -873,7 +873,7 @@ static void ShowDemoWindowWidgets() ImGui::TextWrapped( "CJK text will only appears if the font was loaded with the appropriate CJK character ranges. " "Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. " - "Read docs/FONTS.txt for details."); + "Read docs/FONTS.md for details."); ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); // Normally we would use u8"blah blah" with the proper characters directly in the string. ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; @@ -3538,7 +3538,7 @@ void ImGui::ShowFontSelector(const char* label) 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.txt for more details.\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()."); } @@ -3766,7 +3766,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { // 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.txt about using icon fonts. It's really easy and super convenient! + // 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]; } } @@ -3784,7 +3784,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGuiIO& io = ImGui::GetIO(); ImFontAtlas* atlas = io.Fonts; - HelpMarker("Read FAQ and docs/FONTS.txt for details on font loading."); + HelpMarker("Read FAQ and docs/FONTS.md for details on font loading."); ImGui::PushItemWidth(120); for (int i = 0; i < atlas->Fonts.Size; i++) { From 53f0f972737a42472fce671864cb9b5fa4514562 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 9 Jun 2020 17:29:26 +0200 Subject: [PATCH 084/959] Added FAQ entry about DPI. Added Japanese font loading example. --- docs/CHANGELOG.txt | 2 ++ docs/FAQ.md | 28 ++++++++++++++++++++++++++-- docs/FONTS.md | 34 ++++++++++++++++++++++++++++++++++ imgui.cpp | 3 ++- 4 files changed, 64 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 459bf25c..90e06972 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,8 @@ Other Changes: - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after a callback draw command would incorrectly override the callback draw command. - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. +- Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. + Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). Fixed a static contructor which led to this dependency on some compiler setups (unclear which). diff --git a/docs/FAQ.md b/docs/FAQ.md index 15e2cd73..5e824b86 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -27,6 +27,7 @@ or view this file with any Markdown viewer. | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | | [How can I display custom shapes? (using low-level ImDrawList API)](#q-how-can-i-display-custom-shapes-using-low-level-imdrawlist-api) | | **Q&A: Fonts, Text** | +| [How should I handle DPi in my application?](#q-how-should-i-handle-dpi-in-my-application) | | [How can I load a different font than the default?](#q-how-can-i-load-a-different-font-than-the-default) | | [How can I easily use icons in my application?](#q-how-can-i-easily-use-icons-in-my-application) | | [How can I load multiple fonts?](#q-how-can-i-load-multiple-fonts) | @@ -441,10 +442,33 @@ ImGui::End(); # Q&A: Fonts, Text +### Q: How should I handle DPI in my application? + +The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. + +Your application may want to detect DPI change and reload the font and reset style being frames. + +Your ui code should avoid using hardcoded constants for size and positioning. Prefer to express values as multiple of reference values such as `ImGui::GetFontSize()` or `ImGui::GetFrameHeight()`. So e.g. instead of seeing a hardcoded height of 500 for a given item/window, you may want to use `30*ImGui::GetFontSize()` instead. + +Down the line Dear ImGui will provide a variety of standardized reference values to facilitate using this. + +Applications in the `examples/` folder are not DPI aware partly because they are unable to load a custom font from the file-system (may change that in the future). + +The reason DPI is not auto-magically solved in stock examples is that we don't yet have a satisfying solution for the "multi-dpi" problem (using the `docking` branch: when multiple viewport windows are over multiple monitors using different DPI scale). The current way to handle this on the application side is: +- Create and maintain one font atlas per active DPI scale (e.g. by iterating `platform_io.Monitors[]` before `NewFrame()`). +- Hook `platform_io.OnChangedViewport()` to detect when a `Begin()` call makes a Dear ImGui window change monitor (and therefore DPI). +- In the hook: swap atlas, swap style with correctly sized one, remap the current font from one atlas to the other (may need to maintain a remapping table of your fonts at variying DPI scale). + +This approach is relatively easy and functional but come with two issues: +- It's not possibly to reliably size or position a window ahead of `Begin()` without knowing on which monitor it'll land. +- Style override may be lost during the `Begin()` call crossing monitor boundaries. You may need to do some custom scaling mumbo-jumbo if you want your `OnChangedViewport()` handler to preserve style overrides. + +Please note that if you are not using multi-viewports with multi-monitors using different DPI scale, you can ignore all of this and use the simpler technique recommended at the top. + ### Q: How can I load a different font than the default? Use the font atlas to load the TTF/OTF file you want: -```c +```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() @@ -459,7 +483,7 @@ Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear img New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash "\\": -```c +```cpp io.Fonts->AddFontFromFileTTF("MyFolder\MyFont.ttf", size); // WRONG (you are escaping the M here!) io.Fonts->AddFontFromFileTTF("MyFolder\\MyFont.ttf", size; // CORRECT io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT diff --git a/docs/FONTS.md b/docs/FONTS.md index d2f40f2b..158e08ab 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -14,6 +14,7 @@ In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) fo ## Index - [Readme First](#readme-first) +- [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application) - [Fonts Loading Instructions](#font-loading-instructions) - [Using Icons](#using-icons) - [Using FreeType Rasterizer](#using-freetype-rasterizer) @@ -43,6 +44,13 @@ u8"こんにちは" // this will be encoded as UTF-8 ##### [Return to Index](#index) +## How should I handle DPI in my application? + +See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application). + +##### [Return to Index](#index) + + ## Font Loading Instructions **Load default font:** @@ -51,6 +59,7 @@ ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontDefault(); ``` + **Load .TTF/.OTF file with:** ```cpp ImGuiIO& io = ImGui::GetIO(); @@ -58,6 +67,7 @@ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ``` If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully. + **Load multiple fonts:** ```cpp ImGuiIO& io = ImGui::GetIO(); @@ -71,6 +81,7 @@ ImGui::Text("Hello with another font"); ImGui::PopFont(); ``` + **For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** ```cpp ImFontConfig config; @@ -80,6 +91,7 @@ config.GlyphExtraSpacing.x = 1.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); ``` + **Combine multiple fonts into one:** ```cpp // Load a first font @@ -97,6 +109,7 @@ io.Fonts->Build(); ``` **Add a fourth parameter to bake specific font ranges only:** + ```cpp // Basic Latin, Extended Latin io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); @@ -109,6 +122,27 @@ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRa ``` See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges. + +**Example loading and using a Japanese font:** + +```cpp +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); +``` +```cpp +ImGui::Text(u8"こんにちは!テスト %d", 123); +if (ImGui::Button(u8"ロード")) +{ + // do stuff +} +ImGui::InputText("string", buf, IM_ARRAYSIZE(buf)); +ImGui::SliderFloat("float", &f, 0.0f, 1.0f); +``` + +![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png) +
_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_ + + **Offset font vertically by altering the `io.Font->DisplayOffset` value:** ```cpp ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); diff --git a/imgui.cpp b/imgui.cpp index 2d740d1b..b05f969a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -765,11 +765,12 @@ CODE Q&A: Fonts, Text ================ + Q: How should I handle DPI in my application? Q: How can I load a different font than the default? Q: How can I easily use icons in my application? Q: How can I load multiple fonts? Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? - >> See https://www.dearimgui.org/faq (docs/FAQ.md) docs/FONTS.md + >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md Q&A: Concerns ============= From 16da8e6da6ae58c9ab639eb678d69bd22e729528 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Jun 2020 17:54:19 +0200 Subject: [PATCH 085/959] Revert "Columns: Lower overhead on column switches and switching to background channel (some stress tests in debug builds went 3->2 ms). (#125)" This reverts commit 9b3ce494fdee20f56ee672febe2f9d737a3927cc. --- docs/CHANGELOG.txt | 2 -- imgui.cpp | 7 +------ imgui_internal.h | 1 - imgui_widgets.cpp | 29 ++++------------------------- 4 files changed, 5 insertions(+), 34 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 90e06972..9ca3d387 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -46,8 +46,6 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) -- Columns: Lower overhead on column switches and switching to background channel (some of our stress - tests in debug builds went 3->2 ms). Benefits Columns but was primarily made with Tables in mind! - Style: Added style.TabMinWidthForUnselectedCloseButton settings. Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). diff --git a/imgui.cpp b/imgui.cpp index b05f969a..4f66fda2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4168,12 +4168,7 @@ static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_da } } -// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. -// - When using this function it is sane to ensure that float are perfectly rounded to integer values, -// so that e.g. (int)(max.x-min.x) in user's render produce correct result. -// - 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 a more -// specialized code path to added extraneous updates of the underlying ImDrawCmd. +// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/imgui_internal.h b/imgui_internal.h index b07c5568..7b15e63f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -435,7 +435,6 @@ struct IMGUI_API ImRect void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } - ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } }; // Helper: ImBitArray diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7d5bc5cf..2ba7c6b4 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7549,11 +7549,6 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; - - // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop - //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PushColumnsBackground()\n"); - window->DrawList->_CmdHeader.ClipRect = columns->HostClipRect.ToVec4(); - columns->Splitter.SetCurrentChannel(window->DrawList, 0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); @@ -7567,12 +7562,6 @@ void ImGui::PopColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; - - // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop - //if (window->DrawList->Flags & ImDrawListFlags_Debug) IMGUI_DEBUG_LOG("PopColumnsBackground()\n"); - ImVec4 pop_clip_rect = window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 2]; - window->DrawList->_CmdHeader.ClipRect = pop_clip_rect; - columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); PopClipRect(); } @@ -7695,22 +7684,11 @@ void ImGui::NextColumn() return; } PopItemWidth(); - - // Next column - if (++columns->Current == columns->Count) - columns->Current = 0; - - // As a small optimization, to avoid doing PopClipRect() + SetCurrentChannel() + PushClipRect() - // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), - // We use a shortcut: we override ClipRect in window and drawlist's CmdHeader + SetCurrentChannel(). - ImGuiColumnData* column = &columns->Columns[columns->Current]; - window->ClipRect = column->ClipRect; - window->DrawList->_CmdHeader.ClipRect = column->ClipRect.ToVec4(); - //PopClipRect(); + PopClipRect(); const float column_padding = g.Style.ItemSpacing.x; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (columns->Current > 0) + if (++columns->Current < columns->Count) { // Columns 1+ ignore IndentX (by canceling it out) // FIXME-COLUMNS: Unnecessary, could be locked? @@ -7723,6 +7701,7 @@ void ImGui::NextColumn() // Column 0 honor IndentX window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); columns->Splitter.SetCurrentChannel(window->DrawList, 1); + columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -7730,7 +7709,7 @@ void ImGui::NextColumn() window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = 0.0f; - //PushColumnClipRect(columns->Current); + PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. float offset_0 = GetColumnOffset(columns->Current); From 64d8d302fb379dd9d7fbe5475a32bd6d61004db5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 10 Jun 2020 19:16:06 +0200 Subject: [PATCH 086/959] ImDrawList: Fixed VtxOffset change leading to unnecessary leading empty ImDrawCmd in certain cases. --- imgui.h | 1 + imgui_draw.cpp | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 3f25e81e..4de17899 100644 --- a/imgui.h +++ b/imgui.h @@ -2075,6 +2075,7 @@ struct ImDrawList IMGUI_API void _PopUnusedDrawCmd(); IMGUI_API void _OnChangedClipRect(); IMGUI_API void _OnChangedTextureID(); + IMGUI_API void _OnChangedVtxOffset(); }; // All draw data to render a Dear ImGui frame diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 94f223ba..5b0a9855 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -514,6 +514,21 @@ void ImDrawList::_OnChangedTextureID() curr_cmd->TextureId = _CmdHeader.TextureId; } +void ImDrawList::_OnChangedVtxOffset() +{ + // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this. + _VtxCurrentIdx = 0; + ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; + IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); + if (curr_cmd->ElemCount != 0) + { + AddDrawCmd(); + return; + } + IM_ASSERT(curr_cmd->UserCallback == NULL); + curr_cmd->VtxOffset = _CmdHeader.VtxOffset; +} + // 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) void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) { @@ -570,8 +585,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { _CmdHeader.VtxOffset = VtxBuffer.Size; - _VtxCurrentIdx = 0; - AddDrawCmd(); + _OnChangedVtxOffset(); } ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; From a933cc4f4d366340eff5c6dcb3a927478c9006a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 11 Jun 2020 09:52:46 +0200 Subject: [PATCH 087/959] Documentation update --- docs/FAQ.md | 11 +++++++++-- docs/README.md | 29 ++++++++++++++++------------- imgui.cpp | 3 ++- 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 5e824b86..1401486a 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -20,6 +20,7 @@ or view this file with any Markdown viewer. | [How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)](#q-how-can-i-use-this-on-a-machine-without-mouse-keyboard-or-screen-input-share-remote-display) | | [I integrated Dear ImGui in my engine and the text or lines are blurry..](#q-i-integrated-dear-imgui-in-my-engine-and-the-text-or-lines-are-blurry) | | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | +| [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | **Q&A: Usage** | | **[Why are multiple widgets reacting when I interact with a single one?
How can I have multiple widgets with the same label or with an empty label?](#q-why-are-multiple-widgets-reacting-when-i-interact-with-a-single-one-q-how-can-i-have-multiple-widgets-with-the-same-label-or-with-an-empty-label)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| @@ -27,7 +28,7 @@ or view this file with any Markdown viewer. | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | | [How can I display custom shapes? (using low-level ImDrawList API)](#q-how-can-i-display-custom-shapes-using-low-level-imdrawlist-api) | | **Q&A: Fonts, Text** | -| [How should I handle DPi in my application?](#q-how-should-i-handle-dpi-in-my-application) | +| [How should I handle DPI in my application?](#q-how-should-i-handle-dpi-in-my-application) | | [How can I load a different font than the default?](#q-how-can-i-load-a-different-font-than-the-default) | | [How can I easily use icons in my application?](#q-how-can-i-easily-use-icons-in-my-application) | | [How can I load multiple fonts?](#q-how-can-i-load-multiple-fonts) | @@ -78,6 +79,9 @@ You may use the [docking](https://github.com/ocornut/imgui/tree/docking) branch Many projects are using this branch and it is kept in sync with master regularly. +You may merge in the [tables](https://github.com/ocornut/imgui/tree/tables) branch which includes: +- [Table features](https://github.com/ocornut/imgui/issues/2957) + ##### [Return to Index](#index) ---- @@ -144,11 +148,14 @@ Also make sure your orthographic projection matrix and io.DisplaySize matches yo --- ### Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. +### Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. You are probably mishandling the clipping rectangles in your render function. -Rectangles provided by ImGui are defined as +Each draw command needs the triangle rendered using the clipping rectangle provided in the ImDrawCmd structure (`ImDrawCmd->CllipRect`). +Rectangles provided by Dear ImGui are defined as `(x1=left,y1=top,x2=right,y2=bottom)` and **NOT** as `(x1,y1,width,height)` +Refer to rendering back-ends in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder for references of how to handle the `ClipRect` field. ##### [Return to Index](#index) diff --git a/docs/README.md b/docs/README.md index 5536c5bc..df32b9c2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,7 +5,7 @@ Dear ImGui (This library is available under a free and permissive license, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out.) Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts: -
  _E-mail: contact @ dearimgui dot org_ +
  _E-mail: contact @ dearimgui dot com_ Individuals: support continued maintenance and development with [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). @@ -99,7 +99,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: - [imgui-demo-binaries-20190715.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows binaries, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). -The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your style with `style.ScaleAllSizes()`. +The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.org/faq)). ### Integration @@ -122,11 +122,11 @@ Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. ### Upcoming Changes Some of the goals for 2020 are: -- Finish work on docking, tabs. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) -- Finish work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) -- Finish work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) -- Finish work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957)) -- Add an automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) +- Work on docking. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch) +- Work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) +- Work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) +- Work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957)) +- Work on automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) - Make the examples look better, improve styles, improve font support, make the examples hi-DPI and multi-DPI aware. ### Gallery @@ -154,7 +154,7 @@ If you are new to Dear ImGui and have issues with: compiling, linking, adding fo Otherwise, for any other questions, bug reports, requests, feedback, you may post on https://github.com/ocornut/imgui/issues. Please read and fill the New Issue template carefully. -Paid private support is available for business customers (E-mail: _contact @ dearimgui dot org_). +Private support is available for paying business customers (E-mail: _contact @ dearimgui dot com_). **Which version should I get?** @@ -174,14 +174,14 @@ How to help - You may participate in the [Discord server](http://discord.dearimgui.org), [GitHub forum/issues](https://github.com/ocornut/imgui/issues). - You may help with development and submit pull requests! Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance forever. PR should be crafted both in the interest in the end-users and also to ease the maintainer into understanding and accepting it. - See [Help wanted](https://github.com/ocornut/imgui/wiki/Help-Wanted) on the [Wiki](https://github.com/ocornut/imgui/wiki/) for some more ideas. -- Have your company financially support this project. +- Have your company financially support this project (please reach by e-mail) **How can I help financing further development of Dear ImGui?** Your contributions are keeping this project alive. The library is available under a free and permissive license, but continued maintenance and development are a full-time endeavor and I would like to grow the team. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out for invoiced technical support and maintenance contracts. Thank you! Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts: -
  _E-mail: contact @ dearimgui dot org_ +
  _E-mail: contact @ dearimgui.com_ Individuals: support continued maintenance and development with [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). @@ -194,7 +194,7 @@ Ongoing Dear ImGui development is financially supported by users and private spo - [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui/) *Double-chocolate and Salty caramel sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) +- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [RAD Game Tools](http://www.radgametools.com/), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors). @@ -208,9 +208,12 @@ Dear ImGui is using software and services provided free of charge for open sourc Credits ------- -Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com) (PS Vita). +Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect [contributors](https://github.com/ocornut/imgui/graphs/contributors) to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com) (PS Vita). -I first discovered the IMGUI paradigm at [Q-Games](http://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it. +Recurring contributors (2020): Omar Cornut [@ocornut](https://github.com/ocornut), Rokas Kupstys [@rokups](https://github.com/rokups), Ben Carter [@ShironekoBen](https://github.com/ShironekoBen). +A large portion of work on automation systems, regression tests and other features are currently unpublished. + +"I first discovered the IMGUI paradigm at [Q-Games](http://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it." Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license). diff --git a/imgui.cpp b/imgui.cpp index 4f66fda2..fcdcfd3a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -633,7 +633,8 @@ CODE Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - >> See https://www.dearimgui.org/faq + Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. +>> See https://www.dearimgui.org/faq Q&A: Usage ---------- From d3b37180a3ff186b481d93d09664bb244a428d10 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Sat, 13 Jun 2020 14:14:07 +0200 Subject: [PATCH 088/959] ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra unrequired vertex. Amend 5363af7f47573c8a9231bc44bc6252188affea08, 051ce0765ef8569729c9ae9b3d466132f9010b89 --- docs/CHANGELOG.txt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9ca3d387..9feee86e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,19 +56,21 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] -- ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the +- ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where changing channels with different TextureId, VtxOffset would incorrectly apply new settings to draw channels. (#3129, #3163) [@ocornut, @thedmd, @Shironekoben] -- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current +- ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split when current VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after a callback draw command would incorrectly override the callback draw command. +- ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would + generate an extra unrequired vertex. [@ShironekoBen] - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. -- Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. - Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] +- Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. + Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). Fixed a static contructor which led to this dependency on some compiler setups (unclear which). From 90c0c0c163b48b6bb274a4153f96870e9e4dd727 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Jun 2020 15:48:05 +0200 Subject: [PATCH 089/959] Columns: Lower overhead on column switches and switching to background channel. (second attempt for 9b3ce49) Internals: Bits, comments, added ImRect::ToVec4() --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 7 ++++++- imgui_internal.h | 5 ++++- imgui_widgets.cpp | 49 ++++++++++++++++++++++++++++++++-------------- 4 files changed, 46 insertions(+), 17 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9feee86e..9852e5bd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,8 @@ Other Changes: BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] +- Columns: Lower overhead on column switches and switching to background channel. + Benefits Columns but was primarily made with Tables in mind! - ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] diff --git a/imgui.cpp b/imgui.cpp index fcdcfd3a..c84247a2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4169,7 +4169,12 @@ static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_da } } -// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +// - When using this function it is sane to ensure that float are perfectly rounded to integer values, +// so that e.g. (int)(max.x-min.x) in user's render produce correct result. +// - 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. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); diff --git a/imgui_internal.h b/imgui_internal.h index 7b15e63f..f8ec2fdf 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -435,6 +435,7 @@ struct IMGUI_API ImRect void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } + ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } }; // Helper: ImBitArray @@ -1012,7 +1013,8 @@ struct ImGuiColumns float LineMinY, LineMaxY; float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() - ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns() + ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() + ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns() ImVector Columns; ImDrawListSplitter Splitter; @@ -1894,6 +1896,7 @@ namespace ImGui IMGUI_API bool IsDragDropPayloadBeingAccepted(); // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) + IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect); IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). IMGUI_API void EndColumns(); // close columns IMGUI_API void PushColumnClipRect(int column_index); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ba7c6b4..7fd76823 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7398,6 +7398,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. // In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. //------------------------------------------------------------------------- +// - SetWindowClipRectBeforeSetChannel() [Internal] // - GetColumnIndex() // - GetColumnCount() // - GetColumnOffset() @@ -7415,6 +7416,18 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, // - Columns() //------------------------------------------------------------------------- +// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +// they would meddle many times with the underlying ImDrawCmd. +// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +// the subsequent single call to SetCurrentChannel() does it things once. +void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect) +{ + ImVec4 clip_rect_vec4 = clip_rect.ToVec4(); + window->ClipRect = clip_rect; + window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4; + window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4; +} + int ImGui::GetColumnIndex() { ImGuiWindow* window = GetCurrentWindowRead(); @@ -7549,11 +7562,11 @@ void ImGui::PushColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + columns->HostBackupClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect); columns->Splitter.SetCurrentChannel(window->DrawList, 0); - int cmd_size = window->DrawList->CmdBuffer.Size; - PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); - IM_UNUSED(cmd_size); - IM_ASSERT(cmd_size >= window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } void ImGui::PopColumnsBackground() @@ -7562,8 +7575,10 @@ void ImGui::PopColumnsBackground() ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect); columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); - PopClipRect(); } ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) @@ -7611,7 +7626,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; - columns->HostClipRect = window->ClipRect; + columns->HostInitialClipRect = window->ClipRect; columns->HostWorkRect = window->WorkRect; // Set state for first column @@ -7683,25 +7698,31 @@ void ImGui::NextColumn() IM_ASSERT(columns->Current == 0); return; } + + // Next column + if (++columns->Current == columns->Count) + columns->Current = 0; + PopItemWidth(); - PopClipRect(); + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), + ImGuiColumnData* column = &columns->Columns[columns->Current]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); const float column_padding = g.Style.ItemSpacing.x; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (++columns->Current < columns->Count) + if (columns->Current > 0) { // Columns 1+ ignore IndentX (by canceling it out) // FIXME-COLUMNS: Unnecessary, could be locked? window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding; - columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); } else { - // New row/line - // Column 0 honor IndentX + // New row/line: column 0 honor IndentX. window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); - columns->Splitter.SetCurrentChannel(window->DrawList, 1); - columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -7709,8 +7730,6 @@ void ImGui::NextColumn() window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = 0.0f; - PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? - // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. float offset_0 = GetColumnOffset(columns->Current); float offset_1 = GetColumnOffset(columns->Current + 1); From c658cba22b67af4de3da948e4ac39ce9b852a967 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jun 2020 16:18:30 +0200 Subject: [PATCH 090/959] Comments, reworded some !(xxx && xxx) complex expression to be a little less confusing. --- imgui_draw.cpp | 2 +- imgui_widgets.cpp | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5b0a9855..750bf9f6 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2906,7 +2906,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 != '\"'); } // We ignore blank width at the end of the line (they can be skipped) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7fd76823..bb69d888 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -557,7 +557,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool if ((flags & ImGuiButtonFlags_PressedOnRelease) && mouse_button_released != -1) { // Repeat mode trumps on release behavior - if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay)) + const bool has_repeated_at_least_once = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; + if (!has_repeated_at_least_once) pressed = true; ClearActiveID(); } @@ -3469,18 +3470,22 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f // Generic named filters if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific)) { + // Allow 0-9 . - + * / if (flags & ImGuiInputTextFlags_CharsDecimal) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; + // Allow 0-9 . - + * / e E if (flags & ImGuiInputTextFlags_CharsScientific) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) return false; + // Allow 0-9 a-F A-F if (flags & ImGuiInputTextFlags_CharsHexadecimal) if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return false; + // Turn a-z into A-Z if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') *p_char = (c += (unsigned int)('A'-'a')); @@ -4283,7 +4288,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ PopFont(); // Log as text - if (g.LogEnabled && !(is_password && !is_displaying_hint)) + if (g.LogEnabled && (!is_password || is_displaying_hint)) LogRenderedText(&draw_pos, buf_display, buf_display_end); if (label_size.x > 0) @@ -7157,7 +7162,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) tab_contents_visible = true; - if (tab_appearing && !(tab_bar_appearing && !tab_is_new)) + // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted + // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. + if (tab_appearing && (!tab_bar_appearing || tab_is_new)) { PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true); ItemAdd(ImRect(), id); @@ -7275,7 +7282,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. -// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem() +// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem(). +// Tabs closed by the close button will automatically be flagged to avoid this issue. +// FIXME: We should aim to support calling SetTabItemClosed() after the tab submission (for next frame) void ImGui::SetTabItemClosed(const char* label) { ImGuiContext& g = *GImGui; From 99ab521024ae68d72b8479f66ea2f052e54f2cac Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jun 2020 22:06:45 +0200 Subject: [PATCH 091/959] Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). + Removed CalcItemRectClosestPoint() entry point --- docs/CHANGELOG.txt | 2 ++ docs/TODO.txt | 1 - imgui.cpp | 6 ++++-- imgui.h | 5 +++-- imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 10 +++++----- 6 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9852e5bd..2d70bc8d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,6 +38,8 @@ Breaking Changes: - Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. +- Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). +- Removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. Other Changes: diff --git a/docs/TODO.txt b/docs/TODO.txt index 75438a6a..955fa31a 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -203,7 +203,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) - popups/modal: make modal title bar blink when trying to click outside the modal - - popups: reopening context menu at new position should be the behavior by default? (equivalent to internal OpenPopupEx() with reopen_existing=true) (~#1497) - popups: if the popup functions took explicit ImGuiID it would allow the user to manage the scope of those ID. (#331) - popups: clicking outside (to close popup) and holding shouldn't drag window below. - popups: add variant using global identifier similar to Begin/End (#402) diff --git a/imgui.cpp b/imgui.cpp index c84247a2..23795c58 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,7 +372,9 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - - 2020/04/23 (1.77) - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). + - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). + - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. + - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead. - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value. @@ -7842,7 +7844,7 @@ void ImGui::EndPopup() g.WithinEndChild = false; } -bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) diff --git a/imgui.h b/imgui.h index 4de17899..be56fa35 100644 --- a/imgui.h +++ b/imgui.h @@ -609,7 +609,7 @@ namespace ImGui IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! - IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack. IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. @@ -1632,6 +1632,8 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.77 (from June 2020) + static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1) { return OpenPopupContextItem(str_id, mouse_button); } // OBSOLETED in 1.72 (from July 2019) static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.71 (from June 2019) @@ -1652,7 +1654,6 @@ namespace ImGui // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } - static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { IM_UNUSED(on_edge); IM_UNUSED(outward); IM_ASSERT(0); return pos; } } typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ace91fd0..4c48ade5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2829,11 +2829,11 @@ static void ShowDemoWindowPopups() ImGui::EndPopup(); } - // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the + // We can also use OpenPopupContextItem() which is the same as BeginPopupContextItem() but without the // Begin() call. So here we will make it that clicking on the text field with the right mouse button (1) // will toggle the visibility of the popup above. ImGui::Text("(You can also right-click me to open the same popup as above.)"); - ImGui::OpenPopupOnItemClick("item context menu", 1); + ImGui::OpenPopupContextItem("item context menu", 1); // When used after an item that has an ID (e.g.Button), we can skip providing an ID to BeginPopupContextItem(). // BeginPopupContextItem() will use the last item ID as the popup ID. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bb69d888..7ed51369 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4435,7 +4435,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); } } else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) @@ -4460,7 +4460,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); } ImGuiWindow* picker_active_window = NULL; @@ -4481,7 +4481,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag } } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); if (BeginPopup("picker")) { @@ -4701,7 +4701,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl } } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { @@ -4714,7 +4714,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl value_changed = value_changed_sv = true; } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupOnItemClick("context"); + OpenPopupContextItem("context"); // Hue bar logic SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); From 1dfd0634cbe70a52a78f1ff247df1db491b745ed Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jun 2020 19:06:20 +0200 Subject: [PATCH 092/959] Internals: Allow ItemHoverable() to be used with id==0 to facilitate high-level read-only hover test in widget code. --- imgui.cpp | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 23795c58..8c0afd06 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3172,17 +3172,22 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) return false; - SetHoveredID(id); - - // [DEBUG] Item Picker tool! - // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making - // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered - // items if we perform the test in ItemAdd(), but that would incur a small runtime cost. - // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd(). - if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id) - GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255)); - if (g.DebugItemPickerBreakId == id) - IM_DEBUG_BREAK(); + // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level + // hover test in widgets code. We could also decide to split this function is two. + if (id != 0) + { + SetHoveredID(id); + + // [DEBUG] Item Picker tool! + // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making + // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered + // items if we perform the test in ItemAdd(), but that would incur a small runtime cost. + // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd(). + if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id) + GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255)); + if (g.DebugItemPickerBreakId == id) + IM_DEBUG_BREAK(); + } return true; } From d31fe97f741ae57600cc0762804eb5fcf79cbc97 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 16:50:28 +0200 Subject: [PATCH 093/959] Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 36 ++++++++++++++++++++++++++---------- imgui_internal.h | 3 ++- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2d70bc8d..ad078258 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,8 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Popups: Fix an edge case where programatically closing a popup while clicking on its empty space + would attempt to focus it and close other popups. (#2880) - Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index 8c0afd06..07c2ea10 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3449,17 +3449,22 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (g.NavWindow && g.NavWindow->Appearing) return; - // Click to focus window and start moving (after we're done with all our widgets) + // Click on empty space to focus window and start moving (after we're done with all our widgets) if (g.IO.MouseClicked[0]) { - if (g.HoveredRootWindow != NULL) + // Handle the edge case of a popup being closed while clicking in its empty space. + // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. + ImGuiWindow* root_window = g.HoveredRootWindow; + const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpenAtAnyLevel(root_window->PopupId); + + if (root_window != NULL && !is_closed_popup) { StartMouseMovingWindow(g.HoveredWindow); - if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar)) - if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) + if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) + if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; } - else if (g.NavWindow != NULL && GetTopMostPopupModal() == NULL) + else if (root_window != NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { // Clicking on void disable focus FocusWindow(NULL); @@ -3700,7 +3705,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) - g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); + g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (g.OpenPopupStack.Size > 0); mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down]) @@ -3718,7 +3723,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() if (g.WantCaptureMouseNextFrame != -1) g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0); else - g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty()); + g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.OpenPopupStack.Size > 0); // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app) if (g.WantCaptureKeyboardNextFrame != -1) @@ -7610,6 +7615,15 @@ bool ImGui::IsPopupOpen(const char* str_id) return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); } +bool ImGui::IsPopupOpenAtAnyLevel(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + for (int n = 0; n < g.OpenPopupStack.Size; n++) + if (g.OpenPopupStack[n].PopupId == id) + return true; + return false; +} + ImGuiWindow* ImGui::GetTopMostPopupModal() { ImGuiContext& g = *GImGui; @@ -7661,8 +7675,8 @@ void ImGui::OpenPopupEx(ImGuiID id) else { // Close child popups if any, then flag popup for open/reopen - g.OpenPopupStack.resize(current_stack_size + 1); - g.OpenPopupStack[current_stack_size] = popup_ref; + ClosePopupToLevel(current_stack_size, false); + g.OpenPopupStack.push_back(popup_ref); } // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). @@ -7675,7 +7689,7 @@ void ImGui::OpenPopupEx(ImGuiID id) void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; - if (g.OpenPopupStack.empty()) + if (g.OpenPopupStack.Size == 0) return; // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. @@ -7714,6 +7728,8 @@ void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_ { ImGuiContext& g = *GImGui; IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); + + // Trim open popup stack ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow; ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window; g.OpenPopupStack.resize(remaining); diff --git a/imgui_internal.h b/imgui_internal.h index f8ec2fdf..3e88b054 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1581,7 +1581,7 @@ struct IMGUI_API ImGuiWindow bool WantCollapseToggle; bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) bool Appearing; // Set during the frame where the window is appearing (or re-appearing) - bool Hidden; // Do not display (== (HiddenFrames*** > 0)) + bool Hidden; // Do not display (== HiddenFrames*** > 0) bool IsFallbackWindow; // Set on the "Debug##Default" window. bool HasCloseButton; // Set when the window has a close button (p_open != NULL) signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) @@ -1853,6 +1853,7 @@ namespace ImGui IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id at current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! + IMGUI_API bool IsPopupOpenAtAnyLevel(ImGuiID id); IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); From 37eb89371b7ee8b0728b07b2ab437c6281bc8261 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 18:46:14 +0200 Subject: [PATCH 094/959] Popups: Internals: Added IsAnyPopupOpen(). --- imgui.cpp | 22 ++++++++++++++++++---- imgui.h | 5 +++-- imgui_demo.cpp | 2 +- imgui_internal.h | 3 ++- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 07c2ea10..7358b22a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7603,12 +7603,14 @@ void ImGui::SetTooltip(const char* fmt, ...) // [SECTION] POPUPS //----------------------------------------------------------------------------- +// Return true if the popup is open at the current BeginPopup() level of the popup stack bool ImGui::IsPopupOpen(ImGuiID id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; } +// Return true if the popup is open at the current BeginPopup() level of the popup stack bool ImGui::IsPopupOpen(const char* str_id) { ImGuiContext& g = *GImGui; @@ -7624,6 +7626,14 @@ bool ImGui::IsPopupOpenAtAnyLevel(ImGuiID id) return false; } +// Return true if any popup is open at the current BeginPopup() level of the popup stack +// This may be used to e.g. test for another popups already opened in the same frame to handle popups priorities at the same level. +bool ImGui::IsAnyPopupOpen() +{ + ImGuiContext& g = *GImGui; + return g.OpenPopupStack.Size > g.BeginPopupStack.Size; +} + ImGuiWindow* ImGui::GetTopMostPopupModal() { ImGuiContext& g = *GImGui; @@ -7879,8 +7889,10 @@ bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_butt } // This is a helper to handle the simplest case of associating one named popup to one given widget. -// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). -// You can pass a NULL str_id to use the identifier of the last item. +// - You can pass a NULL str_id to use the identifier of the last item. +// - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +// - This is essentially the same as calling OpenPopupContextItem() + BeginPopupEx() but written to avoid +// computing the ID twice because BeginPopupContextXXX functions are called very frequently. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; @@ -7895,9 +7907,10 @@ bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_but bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items) { + ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "window_context"; - ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + ImGuiID id = window->GetID(str_id); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(id); @@ -7906,9 +7919,10 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_b bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button) { + ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "void_context"; - ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + ImGuiID id = window->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); diff --git a/imgui.h b/imgui.h index be56fa35..13657d74 100644 --- a/imgui.h +++ b/imgui.h @@ -602,6 +602,7 @@ namespace ImGui // (*1) You can bypass that restriction and detect hovering even when normally blocked by a popup. // To do this use the ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). // This is what BeginPopupContextItem() and BeginPopupContextWindow() are doing already, allowing a right-click to reopen another popups without losing the click. + // - The BeginPopupContextXXX functions are essentially helpers to do an OpenPopup() in some condition + BeginPopup(). IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! @@ -609,8 +610,8 @@ namespace ImGui IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! - IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. - IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack. + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. // Columns diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4c48ade5..65d24bbd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2813,7 +2813,7 @@ static void ShowDemoWindowPopups() if (ImGui::TreeNode("Context menus")) { // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: - // if (IsItemHovered() && IsMouseReleased(0)) + // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) // OpenPopup(id); // return BeginPopup(id); // For more advanced uses you may want to replicate and customize this code. diff --git a/imgui_internal.h b/imgui_internal.h index 3e88b054..4f101920 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1852,8 +1852,9 @@ namespace ImGui IMGUI_API void OpenPopupEx(ImGuiID id); IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); - IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id at current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack! + IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id at the current BeginPopup() level of the popup stack (this doesn't scan the whole popup stack!) IMGUI_API bool IsPopupOpenAtAnyLevel(ImGuiID id); + IMGUI_API bool IsAnyPopupOpen(); // Return true if any popup is open at the current BeginPopup() level of the popup stack IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); From 6e138504c1dc097a3b492da193101a9df950f260 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 19:32:21 +0200 Subject: [PATCH 095/959] Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) --- docs/CHANGELOG.txt | 1 + imgui.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ad078258..47995a88 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Other Changes: Set to an intermediary value to toggle behavior based on width (same as Firefox). - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) +- Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) - Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index 7358b22a..496e71b7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7924,7 +7924,8 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_but str_id = "void_context"; ImGuiID id = window->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) - OpenPopupEx(id); + if (GetTopMostPopupModal() == NULL) + OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } From 078571b7a99d87d83140d5e13f101c5528e25c48 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 23:05:01 +0200 Subject: [PATCH 096/959] Popups: added comments, reorganized the functions in imgui.h --- docs/CHANGELOG.txt | 3 ++- docs/TODO.txt | 4 +++- imgui.cpp | 2 +- imgui.h | 50 ++++++++++++++++++++++++++-------------------- 4 files changed, 34 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 47995a88..a110a596 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,7 +55,7 @@ Other Changes: - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) -- Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] +- Popups: Clarified some of the comments and function prototypes. - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] @@ -63,6 +63,7 @@ Other Changes: drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Columns: Lower overhead on column switches and switching to background channel. Benefits Columns but was primarily made with Tables in mind! +- Fonts: Fix GetGlyphRangesKorean() end-range to end at 0xD7A3 (instead of 0xD79D). (#348, #3217) [@marukrap] - ImDrawList: Fixed an issue where draw command merging or primitive unreserve while crossing the VtxOffset boundary would lead to draw commands with wrong VtxOffset. (#3129, #3163, #3232, #2591) [@thedmd, @Shironekoben, @sergeyn, @ocornut] diff --git a/docs/TODO.txt b/docs/TODO.txt index 955fa31a..213d1d35 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -202,11 +202,13 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - listbox: future api should allow to enable horizontal scrolling (#2510) !- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) - - popups/modal: make modal title bar blink when trying to click outside the modal + - modals: make modal title bar blink when trying to click outside the modal + - modals: technically speaking, we could make Begin() with ImGuiWindowFlags_Modal work without involving popup. May help untangle a few things, as modals are more like regular windows than popups. - popups: if the popup functions took explicit ImGuiID it would allow the user to manage the scope of those ID. (#331) - popups: clicking outside (to close popup) and holding shouldn't drag window below. - popups: add variant using global identifier similar to Begin/End (#402) - popups: border options. richer api like BeginChild() perhaps? (#197) + - popups/modals: although it is sometimes convenient that popups/modals lifetime is owned by imgui, we could also a bool-owned-by-user api as long as Begin() return value testing is enforced. - tooltip: drag and drop with tooltip near monitor edges lose/changes its last direction instead of locking one. The drag and drop tooltip should always follow without changing direction. - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred direction" and may teleport when moving mouse. diff --git a/imgui.cpp b/imgui.cpp index 496e71b7..584b7a85 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7891,7 +7891,7 @@ bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_butt // This is a helper to handle the simplest case of associating one named popup to one given widget. // - You can pass a NULL str_id to use the identifier of the last item. // - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). -// - This is essentially the same as calling OpenPopupContextItem() + BeginPopupEx() but written to avoid +// - This is essentially the same as calling OpenPopupContextItem() + BeginPopup() but written to avoid // computing the ID twice because BeginPopupContextXXX functions are called very frequently. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) { diff --git a/imgui.h b/imgui.h index 13657d74..fd852a5d 100644 --- a/imgui.h +++ b/imgui.h @@ -591,28 +591,34 @@ namespace ImGui IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); // Popups, Modals - // The properties of popups windows are: - // - They block normal mouse hovering detection outside them. (*1) - // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. - // Because hovering detection is disabled outside the popup, when clicking outside the click will not be seen by underlying widgets! (*1) - // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as we are used to with regular Begin() calls. - // User can manipulate the visibility state by calling OpenPopup(), CloseCurrentPopup() etc. - // - We default to use the right mouse (ImGuiMouseButton_Right=1) for the Popup Context functions. - // Those three properties are connected: we need to retain popup visibility state in the library because popups may be closed as any time. - // (*1) You can bypass that restriction and detect hovering even when normally blocked by a popup. - // To do this use the ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). - // This is what BeginPopupContextItem() and BeginPopupContextWindow() are doing already, allowing a right-click to reopen another popups without losing the click. - // - The BeginPopupContextXXX functions are essentially helpers to do an OpenPopup() in some condition + BeginPopup(). - IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). - IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! - IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! - IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window. - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). - IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) - IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! - IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) - IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack - IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. + // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. + // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. + // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). + // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. + // This is sometimes leading to confusing mistakes. May rework this in the future. + // Popups: begin/end functions + // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window. + // - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar. + IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. + IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! + // Popups: open/close functions + // - OpenPopup(): set popup state to open. + // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. + // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). + IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. + IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack + // Popups: open+begin combined functions helpers + // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. + // - They are convenient to easily create context menus, hence the name. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1, bool also_over_items = true); // open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked in void (where there are no windows). // Columns // - You can also use SameLine(pos_x) to mimic simplified columns. From b1d8309abcbe67755b2a7e96c1f4a0123db2882e Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Thu, 18 Jun 2020 15:18:14 +0200 Subject: [PATCH 097/959] Added ImGuiTabItemFlags_NoTooltip for individual Tab Item. --- docs/CHANGELOG.txt | 2 ++ imgui.h | 3 ++- imgui_widgets.cpp | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a110a596..b479a333 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -52,6 +52,8 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item + (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) diff --git a/imgui.h b/imgui.h index fd852a5d..eb2a611b 100644 --- a/imgui.h +++ b/imgui.h @@ -913,7 +913,8 @@ enum ImGuiTabItemFlags_ ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. Also: tab is selected on closure and closure is deferred by one frame to allow code to undo it without flicker. ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. - ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoTooltip = 1 << 4 // Disable tooltip for the given tab }; // Flags for ImGui::IsWindowFocused() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7ed51369..0ce3de71 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7275,7 +7275,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer) // We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores) if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered()) - if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip)) + if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip)) SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); return tab_contents_visible; From 704723744e1515784cce6ac18d43f62fa84545fa Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Jun 2020 16:19:51 +0200 Subject: [PATCH 098/959] Disabled latest overzealous warnings from Clang --- imgui.cpp | 25 ++++++++++++++----------- imgui_demo.cpp | 3 +++ imgui_draw.cpp | 21 ++++++++++++--------- imgui_internal.h | 3 +++ imgui_widgets.cpp | 20 +++++++++++++------- 5 files changed, 45 insertions(+), 27 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 584b7a85..648c265e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -864,20 +864,23 @@ CODE // Clang/GCC warnings with -Weverything #if defined(__clang__) -#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! -#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. -#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. -#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. -#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. -#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is. -#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // -#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. -#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int' #if __has_warning("-Wzero-as-null-pointer-constant") -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") -#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif #elif defined(__GNUC__) // We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 65d24bbd..e173058c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -98,6 +98,9 @@ Index of this file: #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier #endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 750bf9f6..71d98327 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -57,21 +57,24 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) -#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. -#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. -#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is. -#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #if __has_warning("-Wzero-as-null-pointer-constant") -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wcomma") -#pragma clang diagnostic ignored "-Wcomma" // warning : possible misuse of comma operator here // +#pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here #endif #if __has_warning("-Wreserved-id-macro") -#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier #endif #if __has_warning("-Wdouble-promotion") -#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind @@ -108,7 +111,7 @@ namespace IMGUI_STB_NAMESPACE #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" -#pragma clang diagnostic ignored "-Wcast-qual" // warning : cast from 'const xxxx *' to 'xxx *' drops const qualifier // +#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier #endif #if defined(__GNUC__) diff --git a/imgui_internal.h b/imgui_internal.h index 4f101920..ddca9fff 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -66,6 +66,9 @@ Index of this file: #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" #endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#endif #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0ce3de71..12a8c08f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -58,18 +58,24 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) -#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. -#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. -#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. -#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #if __has_warning("-Wzero-as-null-pointer-constant") -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") -#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#endif +#if __has_warning("-Wenum-enum-conversion") +#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') #endif #if __has_warning("-Wdeprecated-enum-enum-conversion") -#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#endif +#if __has_warning("-Wimplicit-int-float-conversion") +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind From 8ead38c10067954ff51076d0b59ad3b12c790240 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 18 Jun 2020 16:33:23 +0200 Subject: [PATCH 099/959] Clang: Reduce uses of __has_warning for overall sanity, as compilers are hostile to software targetting multiple compiler version. --- imgui.cpp | 11 ++++------- imgui_demo.cpp | 45 ++++++++++++++++++++++----------------------- imgui_draw.cpp | 14 ++++---------- imgui_internal.h | 16 +++++++--------- imgui_widgets.cpp | 14 ++++---------- 5 files changed, 41 insertions(+), 59 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 648c265e..f4a1c205 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -864,7 +864,10 @@ CODE // Clang/GCC warnings with -Weverything #if defined(__clang__) -#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. @@ -873,15 +876,9 @@ CODE #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int' -#if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 -#endif -#if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. -#endif -#if __has_warning("-Wimplicit-int-float-conversion") #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#endif #elif defined(__GNUC__) // We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e173058c..33d069dc 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -79,35 +79,34 @@ Index of this file: #include // intptr_t #endif +// Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif + +// Clang/GCC warnings with -Weverything #if defined(__clang__) -#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. -#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code) -#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type -#pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal -#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. -#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. -#if __has_warning("-Wzero-as-null-pointer-constant") -#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 -#endif -#if __has_warning("-Wdouble-promotion") -#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. -#endif -#if __has_warning("-Wreserved-id-macro") -#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier -#endif -#if __has_warning("-Wimplicit-int-float-conversion") -#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! #endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type +#pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #elif defined(__GNUC__) -#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size -#pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure) -#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function -#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value -#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub. #endif // Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 71d98327..0e7c294e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -57,25 +57,19 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness -#if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 -#endif -#if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here -#endif -#if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier -#endif -#if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. -#endif -#if __has_warning("-Wimplicit-int-float-conversion") #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used diff --git a/imgui_internal.h b/imgui_internal.h index ddca9fff..9e0fe99e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -57,18 +57,16 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h -#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h #pragma clang diagnostic ignored "-Wold-style-cast" -#if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" -#endif -#if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" -#endif -#if __has_warning("-Wimplicit-int-float-conversion") -#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#endif +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 12a8c08f..70ab9e3d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -58,25 +58,19 @@ Index of this file: // Clang/GCC warnings with -Weverything #if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness -#if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 -#endif -#if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. -#endif -#if __has_warning("-Wenum-enum-conversion") #pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') -#endif -#if __has_warning("-Wdeprecated-enum-enum-conversion") #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated -#endif -#if __has_warning("-Wimplicit-int-float-conversion") #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision -#endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked From 9c2a36f5732d8031a410bf656a0f41e9e3775b13 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 10:08:05 +0200 Subject: [PATCH 100/959] Internals: clarified the code for ClampWindowRect(). As a side-effect, some rounding error may be neutralized however this isn't the intent. (#3309) --- imgui.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f4a1c205..9bb5f9d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5239,11 +5239,13 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s return ret_auto_fit; } -static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding) +static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& viewport_rect, const ImVec2& padding) { ImGuiContext& g = *GImGui; - ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size; - window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping); + ImVec2 size_for_clamping = window->Size; + if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) + size_for_clamping.y = window->TitleBarHeight(); + window->Pos = ImClamp(window->Pos, viewport_rect.Min + padding - size_for_clamping, viewport_rect.Max - padding); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) From 99f68d79581deef58d1edc5d07a92ad7806cabd6 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 10:56:54 +0200 Subject: [PATCH 101/959] Docs: Added FAQ entries removed old one which is misleading today. Misc tweaks. --- docs/FAQ.md | 20 +++++++++++++++----- docs/README.md | 4 ++-- docs/TODO.txt | 3 ++- examples/README.txt | 41 +++++++++++++++++++++++------------------ imgui.cpp | 11 +++++++---- 5 files changed, 49 insertions(+), 30 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 1401486a..55e7ebeb 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -15,12 +15,13 @@ or view this file with any Markdown viewer. | [What is this library called?](#q-what-is-this-library-called) | | [Which version should I get?](#q-which-version-should-i-get) | | **Q&A: Integration** | +| **[How to get started?](#q-how-to-get-started)** | | **[How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application?](#q-how-can-i-tell-whether-to-dispatch-mousekeyboard-to-dear-imgui-or-to-my-application)** | | [How can I enable keyboard or gamepad controls?](#q-how-can-i-enable-keyboard-or-gamepad-controls) | | [How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)](#q-how-can-i-use-this-on-a-machine-without-mouse-keyboard-or-screen-input-share-remote-display) | -| [I integrated Dear ImGui in my engine and the text or lines are blurry..](#q-i-integrated-dear-imgui-in-my-engine-and-the-text-or-lines-are-blurry) | +| [I integrated Dear ImGui in my engine and little squares are showing instead of text..](#q-i-integrated-dear-imgui-in-my-engine-and-little-squares-are-showing-instead-of-text) | | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | -| [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) +| [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | **Q&A: Usage** | | **[Why are multiple widgets reacting when I interact with a single one?
How can I have multiple widgets with the same label or with an empty label?](#q-why-are-multiple-widgets-reacting-when-i-interact-with-a-single-one-q-how-can-i-have-multiple-widgets-with-the-same-label-or-with-an-empty-label)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| @@ -88,6 +89,15 @@ You may merge in the [tables](https://github.com/ocornut/imgui/tree/tables) bran # Q&A: Integration +### Q: How to get started? + +Read `PROGRAMMER GUIDE` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp). +Read [examples/README.txt](https://github.com/ocornut/imgui/tree/master/examples/README.txt). + +##### [Return to Index](#index) + +--- + ### Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application? You can read the `io.WantCaptureMouse`, `io.WantCaptureKeyboard` and `io.WantTextInput` flags from the ImGuiIO structure. @@ -139,9 +149,9 @@ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-lik --- -### Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. -In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). -Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. +### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. +This usually means that: your font texture wasn't uploaded into GPU, or your shader or other rendering state are not reading from the right texture (e.g. texture wasn't bound). +If this happens using the standard back-ends it is probably that the texture failed to upload, which could happens if for some reason your texture is too big. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). ##### [Return to Index](#index) diff --git a/docs/README.md b/docs/README.md index df32b9c2..a0ca6483 100644 --- a/docs/README.md +++ b/docs/README.md @@ -96,7 +96,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas ![screenshot demo](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png) -You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: +You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: - [imgui-demo-binaries-20190715.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows binaries, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.org/faq)). @@ -158,7 +158,7 @@ Private support is available for paying business customers (E-mail: _contact @ d **Which version should I get?** -I occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. +We occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. You may also peak at the [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features in the `docking` branch. Many projects are using this branch and it is kept in sync with master regularly. diff --git a/docs/TODO.txt b/docs/TODO.txt index 213d1d35..71969690 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -382,6 +382,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: window minimize, maximize (#583) - examples: provide a zero frame-rate/idle example. - examples: dx11/dx12: try to use new swapchain blit models (#2970) + - backends: report it better when not able to create texture? - backends: apple: example_apple should be using modern GL3. - backends: glfw: could go idle when minimized? if (glfwGetWindowAttrib(window, GLFW_ICONIFIED)) { glfwWaitEvents(); continue; } // issue: DeltaTime will be super high on resume, perhaps provide a way to let impl know (#440) - backends: opengl: rename imgui_impl_opengl2 to impl_opengl_legacy and imgui_impl_opengl3 to imgui_impl_opengl? (#1900) @@ -392,7 +393,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - backends: bgfx: https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - backends: mscriptem: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) - - optimization: replace vsnprintf with stb_printf? or enable the defines/infrastructure to allow it (#1038) + - optimization: replace vsnprintf with stb_printf? using IMGUI_USE_STB_SPRINTF.(#1038) - optimization: add clipping for multi-component widgets (SliderFloatX, ColorEditX, etc.). one problem is that nav branch can't easily clip parent group when there is a move request. - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) - optimization: fully covered window (covered by another with non-translucent bg + WindowRounding worth of padding) may want to clip rendering. diff --git a/examples/README.txt b/examples/README.txt index 3356b546..0933a6ba 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -32,29 +32,34 @@ You can find binaries of some of those example applications at: --------------------------------------- - MISC COMMENTS AND SUGGESTIONS + GETTING STARTED --------------------------------------- - - Read FAQ at http://dearimgui.org/faq - - Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. Please read the comments and instruction at the top of each file. + Please read FAQ at http://www.dearimgui.org/faq - - If you are using of the backend provided here, so you can copy the imgui_impl_xxx.cpp/h files + - If you are using of the backend provided here, you can add the imgui_impl_xxx.cpp/h files to your project and use them unmodified. Each imgui_impl_xxxx.cpp comes with its own individual - ChangeLog at the top of the .cpp files, so if you want to update them later it will be easier to + Changelog at the top of the .cpp files, so if you want to update them later it will be easier to catch up with what changed. - - Dear ImGui has 0 to 1 frame of lag for most behaviors, at 60 FPS your experience should be pleasant. - However, consider that OS mouse cursors are typically drawn through a specific hardware accelerated path - and will feel smoother than common GPU rendered contents (including Dear ImGui windows). - You may experiment with the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor itself, - to visualize the lag between a hardware cursor and a software cursor. However, rendering a mouse cursor - at 60 FPS will feel slow. It might be beneficial to the user experience to switch to a software rendered - cursor only when an interactive drag is in progress. - Note that some setup or GPU drivers are likely to be causing extra lag depending on their settings. - If you feel that dragging windows feels laggy and you are not sure who to blame: try to build an - application drawing a shape directly under the mouse cursor. + - Dear ImGui has no particular extra lag for most behaviors, e.g. the value of 'io.MousePos' provided in + NewFrame() will result at the time of EndFrame()/Render() in a moved windows rendered following that mouse + movement. At 60 FPS your experience should be pleasant. + However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated + path and will feel smoother than the majority of contents rendererd via regular graphics API (including, + but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane as + the mouse, that disconnect may be jarring to particularly sensitive users. + You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor + using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a + regularly rendered software cursor. + However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at + all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ + when an interactive drag is in progress. + Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. + If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple + drawing a flat 2D shape directly under the mouse cursor. --------------------------------------- @@ -155,12 +160,12 @@ Those will allow you to create portable applications and will solve and abstract Building: Unfortunately in 2020 it is still tedious to create and maintain portable build files using external libraries (the kind we're using here to create a window and render 3D triangles) without relying on - third party software. For most examples here I choose to provide: + third party software. For most examples here we choose to provide: - Makefiles for Linux/OSX - Batch files for Visual Studio 2008+ - - A .sln project file for Visual Studio 2010+ + - A .sln project file for Visual Studio 2012+ - Xcode project files for the Apple examples - Please let me know if they don't work with your setup! + Please let us know if they don't work with your setup! You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those directly with a command-line compiler. diff --git a/imgui.cpp b/imgui.cpp index 9bb5f9d2..2df5ce1e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -18,7 +18,7 @@ // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // See LICENSE.txt for copyright and licensing details (standard MIT License). -// This library is free but I need your support to sustain development and maintenance. +// This library is free but needs your support to sustain development and maintenance. // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org". // Individuals: you can support continued development via donations. See docs/README or web page. @@ -169,7 +169,7 @@ CODE --------------------------------------------------------------- - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. - In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder. - - Add the Dear ImGui source files to your projects or using your preferred build system. + - Add the Dear ImGui source files + selected back-end source files to your projects or using your preferred build system. It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL). - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. @@ -622,18 +622,21 @@ CODE Q: What is this library called? Q: Which version should I get? >> This library is called "Dear ImGui", please don't call it "ImGui" :) - >> See https://www.dearimgui.org/faq + >> See https://www.dearimgui.org/faq for details. Q&A: Integration ================ + Q: How to get started? + A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt. + Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application? A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! >> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this. Q. How can I enable keyboard controls? Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) - Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. + Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. >> See https://www.dearimgui.org/faq From 1a1dcea1a02c4e1542b6e2619111fe2d20e22383 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 20 Jun 2020 22:03:50 +0200 Subject: [PATCH 102/959] Internals: Initialize drawlist earlier in Begin() to facilitate detecting accidental draw earlier than legal. (#3311) --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 2df5ce1e..c9146e13 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5606,6 +5606,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->HasCloseButton = (p_open != NULL); window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->IDStack.resize(1); + window->DrawList->_ResetForNewFrame(); // Restore buffer capacity when woken from a compacted state, to avoid if (window->MemoryCompacted) @@ -5883,7 +5884,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // DRAWING // Setup draw list and outer clipping rectangle - window->DrawList->_ResetForNewFrame(); + IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); From 76e40fe5d1059733ddcdd88236ee5c5743ed64b7 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 20 Jun 2020 22:06:44 +0200 Subject: [PATCH 103/959] Docking: Fix misuse of PushClipRect in UpdateWindowManualResize(). (#3311) --- imgui.cpp | 5 ++--- imgui.h | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ff6722af..08c86496 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5502,9 +5502,10 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // This is however not the case with current back-ends under Win32, but a custom borderless window implementation would benefit from it. // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). + // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration); if (clip_with_viewport_rect) - PushClipRect(window->Viewport->Pos, window->Viewport->Pos + window->Viewport->Size, true); // Won't incur a draw command as we are not drawing here. + window->ClipRect = window->Viewport->GetMainRect(); // Resize grips and borders are on layer 1 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; @@ -5568,8 +5569,6 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s } } PopID(); - if (clip_with_viewport_rect) - PopClipRect(); // Restore nav layer window->DC.NavLayerCurrent = ImGuiNavLayer_Main; diff --git a/imgui.h b/imgui.h index 980fbf16..c283070f 100644 --- a/imgui.h +++ b/imgui.h @@ -1697,7 +1697,7 @@ struct ImGuiSizeCallbackData // Important: the content of this class is still highly WIP and likely to change and be refactored // before we stabilize Docking features. Please be mindful if using this. // Provide hints: -// - To the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +// - To the platform back-end via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) // - To the platform back-end for OS level parent/child relationships of viewport. // - To the docking system for various options and filtering. struct ImGuiWindowClass @@ -1707,7 +1707,7 @@ struct ImGuiWindowClass ImGuiViewportFlags ViewportFlagsOverrideSet; // Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. ImGuiViewportFlags ViewportFlagsOverrideClear; // Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) - ImGuiDockNodeFlags DockNodeFlagsOverrideClear; // [EXPERIMENTAL] + ImGuiDockNodeFlags DockNodeFlagsOverrideClear; // [EXPERIMENTAL] bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. From e0ec69d84be361611a4fdd5e853f25a04a59c8b0 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 15:47:07 +0200 Subject: [PATCH 104/959] Internals: Added ImageButtonEx() helper to temporarily bypass ID issues (#2464, #1390) --- imgui_internal.h | 1 + imgui_widgets.cpp | 45 ++++++++++++++++++++++++++------------------- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 9e0fe99e..a00a3418 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1958,6 +1958,7 @@ namespace ImGui IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); IMGUI_API void Scrollbar(ImGuiAxis axis); IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float avail_v, float contents_v, ImDrawCornerFlags rounding_corners); + IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col); IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowResizeID(ImGuiWindow* window, int n); // 0..3: corners, 4..7: borders diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 70ab9e3d..bda694a5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -981,28 +981,16 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& } } -// frame_padding < 0: uses FramePadding from style (default) -// frame_padding = 0: no framing -// frame_padding > 0: set framing size -// The color used are the button colors. -bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +// ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390) +// We provide this internal helper to write your own variant while we figure out how to redesign the public ImageButton() API. +bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col) { + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; - - // Default to using texture ID as ID. User can still push string/integer prefixes. - // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. - PushID((void*)(intptr_t)user_texture_id); - const ImGuiID id = window->GetID("#image"); - PopID(); - - const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2); - const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, id)) return false; @@ -1013,14 +1001,33 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); - RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); + 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(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); - window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); + window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col)); + window->DrawList->AddImage(texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); return pressed; } +// frame_padding < 0: uses FramePadding from style (default) +// frame_padding = 0: no framing +// frame_padding > 0: set framing size +bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + // Default to using texture ID as ID. User can still push string/integer prefixes. + PushID((void*)(intptr_t)user_texture_id); + const ImGuiID id = window->GetID("#image"); + PopID(); + + const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : g.Style.FramePadding; + return ImageButtonEx(id, user_texture_id, size, uv0, uv1, padding, bg_col, tint_col); +} + bool ImGui::Checkbox(const char* label, bool* v) { ImGuiWindow* window = GetCurrentWindow(); From 68389200c4aaaa0e723f6d8e11064ca68c3b061d Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 16:12:19 +0200 Subject: [PATCH 105/959] Internals: Comments about CalcWrapWidthForPos() (#778) --- imgui.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index c9146e13..942b5122 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3255,11 +3255,21 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) if (wrap_pos_x < 0.0f) return 0.0f; - ImGuiWindow* window = GImGui->CurrentWindow; + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; if (wrap_pos_x == 0.0f) + { + // We could decide to setup a default wrapping max point for auto-resizing windows, + // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? + //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) + // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x); + //else wrap_pos_x = window->WorkRect.Max.x; + } else if (wrap_pos_x > 0.0f) + { wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + } return ImMax(wrap_pos_x - pos.x, 1.0f); } From b83a1f3b002a630ba4d3e8d15c895fde2a016205 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 17:52:13 +0200 Subject: [PATCH 106/959] BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. (#915, #3091) --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 10 ++++++---- imgui_demo.cpp | 4 ++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b479a333..00dbbceb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -58,6 +58,10 @@ Other Changes: would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) - Popups: Clarified some of the comments and function prototypes. +- Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will + not always be auto-centered. Note that modals are more similar to regular windows than they are to + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] diff --git a/imgui.cpp b/imgui.cpp index 942b5122..bb5d8a91 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5748,7 +5748,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (window_just_activated_by_user) { window->AutoPosLastDirection = ImGuiDir_None; - if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos() window->Pos = g.BeginPopupStack.back().OpenPopupPos; } @@ -7807,6 +7807,7 @@ void ImGui::CloseCurrentPopup() window->DC.NavHideHighlightOneFrame = true; } +// Attention! BeginPopup() adds default flags which BeginPopupEx()! bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; @@ -7855,12 +7856,13 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla return false; } - // Center modal windows by default + // Center modal windows by default for increased visibility + // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) - SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); - flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings; + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse; const bool is_open = Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 33d069dc..0c9b6e23 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2865,6 +2865,10 @@ static void ShowDemoWindowPopups() if (ImGui::Button("Delete..")) ImGui::OpenPopup("Delete?"); + // Always center this window when appearing + ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); From a616ff5d4a7bb72ccbe9906d3220d0938c1915cf Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 17:52:13 +0200 Subject: [PATCH 107/959] BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. (#915, #3091) # Conflicts: # imgui.cpp --- docs/CHANGELOG.txt | 4 ++++ imgui.cpp | 10 ++++++---- imgui_demo.cpp | 4 ++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ead04e53..11f0c052 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -127,6 +127,10 @@ Other Changes: would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) - Popups: Clarified some of the comments and function prototypes. +- Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will + not always be auto-centered. Note that modals are more similar to regular windows than they are to + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] diff --git a/imgui.cpp b/imgui.cpp index 08c86496..4a57b478 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6191,7 +6191,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (window_just_activated_by_user) { window->AutoPosLastDirection = ImGuiDir_None; - if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos() window->Pos = g.BeginPopupStack.back().OpenPopupPos; } @@ -8547,6 +8547,7 @@ void ImGui::CloseCurrentPopup() window->DC.NavHideHighlightOneFrame = true; } +// Attention! BeginPopup() adds default flags which BeginPopupEx()! bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; @@ -8595,15 +8596,16 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla return false; } - // Center modal windows by default + // Center modal windows by default for increased visibility + // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) { ImGuiViewportP* viewport = window->WasActive ? window->Viewport : (ImGuiViewportP*)GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport? - SetNextWindowPos(viewport->GetMainRect().GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + SetNextWindowPos(viewport->GetMainRect().GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); } - flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking; + flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; const bool is_open = Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 42a6320d..2202cbf3 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2922,6 +2922,10 @@ static void ShowDemoWindowPopups() if (ImGui::Button("Delete..")) ImGui::OpenPopup("Delete?"); + // Always center this window when appearing + ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); From e1d7e1471702ed0f50cf11bccb3877df05f45134 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 18:31:44 +0200 Subject: [PATCH 108/959] Viewports: used main viewport for centering (wip), clarified the meaning of how ImGuiPlatformMonitor WorkPos/WorkSize should be set if unknown, added asserts. --- imgui.cpp | 5 ++--- imgui.h | 5 +++-- imgui_demo.cpp | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4a57b478..9e19f946 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7590,9 +7590,8 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) { ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n]; - IM_UNUSED(mon); - IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor bounds not setup properly."); - IM_ASSERT(mon.WorkSize.x > 0.0f && mon.WorkSize.y > 0.0f && "Monitor bounds not setup properly. If you don't have work area information, just copy Min/Max into them."); + IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly."); + IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them."); IM_ASSERT(mon.DpiScale != 0.0f); } } diff --git a/imgui.h b/imgui.h index c283070f..dc37773c 100644 --- a/imgui.h +++ b/imgui.h @@ -2570,7 +2570,7 @@ struct ImGuiPlatformIO struct ImGuiPlatformMonitor { ImVec2 MainPos, MainSize; // Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) - ImVec2 WorkPos, WorkSize; // (Optional) Coordinates without task bars / side bars / menu bars. imgui uses this to avoid positioning popups/tooltips inside this region. + ImVec2 WorkPos, WorkSize; // Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. float DpiScale; // 1.0f = 96 DPI ImGuiPlatformMonitor() { MainPos = MainSize = WorkPos = WorkSize = ImVec2(0, 0); DpiScale = 1.0f; } }; @@ -2621,7 +2621,8 @@ struct ImGuiViewport ImGuiViewport() { ID = 0; Flags = 0; DpiScale = 0.0f; DrawData = NULL; ParentViewportId = 0; RendererUserData = PlatformUserData = PlatformHandle = PlatformHandleRaw = NULL; PlatformRequestMove = PlatformRequestResize = PlatformRequestClose = false; } ~ImGuiViewport() { IM_ASSERT(PlatformUserData == NULL && RendererUserData == NULL); } - // Access work-area rectangle + // Access work-area rectangle with GetWorkXXX functions (see comments above) + ImVec2 GetCenter() { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); } ImVec2 GetWorkPos() { return ImVec2(Pos.x + WorkOffsetMin.x, Pos.y + WorkOffsetMin.y); } ImVec2 GetWorkSize() { return ImVec2(Size.x - WorkOffsetMin.x + WorkOffsetMax.x, Size.y - WorkOffsetMin.y + WorkOffsetMax.y); } // This not clamped }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2202cbf3..c6dec7a2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2923,8 +2923,8 @@ static void ShowDemoWindowPopups() ImGui::OpenPopup("Delete?"); // Always center this window when appearing - ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f); - ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGuiViewport* viewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { From 7538bbabb62da3105b62ca596827407f638c2e27 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 19:01:40 +0200 Subject: [PATCH 109/959] Demo: Commented out ideas on another way to center a window. --- imgui_demo.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c6dec7a2..b43f5981 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2923,8 +2923,11 @@ static void ShowDemoWindowPopups() ImGui::OpenPopup("Delete?"); // Always center this window when appearing - ImGuiViewport* viewport = ImGui::GetMainViewport(); - ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + //ImVec2 parent_pos = ImGui::GetWindowPos(); + //ImVec2 parent_size = ImGui::GetWindowSize(); + //ImVec2 center(parent_pos.x + parent_size.x * 0.5f, parent_pos.y + parent_size.y * 0.5f); + ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { From 1c35750ee0fdf9b631429e6d9e57928f57ba705e Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 23 Jun 2020 19:45:31 +0200 Subject: [PATCH 110/959] Added ImGuiCond_None for consistency and for generated bindings needing this for enums mapping. --- imgui.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index eb2a611b..cedc8618 100644 --- a/imgui.h +++ b/imgui.h @@ -1277,7 +1277,8 @@ enum ImGuiMouseCursor_ // Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. enum ImGuiCond_ { - ImGuiCond_Always = 1 << 0, // Set the variable + ImGuiCond_None = 0, // No condition (always set the variable), same as _Always + ImGuiCond_Always = 1 << 0, // No condition (always set the variable) ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call will succeed) ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) From 5acf6d861ae075e12b03c47fea8eb26e4c48bbeb Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 15:17:56 +0200 Subject: [PATCH 111/959] Popups: Added ImGuiPopupFlags type, ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(). # Conflicts: # docs/CHANGELOG.txt --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 64 +++++++++++++++++++++++++++------------------- imgui.h | 16 +++++++++++- imgui_internal.h | 4 +-- imgui_widgets.cpp | 6 ++--- 5 files changed, 59 insertions(+), 34 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 00dbbceb..8882f0af 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,9 @@ Other Changes: Set to an intermediary value to toggle behavior based on width (same as Firefox). - Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] +- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), + allowing to check if any popup is open at the current level, if a given popup is open at any popup + level, if any popup is open at all. - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) - Popups: Fix BeginPopupContextVoid() when clicking over the area made unavailable by a modal. (#1636) diff --git a/imgui.cpp b/imgui.cpp index bb5d8a91..f2e77c79 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3468,7 +3468,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() // Handle the edge case of a popup being closed while clicking in its empty space. // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. ImGuiWindow* root_window = g.HoveredRootWindow; - const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpenAtAnyLevel(root_window->PopupId); + const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel); if (root_window != NULL && !is_closed_popup) { @@ -7619,35 +7619,45 @@ void ImGui::SetTooltip(const char* fmt, ...) // [SECTION] POPUPS //----------------------------------------------------------------------------- -// Return true if the popup is open at the current BeginPopup() level of the popup stack -bool ImGui::IsPopupOpen(ImGuiID id) +// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel +bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; - return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; -} - -// Return true if the popup is open at the current BeginPopup() level of the popup stack -bool ImGui::IsPopupOpen(const char* str_id) -{ - ImGuiContext& g = *GImGui; - return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); -} - -bool ImGui::IsPopupOpenAtAnyLevel(ImGuiID id) -{ - ImGuiContext& g = *GImGui; - for (int n = 0; n < g.OpenPopupStack.Size; n++) - if (g.OpenPopupStack[n].PopupId == id) - return true; - return false; + if (popup_flags & ImGuiPopupFlags_AnyPopupId) + { + // Return true if any popup is open at the current BeginPopup() level of the popup stack + // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level. + IM_ASSERT(id == 0); + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + return g.OpenPopupStack.Size > 0; + else + return g.OpenPopupStack.Size > g.BeginPopupStack.Size; + } + else + { + if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) + { + // Return true if the popup is open anywhere in the popup stack + for (int n = 0; n < g.OpenPopupStack.Size; n++) + if (g.OpenPopupStack[n].PopupId == id) + return true; + return false; + } + else + { + // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query) + return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; + } + } } -// Return true if any popup is open at the current BeginPopup() level of the popup stack -// This may be used to e.g. test for another popups already opened in the same frame to handle popups priorities at the same level. -bool ImGui::IsAnyPopupOpen() +bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; - return g.OpenPopupStack.Size > g.BeginPopupStack.Size; + ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id); + if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0) + IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally + return IsPopupOpen(id, popup_flags); } ImGuiWindow* ImGui::GetTopMostPopupModal() @@ -7674,7 +7684,7 @@ void ImGui::OpenPopupEx(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; - int current_stack_size = g.BeginPopupStack.Size; + const int current_stack_size = g.BeginPopupStack.Size; ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; @@ -7811,7 +7821,7 @@ void ImGui::CloseCurrentPopup() bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; - if (!IsPopupOpen(id)) + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; @@ -7850,7 +7860,7 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(name); - if (!IsPopupOpen(id)) + if (!IsPopupOpen(id, ImGuiPopupFlags_None)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; diff --git a/imgui.h b/imgui.h index cedc8618..63bfc270 100644 --- a/imgui.h +++ b/imgui.h @@ -161,6 +161,7 @@ typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: f typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super) +typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() @@ -612,13 +613,17 @@ namespace ImGui IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. - IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current BeginPopup() level of the popup stack // Popups: open+begin combined functions helpers // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. // - They are convenient to easily create context menus, hence the name. IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1, bool also_over_items = true); // open+begin popup when clicked on current window. IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked in void (where there are no windows). + // Popups: test function + // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. + // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. + IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. // Columns // - You can also use SameLine(pos_x) to mimic simplified columns. @@ -865,6 +870,15 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog }; +// Flags for IsPopupOpen() function. +enum ImGuiPopupFlags_ +{ + ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) + ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel +}; + // Flags for ImGui::Selectable() enum ImGuiSelectableFlags_ { diff --git a/imgui_internal.h b/imgui_internal.h index a00a3418..d0c8bbcb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1853,9 +1853,7 @@ namespace ImGui IMGUI_API void OpenPopupEx(ImGuiID id); IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); - IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id at the current BeginPopup() level of the popup stack (this doesn't scan the whole popup stack!) - IMGUI_API bool IsPopupOpenAtAnyLevel(ImGuiID id); - IMGUI_API bool IsAnyPopupOpen(); // Return true if any popup is open at the current BeginPopup() level of the popup stack + IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags); IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bda694a5..79144ee9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1492,7 +1492,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF bool hovered, held; bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); - bool popup_open = IsPopupOpen(id); + bool popup_open = IsPopupOpen(id, ImGuiPopupFlags_None); const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); const float value_x2 = ImMax(frame_bb.Min.x, frame_bb.Max.x - arrow_size); @@ -6288,7 +6288,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - bool menu_is_open = IsPopupOpen(id); + bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None); // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus; @@ -6414,7 +6414,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true; - if (want_close && IsPopupOpen(id)) + if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None)) ClosePopupToLevel(g.BeginPopupStack.Size, true); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0)); From fed80b95375f716536ceaa3c5e8b21c96e150bff Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 15:26:02 +0200 Subject: [PATCH 112/959] Popups: Changed 'int mouse_buttons' to ImGuiPopupFlags. Added ImGuiPopupFlags_NoOpenOverExistingPopup, ImGuiPopupFlags_NoOpenOverItems. Refactored signature of BeginPopupContextWindow(). --- docs/CHANGELOG.txt | 9 +++++++++ imgui.cpp | 34 ++++++++++++++++++++++------------ imgui.h | 31 +++++++++++++++++++++++-------- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 5 files changed, 56 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8882f0af..5b33b11d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,8 @@ Breaking Changes: - Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). +- Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor + of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - Removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. Other Changes: @@ -54,6 +56,13 @@ Other Changes: Set to an intermediary value to toggle behavior based on width (same as Firefox). - Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] +- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new + ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward + compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. +- Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions + to first test for the presence of another popup at the same level. +- Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing + for !IsAnyItemHovered() prior to doing an OpenPopup. - Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. diff --git a/imgui.cpp b/imgui.cpp index f2e77c79..07c5ea4a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). @@ -7670,21 +7671,26 @@ ImGuiWindow* ImGui::GetTopMostPopupModal() return NULL; } -void ImGui::OpenPopup(const char* str_id) +void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; - OpenPopupEx(g.CurrentWindow->GetID(str_id)); + OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags); } // Mark popup as open (toggle toward open state). // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) -void ImGui::OpenPopupEx(ImGuiID id) +void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; const int current_stack_size = g.BeginPopupStack.Size; + + if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup) + if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId)) + return; + ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; @@ -7903,14 +7909,15 @@ void ImGui::EndPopup() g.WithinEndChild = false; } -bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) - OpenPopupEx(id); + OpenPopupEx(id, popup_flags); return true; } return false; @@ -7921,39 +7928,42 @@ bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiMouseButton mouse_butt // - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // - This is essentially the same as calling OpenPopupContextItem() + BeginPopup() but written to avoid // computing the ID twice because BeginPopupContextXXX functions are called very frequently. -bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; if (window->SkipItems) return false; ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) - OpenPopupEx(id); + OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } -bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mouse_button, bool also_over_items) +bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "window_context"; ImGuiID id = window->GetID(str_id); + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) - if (also_over_items || !IsAnyItemHovered()) - OpenPopupEx(id); + if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) + OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } -bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiMouseButton mouse_button) +bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "void_context"; ImGuiID id = window->GetID(str_id); + int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) if (GetTopMostPopupModal() == NULL) - OpenPopupEx(id); + OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } diff --git a/imgui.h b/imgui.h index 63bfc270..c443ca75 100644 --- a/imgui.h +++ b/imgui.h @@ -606,19 +606,22 @@ namespace ImGui IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! // Popups: open/close functions - // - OpenPopup(): set popup state to open. + // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). - IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). - IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). + IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). + IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. // Popups: open+begin combined functions helpers // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. // - They are convenient to easily create context menus, hence the name. - IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! - IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1, bool also_over_items = true); // open+begin popup when clicked on current window. - IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiMouseButton mouse_b = 1); // open+begin popup when clicked in void (where there are no windows). + // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. + // - We exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter. Passing a mouse button to ImGuiPopupFlags is guaranteed to be legal. + IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). // Popups: test function // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. @@ -870,10 +873,21 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog }; -// Flags for IsPopupOpen() function. +// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat +// small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. +// It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. +// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. enum ImGuiPopupFlags_ { ImGuiPopupFlags_None = 0, + ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranted to always be == 0 (same as ImGuiMouseButton_Left) + ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranted to always be == 1 (same as ImGuiMouseButton_Right) + ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranted to always be == 2 (same as ImGuiMouseButton_Middle) + ImGuiPopupFlags_MouseButtonMask_ = 0x1F, + ImGuiPopupFlags_MouseButtonDefault_ = 1, + ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + ImGuiPopupFlags_NoOpenOverItems = 1 << 6, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space ImGuiPopupFlags_AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. ImGuiPopupFlags_AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel @@ -1656,7 +1670,8 @@ struct ImGuiPayload namespace ImGui { // OBSOLETED in 1.77 (from June 2020) - static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mouse_button = 1) { return OpenPopupContextItem(str_id, mouse_button); } + static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupContextItem(str_id, mb); } // Passing a mouse button to ImGuiPopupFlags is legal + static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } // OBSOLETED in 1.72 (from July 2019) static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.71 (from June 2019) diff --git a/imgui_internal.h b/imgui_internal.h index d0c8bbcb..9ec0760d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1850,7 +1850,7 @@ namespace ImGui // Popups, Modals, Tooltips IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags); - IMGUI_API void OpenPopupEx(ImGuiID id); + IMGUI_API void OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None); IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 79144ee9..ec0bcc74 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1517,7 +1517,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF { if (window->DC.NavLayerCurrent == 0) window->NavLastIds[0] = id; - OpenPopupEx(id); + OpenPopupEx(id, ImGuiPopupFlags_None); popup_open = true; } From 45a7cf47ab12c7fe9f239a213b279e1803041ca6 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Jun 2020 16:44:06 +0200 Subject: [PATCH 113/959] FAQ update, removed redundant block in imgui.cpp --- docs/CHANGELOG.txt | 5 +- docs/FAQ.md | 13 +++-- imgui.cpp | 128 +++------------------------------------------ 3 files changed, 19 insertions(+), 127 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5b33b11d..35265e30 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,12 +36,13 @@ HOW TO UPDATE? Breaking Changes: -- Removed unncessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please +- Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. -- Removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. + Kept inline redirection function (will obsolete). +- Removed obsoleted CalcItemRectClosestPoint() entry point (has been asserting since December 2017). Other Changes: diff --git a/docs/FAQ.md b/docs/FAQ.md index 55e7ebeb..adce4d40 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -23,7 +23,7 @@ or view this file with any Markdown viewer. | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | **Q&A: Usage** | -| **[Why are multiple widgets reacting when I interact with a single one?
How can I have multiple widgets with the same label or with an empty label?](#q-why-are-multiple-widgets-reacting-when-i-interact-with-a-single-one-q-how-can-i-have-multiple-widgets-with-the-same-label-or-with-an-empty-label)** | +| **[How can I have widgets with an empty label?
How can I have multiple widgets with the same label?
Why are multiple widgets reacting when I interact with one?](#q-how-can-i-have-widgets-with-an-empty-label)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| | [How can I use my own math types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-math-types-instead-of-imvec2imvec4) | | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | @@ -173,7 +173,9 @@ Refer to rendering back-ends in the [examples/](https://github.com/ocornut/imgui # Q&A: Usage -### Q: Why are multiple widgets reacting when I interact with a single one?
Q: How can I have multiple widgets with the same label or with an empty label? +### Q: How can I have widgets with an empty label? +### Q: How can I have multiple widgets with the same label? +### Q: Why are multiple widgets reacting when I interact with one? A primer on labels and the ID Stack... @@ -295,11 +297,12 @@ if (TreeNode("node")) // <-- this function call will do a PushID() for you (unl TreePop(); } ``` -- When working with trees, ID are used to preserve the open/close state of each tree node. + +When working with trees, ID are used to preserve the open/close state of each tree node. Depending on your use cases you may want to use strings, indices or pointers as ID. -e.g. when following a single pointer that may change over time, using a static string as ID +- e.g. when following a single pointer that may change over time, using a static string as ID will preserve your node open/closed state when the targeted object change. -e.g. when displaying a list of objects, using indices or pointers as ID will preserve the +- e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. See what makes more sense in your situation! ##### [Return to Index](#index) diff --git a/imgui.cpp b/imgui.cpp index 07c5ea4a..a4ec7178 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -601,7 +601,10 @@ CODE FREQUENTLY ASKED QUESTIONS (FAQ) ================================ - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer) + Read all answers online: + https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) + Read all answers locally (with a text editor or ideally a Markdown viewer): + docs/FAQ.md Some answers are copied down here to facilitate searching in code. Q&A: Basics @@ -640,130 +643,15 @@ CODE Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. ->> See https://www.dearimgui.org/faq + >> See https://www.dearimgui.org/faq Q&A: Usage ---------- - Q: Why are multiple widgets reacting when I interact with a single one? - Q: How can I have multiple widgets with the same label or with an empty label? - A: A primer on labels and the ID Stack... - - Dear ImGui internally need to uniquely identify UI elements. - Elements that are typically not clickable (such as calls to the Text functions) don't need an ID. - Interactive widgets (such as calls to Button buttons) need a unique ID. - Unique ID are used internally to track active widgets and occasionally associate state to widgets. - Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element. - - - Unique ID are often derived from a string label: - - Button("OK"); // Label = "OK", ID = hash of (..., "OK") - Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel") - - - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having - two buttons labeled "OK" in different windows or different tree locations is fine. - We used "..." above to signify whatever was already pushed to the ID stack previously: - - Begin("MyWindow"); - Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK") - End(); - Begin("MyOtherWindow"); - Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK") - End(); - - - If you have a same ID twice in the same location, you'll have a conflict: - - Button("OK"); - Button("OK"); // ID collision! Interacting with either button will trigger the first one. - - Fear not! this is easy to solve and there are many ways to solve it! - - - Solving ID conflict in a simple/local context: - When passing a label you can optionally specify extra ID information within string itself. - Use "##" to pass a complement to the ID that won't be visible to the end-user. - This helps solving the simple collision cases when you know e.g. at compilation time which items - are going to be created: - - Begin("MyWindow"); - Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play") - Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above - Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above - End(); - - - If you want to completely hide the label, but still need an ID: - - Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox! - - - Occasionally/rarely you might want change a label while preserving a constant ID. This allows - you to animate labels. For example you may want to include varying information in a window title bar, - but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID: - - Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID") - Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different - - sprintf(buf, "My game (%f FPS)###MyGame", fps); - Begin(buf); // Variable title, ID = hash of "MyGame" - - - Solving ID conflict in a more general manner: - Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts - within the same window. This is the most convenient way of distinguishing ID when iterating and - creating many UI elements programmatically. - You can push a pointer, a string or an integer value into the ID stack. - Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack. - At each level of the stack we store the seed used for items at this level of the ID stack. - - Begin("Window"); - for (int i = 0; i < 100; i++) - { - PushID(i); // Push i to the id tack - Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click") - PopID(); - } - for (int i = 0; i < 100; i++) - { - MyObject* obj = Objects[i]; - PushID(obj); - Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click") - PopID(); - } - for (int i = 0; i < 100; i++) - { - MyObject* obj = Objects[i]; - PushID(obj->Name); - Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click") - PopID(); - } - End(); - - - You can stack multiple prefixes into the ID stack: - - Button("Click"); // Label = "Click", ID = hash of (..., "Click") - PushID("node"); - Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") - PushID(my_ptr); - Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click") - PopID(); - PopID(); - - - Tree nodes implicitly creates a scope for you by calling PushID(). - - Button("Click"); // Label = "Click", ID = hash of (..., "Click") - if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag) - { - Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") - TreePop(); - } - - - When working with trees, ID are used to preserve the open/close state of each tree node. - Depending on your use cases you may want to use strings, indices or pointers as ID. - e.g. when following a single pointer that may change over time, using a static string as ID - will preserve your node open/closed state when the targeted object change. - e.g. when displaying a list of objects, using indices or pointers as ID will preserve the - node open/closed state differently. See what makes more sense in your situation! - + Q: How can I have widgets with an empty label? + Q: How can I have multiple widgets with the same label? + Q: Why are multiple widgets reacting when I interact with one? Q: How can I display an image? What is ImTextureID, how does it works? - >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - Q: How can I use my own math types instead of ImVec2/ImVec4? Q: How can I interact with standard C++ types (such as std::string and std::vector)? Q: How can I display custom shapes? (using low-level ImDrawList API) From 6b0cf2e6aed04209015a4636ed4302323f12ea83 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 24 Jun 2020 14:00:35 +0300 Subject: [PATCH 114/959] Windows: Fix unintended window size changes when resizing windows close to main viewport edges. --- docs/CHANGELOG.txt | 13 +++++++------ imgui.cpp | 7 +++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 35265e30..c145e368 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,17 +55,18 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). -- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item +- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] -- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new - ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward +- Windows: Fix unintended feedback loops when resizing windows close to main viewport edges. [@rokups] +- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new + ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. - Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions to first test for the presence of another popup at the same level. - Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing for !IsAnyItemHovered() prior to doing an OpenPopup. -- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), - allowing to check if any popup is open at the current level, if a given popup is open at any popup +- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), + allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) @@ -73,7 +74,7 @@ Other Changes: - Popups: Clarified some of the comments and function prototypes. - Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. Note that modals are more similar to regular windows than they are to - popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index a4ec7178..3135ca48 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5071,6 +5071,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) @@ -5096,6 +5099,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left + ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } @@ -5117,6 +5123,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); + nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); From d7ef56dca211fce88c797068b29e1112867c25e4 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 24 Jun 2020 14:00:35 +0300 Subject: [PATCH 115/959] Windows: Fix unintended window size changes when resizing windows close to main viewport edges. --- docs/CHANGELOG.txt | 13 +++++++------ imgui.cpp | 7 +++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f7128b4a..8d5a69bd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -123,17 +123,18 @@ Other Changes: Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). Set to an intermediary value to toggle behavior based on width (same as Firefox). -- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item +- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] -- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new - ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward +- Windows: Fix unintended feedback loops when resizing windows close to main viewport edges. [@rokups] +- Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new + ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. - Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions to first test for the presence of another popup at the same level. - Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing for !IsAnyItemHovered() prior to doing an OpenPopup. -- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), - allowing to check if any popup is open at the current level, if a given popup is open at any popup +- Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), + allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. - Popups: Fix an edge case where programatically closing a popup while clicking on its empty space would attempt to focus it and close other popups. (#2880) @@ -141,7 +142,7 @@ Other Changes: - Popups: Clarified some of the comments and function prototypes. - Modals: BeginPopupModal() doesn't set the ImGuiWindowFlags_NoSavedSettings flag anymore, and will not always be auto-centered. Note that modals are more similar to regular windows than they are to - popups, so api and behavior may evolve further toward embracing this. (#915, #3091) + popups, so api and behavior may evolve further toward embracing this. (#915, #3091) Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to diff --git a/imgui.cpp b/imgui.cpp index 52bb7790..0666b404 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5551,6 +5551,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) @@ -5576,6 +5579,9 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left + ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } @@ -5597,6 +5603,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); + nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); From dd02a180b52130df0747bcb61ed6faf8b95e14a9 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Jun 2020 22:58:23 +0200 Subject: [PATCH 116/959] Windows: Amend 6b0cf2e6 to facilitate working in viewport branch + handle safe area padding and ConfigWindowsMoveFromTitleBarOnly. --- imgui.cpp | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3135ca48..5b7cbe8b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -852,7 +852,7 @@ static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateTabFocus(); static void UpdateDebugToolItemPicker(); -static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); +static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); @@ -5019,7 +5019,7 @@ ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n) // Handle resize for: Resize Grips, Borders, Gamepad // Return true when using auto-fit (double click on resize grip) -static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) +static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; @@ -5071,8 +5071,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip - ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX); corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } @@ -5099,8 +5099,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left - ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX); border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } @@ -5123,7 +5123,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); - nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); + nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); @@ -5148,13 +5148,13 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s return ret_auto_fit; } -static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& viewport_rect, const ImVec2& padding) +static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = window->Size; if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) size_for_clamping.y = window->TitleBarHeight(); - window->Pos = ImClamp(window->Pos, viewport_rect.Min + padding - size_for_clamping, viewport_rect.Max - padding); + window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) @@ -5668,17 +5668,17 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = FindBestWindowPosForPopup(window); + // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. + ImRect viewport_rect(GetViewportRect()); + ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + ImRect visibility_rect(viewport_rect.Min + visibility_padding, viewport_rect.Max - visibility_padding); + // Clamp position/size so window stays visible within its viewport or monitor // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. - ImRect viewport_rect(GetViewportRect()); if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) - { - ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); - if (viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) - { - ClampWindowRect(window, viewport_rect, clamp_padding); - } - } + if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f) + ClampWindowRect(window, visibility_rect); window->Pos = ImFloor(window->Pos); // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) @@ -5705,7 +5705,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (!window->Collapsed) - if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0])) + if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true; window->ResizeBorderHeld = (signed char)border_held; From f4f04cb5ec83168a9d1917ebeed11ac185b37a76 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 25 Jun 2020 22:58:23 +0200 Subject: [PATCH 117/959] Windows: Amend 6b0cf2e6 to facilitate working in viewport branch + handle safe area padding and ConfigWindowsMoveFromTitleBarOnly. # Conflicts: # imgui.cpp --- imgui.cpp | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 0666b404..d265886c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -975,7 +975,7 @@ static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateTabFocus(); static void UpdateDebugToolItemPicker(); -static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); +static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); @@ -5489,7 +5489,7 @@ ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n) // Handle resize for: Resize Grips, Borders, Gamepad // Return true when using auto-fit (double click on resize grip) -static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) +static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; @@ -5551,8 +5551,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip - ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, grip.CornerPosN.y == 1 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, grip.CornerPosN.y == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX); corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } @@ -5579,8 +5579,8 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left - ImVec2 clamp_min = ImVec2(border_n == 1 ? g.Style.DisplayWindowPadding.x : -FLT_MAX, border_n == 2 ? g.Style.DisplayWindowPadding.y : -FLT_MAX); - ImVec2 clamp_max = ImVec2(border_n == 3 ? g.IO.DisplaySize.x - g.Style.DisplayWindowPadding.x : FLT_MAX, border_n == 0 ? g.IO.DisplaySize.y - g.Style.DisplayWindowPadding.y : FLT_MAX); + ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX); + ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX); border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } @@ -5603,7 +5603,7 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); - nav_resize_delta = ImClamp(nav_resize_delta, g.Style.DisplayWindowPadding - window->Pos - window->Size, ImVec2(FLT_MAX, FLT_MAX)); + nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); @@ -5628,13 +5628,13 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s return ret_auto_fit; } -static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& viewport_rect, const ImVec2& padding) +static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = window->Size; if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) size_for_clamping.y = window->TitleBarHeight(); - window->Pos = ImClamp(window->Pos, viewport_rect.Min + padding - size_for_clamping, viewport_rect.Max - padding); + window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) @@ -6318,16 +6318,21 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Viewport->Flags = viewport_flags; } + // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. + ImRect viewport_rect(window->Viewport->GetMainRect()); + ImRect viewport_work_rect(window->Viewport->GetWorkRect()); + ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding); + // Clamp position/size so window stays visible within its viewport or monitor // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. // FIXME: Similar to code in GetWindowAllowedExtentRect() - ImRect viewport_rect = window->Viewport->GetMainRect(); if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) { - ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) { - ClampWindowRect(window, window->Viewport->GetWorkRect(), clamp_padding); + ClampWindowRect(window, visibility_rect); } else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0) { @@ -6339,7 +6344,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) else { ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->Viewport->PlatformMonitor]; - ClampWindowRect(window, ImRect(monitor.WorkPos, monitor.WorkPos + monitor.WorkSize), clamp_padding); + visibility_rect.Min = monitor.WorkPos + visibility_padding; + visibility_rect.Max = monitor.WorkPos + monitor.WorkSize - visibility_padding; + ClampWindowRect(window, visibility_rect); } } } @@ -6375,7 +6382,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (handle_borders_and_resize_grips && !window->Collapsed) - if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0])) + if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true; window->ResizeBorderHeld = (signed char)border_held; From 122febcdbf00f7bda3c5ed654ce589a79cf26777 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jun 2020 15:03:11 +0200 Subject: [PATCH 118/959] IO: Added storage for PenPressure (unused by core library, to facilitate experiments) (#2372) --- imgui.h | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui.h b/imgui.h index c443ca75..d6208a31 100644 --- a/imgui.h +++ b/imgui.h @@ -1584,6 +1584,7 @@ struct ImGuiIO float KeysDownDurationPrev[512]; // Previous duration the key has been down float NavInputsDownDuration[ImGuiNavInput_COUNT]; float NavInputsDownDurationPrev[ImGuiNavInput_COUNT]; + float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16 ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform back-end). Fill using AddInputCharacter() helper. From 9418dcb69355558f70de260483424412c5ca2fce Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jun 2020 15:09:55 +0200 Subject: [PATCH 119/959] Version 1.77 + fix minor clang-tidy warnings which seems reasonable --- docs/CHANGELOG.txt | 32 ++++++++++++++++++-------------- docs/TODO.txt | 5 ++--- examples/README.txt | 2 +- imgui.cpp | 3 ++- imgui.h | 10 +++++----- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 4 ++-- 9 files changed, 34 insertions(+), 30 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c145e368..4d757e0b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -9,11 +9,12 @@ RELEASE NOTES: https://github.com/ocornut/imgui/releases REPORT ISSUES, ASK QUESTIONS: https://github.com/ocornut/imgui/issues COMMITS HISTORY: https://github.com/ocornut/imgui/commits/master FAQ https://www.dearimgui.org/faq/ +WIKI https://github.com/ocornut/imgui/wiki WHEN TO UPDATE? -- Keeping your copy of dear imgui updated once in a while is recommended. -- It is generally safe to sync to the latest commit in master. +- Keeping your copy of Dear ImGui updated regularly is recommended. +- It is generally safe to sync to the latest commit in master or docking branches The library is fairly stable and regressions tends to be fixed fast when reported. HOW TO UPDATE? @@ -31,13 +32,16 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.77 WIP (In Progress) + VERSION 1.77 (Released 2020-06-29) ----------------------------------------------------------------------- +Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.77 + Breaking Changes: - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please - note that this is a Beta api and will likely be reworked to support multi-monitor multi-DPI. + note that this is a Beta api and will likely be reworked in order to support multi-DPI accross + multiple monitors. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. @@ -51,20 +55,20 @@ Other Changes: flag was also set, and _OpenOnArrow is frequently set along with _OpenOnDoubleClick). - TreeNode: Fixed bug where dragging a payload over a TreeNode() with either _OpenOnDoubleClick or _OpenOnArrow would open the node. (#143) -- Style: Added style.TabMinWidthForUnselectedCloseButton settings. - Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). - Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). - Set to an intermediary value to toggle behavior based on width (same as Firefox). -- Tab: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item - (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] - Windows: Fix unintended feedback loops when resizing windows close to main viewport edges. [@rokups] +- Tabs: Added style.TabMinWidthForUnselectedCloseButton settings: + - Set to 0.0f (default) to always make a close button appear on hover (same as Chrome, VS). + - Set to FLT_MAX to only display a close button when selected (merely hovering is not enough). + - Set to an intermediary value to toggle behavior based on width (same as Firefox). +- Tabs: Added a ImGuiTabItemFlags_NoTooltip flag to disable the tooltip for individual tab item + (vs ImGuiTabBarFlags_NoTooltip for entire tab bar). [@Xipiryon] - Popups: All functions capable of opening popups (OpenPopup*, BeginPopupContext*) now take a new ImGuiPopupFlags sets of flags instead of a mouse button index. The API is automatically backward compatible as ImGuiPopupFlags is guaranteed to hold mouse button index in the lower bits. - Popups: Added ImGuiPopupFlags_NoOpenOverExistingPopup for OpenPopup*/BeginPopupContext* functions to first test for the presence of another popup at the same level. - Popups: Added ImGuiPopupFlags_NoOpenOverItems for BeginPopupContextWindow() - similar to testing - for !IsAnyItemHovered() prior to doing an OpenPopup. + for !IsAnyItemHovered() prior to doing an OpenPopup(). - Popups: Added ImGuiPopupFlags_AnyPopupId and ImGuiPopupFlags_AnyPopupLevel flags for IsPopupOpen(), allowing to check if any popup is open at the current level, if a given popup is open at any popup level, if any popup is open at all. @@ -78,7 +82,7 @@ Other Changes: Enforce centering using e.g. SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f)). - Metrics: Added a "Settings" section with some details about persistent ini settings. - Nav, Menus: Fix vertical wrap-around in menus or popups created with multiple appending calls to - BeginMenu()/EndMenu() or BeginPopup/EndPopup(). (#3223, #1207) [@rokups] + BeginMenu()/EndMenu() or BeginPopup(0/EndPopup(). (#3223, #1207) [@rokups] - Drag and Drop: Fixed unintended fallback "..." tooltip display during drag operation when drag source uses _SourceNoPreviewTooltip flags. (#3160) [@rokups] - Columns: Lower overhead on column switches and switching to background channel. @@ -96,12 +100,12 @@ Other Changes: a callback draw command would incorrectly override the callback draw command. - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra unrequired vertex. [@ShironekoBen] -- Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. +- Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeeds but FT_Load_Glyph() fails. - Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). - Fixed a static contructor which led to this dependency on some compiler setups (unclear which). + Fixed a static constructor which led to this dependency on some compiler setups. - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, diff --git a/docs/TODO.txt b/docs/TODO.txt index 71969690..abb9d513 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -34,7 +34,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window/child: border could be emitted in parent as well. - window/child: allow SetNextWindowContentSize() to work on child windows. - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - - window/tab: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). + - window/tabbing: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). ! scrolling: exposing horizontal scrolling with Shift+Wheel even when scrollbar is disabled expose lots of issues (#2424, #1463) - scrolling: while holding down a scrollbar, try to keep the same contents visible (at least while not moving mouse) - scrolling: allow immediately effective change of scroll after Begin() if we haven't appended items yet. @@ -111,7 +111,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. - layout: helper or a way to express ImGui::SameLine(ImGui::GetCursorStartPos().x + ImGui::CalcItemWidth() + ImGui::GetStyle().ItemInnerSpacing.x); in a simpler manner. - - layout: generalization of the above: a concept equivalent to word processor ruler tab stop ~ mini columns (position in X, no clipping implied) (vaguely relate to #267, #395, also what is used internally for menu items) + - layout, font: horizontal tab support, A) text mode: forward only tabs (e.g. every 4 characters/N pixels from pos x1), B) manual mode: explicit tab stops acting as mini columns, no clipping (for menu items, many kind of uses, also vaguely relate to #267, #395) - layout: horizontal layout helper (#97) - layout: horizontal flow until no space left (#404) - layout: more generic alignment state (left/right/centered) for single items? @@ -167,7 +167,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tabs: explicit api (even if internal) to cleanly manipulate tab order. - tabs: Mouse wheel over tab bar could scroll? (#2702) - - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - image button: not taking an explicit id can be problematic. (#2464, #1390) diff --git a/examples/README.txt b/examples/README.txt index 0933a6ba..2137fe09 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.77 WIP + dear imgui, v1.77 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 5b7cbe8b..2b5983a3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (main code and documentation) // Help: @@ -10382,6 +10382,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) char* p = buf; const char* buf_end = buf + IM_ARRAYSIZE(buf); p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : ""); + IM_UNUSED(p); if (ImGui::TreeNode(tab_bar, "%s", buf)) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) diff --git a/imgui.h b/imgui.h index d6208a31..3751f2e3 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (headers) // Help: @@ -59,8 +59,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.77 WIP" -#define IMGUI_VERSION_NUM 17602 +#define IMGUI_VERSION "1.77" +#define IMGUI_VERSION_NUM 17700 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -85,8 +85,8 @@ Index of this file: #define IM_FMTARGS(FMT) #define IM_FMTLIST(FMT) #endif -#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*_ARR))) // Size of a static C-style array. Don't use on pointers! -#define IM_UNUSED(_VAR) ((void)_VAR) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! +#define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. #if (__cplusplus >= 201100) #define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11 #else diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0c9b6e23..7abe7dd7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 0e7c294e..49197277 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 9ec0760d..dd61fea6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! @@ -147,7 +147,7 @@ namespace ImStb #undef STB_TEXTEDIT_CHARTYPE #define STB_TEXTEDIT_STRING ImGuiInputTextState #define STB_TEXTEDIT_CHARTYPE ImWchar -#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f +#define STB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) #define STB_TEXTEDIT_UNDOSTATECOUNT 99 #define STB_TEXTEDIT_UNDOCHARCOUNT 999 #include "imstb_textedit.h" diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ec0bcc74..918dbf94 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 WIP +// dear imgui, v1.77 // (widgets code) /* @@ -5634,7 +5634,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags if (p_open) flags |= ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton; bool is_open = TreeNodeBehavior(id, flags, label); - if (p_open) + if (p_open != NULL) { // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. From dca7c3c62975b893fde1c65f3d8f43bb476bc381 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 29 Jun 2020 20:10:59 +0200 Subject: [PATCH 120/959] TestEngine: Added hook to notify test engine of a removed imgui context. --- imgui.cpp | 5 +++++ imgui.h | 2 +- imgui_internal.h | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 2b5983a3..176326ed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3916,6 +3916,11 @@ void ImGui::Shutdown(ImGuiContext* context) SetCurrentContext(backup_context); } + // Notify hooked test engine, if any +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGuiTestEngineHook_Shutdown(context); +#endif + // Clear everything else for (int i = 0; i < g.Windows.Size; i++) IM_DELETE(g.Windows[i]); diff --git a/imgui.h b/imgui.h index 3751f2e3..9c926c86 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.77" -#define IMGUI_VERSION_NUM 17700 +#define IMGUI_VERSION_NUM 17701 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_internal.h b/imgui_internal.h index dd61fea6..01a7a82c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2028,8 +2028,8 @@ IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned ch // [SECTION] Test Engine Hooks (imgui_test_engine) //----------------------------------------------------------------------------- -//#define IMGUI_ENABLE_TEST_ENGINE #ifdef IMGUI_ENABLE_TEST_ENGINE +extern void ImGuiTestEngineHook_Shutdown(ImGuiContext* ctx); extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); From 0738611559b0a51c7fa0c376eb9601587231f841 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Tue, 30 Jun 2020 15:31:54 +0200 Subject: [PATCH 121/959] Misc: Bunch of code formatting changes suggested by a pass running 'astyle' --- examples/imgui_impl_allegro5.cpp | 16 +-- examples/imgui_impl_dx10.cpp | 2 +- examples/imgui_impl_dx11.cpp | 2 +- examples/imgui_impl_dx12.cpp | 5 +- examples/imgui_impl_dx9.cpp | 4 +- examples/imgui_impl_glfw.cpp | 2 +- examples/imgui_impl_glut.cpp | 8 +- examples/imgui_impl_marmalade.cpp | 10 +- examples/imgui_impl_metal.h | 2 +- examples/imgui_impl_osx.h | 4 +- examples/imgui_impl_vulkan.cpp | 4 +- examples/imgui_impl_win32.cpp | 6 +- imgui.cpp | 116 +++++++++---------- imgui.h | 32 +++--- imgui_demo.cpp | 128 ++++++++++----------- imgui_draw.cpp | 96 ++++++++-------- imgui_internal.h | 32 +++--- imgui_widgets.cpp | 154 +++++++++++++------------- misc/fonts/binary_to_compressed_c.cpp | 20 ++-- misc/freetype/imgui_freetype.cpp | 8 +- 20 files changed, 326 insertions(+), 325 deletions(-) diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 2c7df9a9..4a467c30 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -174,7 +174,7 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplAllegro5_CreateDeviceObjects() { // Build texture atlas - ImGuiIO &io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); @@ -182,7 +182,7 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() // Create texture int flags = al_get_new_bitmap_flags(); int fmt = al_get_new_bitmap_format(); - al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP|ALLEGRO_MIN_LINEAR|ALLEGRO_MAG_LINEAR); + al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE); ALLEGRO_BITMAP* img = al_create_bitmap(width, height); al_set_new_bitmap_flags(flags); @@ -190,13 +190,13 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() if (!img) return false; - ALLEGRO_LOCKED_REGION *locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY); + ALLEGRO_LOCKED_REGION* locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY); if (!locked_img) { al_destroy_bitmap(img); return false; } - memcpy(locked_img->data, pixels, sizeof(int)*width*height); + memcpy(locked_img->data, pixels, sizeof(int) * width * height); al_unlock_bitmap(img); // Convert software texture to hardware texture. @@ -211,7 +211,7 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() // Create an invisible mouse cursor // Because al_hide_mouse_cursor() seems to mess up with the actual inputs.. - ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8,8); + ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8, 8); g_MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0); al_destroy_bitmap(mouse_cursor); @@ -322,7 +322,7 @@ void ImGui_ImplAllegro5_Shutdown() // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. -bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT *ev) +bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) { ImGuiIO& io = ImGui::GetIO(); @@ -403,7 +403,7 @@ void ImGui_ImplAllegro5_NewFrame() if (!g_Texture) ImGui_ImplAllegro5_CreateDeviceObjects(); - ImGuiIO &io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; @@ -413,7 +413,7 @@ void ImGui_ImplAllegro5_NewFrame() // Setup time step double current_time = al_get_time(); - io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; // Setup inputs diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 23ade277..beade17f 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -287,7 +287,7 @@ static void ImGui_ImplDX10_CreateFontsTexture() desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - ID3D10Texture2D *pTexture = NULL; + ID3D10Texture2D* pTexture = NULL; D3D10_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 26eb407f..0f4a8615 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -299,7 +299,7 @@ static void ImGui_ImplDX11_CreateFontsTexture() desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - ID3D11Texture2D *pTexture = NULL; + ID3D11Texture2D* pTexture = NULL; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 167a189b..e9cd45c6 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -359,7 +359,7 @@ static void ImGui_ImplDX12_CreateFontsTexture() hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); - cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*) &cmdList); + cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); hr = cmdQueue->Signal(fence, 1); IM_ASSERT(SUCCEEDED(hr)); @@ -509,7 +509,8 @@ bool ImGui_ImplDX12_CreateDeviceObjects() psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() }; // Create the input layout - static D3D12_INPUT_ELEMENT_DESC local_layout[] = { + static D3D12_INPUT_ELEMENT_DESC local_layout[] = + { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 03114aa8..b4c49cdc 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -199,7 +199,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->TextureId; g_pd3dDevice->SetTexture(0, texture); g_pd3dDevice->SetScissorRect(&r); - g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount/3); + g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3); } } global_idx_offset += cmd_list->IdxBuffer.Size; @@ -250,7 +250,7 @@ static bool ImGui_ImplDX9_CreateFontsTexture() if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK) return false; for (int y = 0; y < height; y++) - memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel)); + memcpy((unsigned char*)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel)); g_FontTexture->UnlockRect(0); // Store our identifier diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index ef63c81f..5ea7be08 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -358,7 +358,7 @@ void ImGui_ImplGlfw_NewFrame() // Setup time step double current_time = glfwGetTime(); - io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; ImGui_ImplGlfw_UpdateMousePosAndButtons(); diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index 3c17bbfc..c8051452 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -25,9 +25,9 @@ #include "imgui.h" #include "imgui_impl_glut.h" #ifdef __APPLE__ - #include +#include #else - #include +#include #endif #ifdef _MSC_VER @@ -41,9 +41,9 @@ bool ImGui_ImplGLUT_Init() ImGuiIO& io = ImGui::GetIO(); #ifdef FREEGLUT - io.BackendPlatformName ="imgui_impl_glut (freeglut)"; + io.BackendPlatformName = "imgui_impl_glut (freeglut)"; #else - io.BackendPlatformName ="imgui_impl_glut"; + io.BackendPlatformName = "imgui_impl_glut"; #endif g_Time = 0; diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index 0675c6b4..00626072 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -36,7 +36,7 @@ static char* g_ClipboardText = NULL; static bool g_osdKeyboardEnabled = false; // use this setting to scale the interface - e.g. on device you could use 2 or 3 scale factor -static ImVec2 g_RenderScale = ImVec2(1.0f,1.0f); +static ImVec2 g_RenderScale = ImVec2(1.0f, 1.0f); // Render function. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) @@ -272,18 +272,18 @@ void ImGui_Marmalade_NewFrame() // Setup display size (every frame to accommodate for window resizing) int w = IwGxGetScreenWidth(), h = IwGxGetScreenHeight(); io.DisplaySize = ImVec2((float)w, (float)h); - // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. + // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. io.DisplayFramebufferScale = g_scale; // Setup time step double current_time = s3eTimerGetUST() / 1000.0f; - io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; double mouse_x, mouse_y; mouse_x = s3ePointerGetX(); mouse_y = s3ePointerGetY(); - io.MousePos = ImVec2((float)mouse_x/g_scale.x, (float)mouse_y/g_scale.y); // Mouse position (set to -FLT_MAX,-FLT_MAX if no mouse / on another screen, etc.) + io.MousePos = ImVec2((float)mouse_x / g_scale.x, (float)mouse_y / g_scale.y); // Mouse position (set to -FLT_MAX,-FLT_MAX if no mouse / on another screen, etc.) for (int i = 0; i < 3; i++) { @@ -294,7 +294,7 @@ void ImGui_Marmalade_NewFrame() // TODO: Hide OS mouse cursor if ImGui is drawing it // s3ePointerSetInt(S3E_POINTER_HIDE_CURSOR,(io.MouseDrawCursor ? 0 : 1)); - // Show/hide OSD keyboard + // Show/hide OSD keyboard if (io.WantTextInput) { // Some text input widget is active? diff --git a/examples/imgui_impl_metal.h b/examples/imgui_impl_metal.h index f6e8fd2b..3e61085c 100644 --- a/examples/imgui_impl_metal.h +++ b/examples/imgui_impl_metal.h @@ -16,7 +16,7 @@ IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id device); IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor *renderPassDescriptor); +IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor); IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder); diff --git a/examples/imgui_impl_osx.h b/examples/imgui_impl_osx.h index dae5c0ce..d37652be 100644 --- a/examples/imgui_impl_osx.h +++ b/examples/imgui_impl_osx.h @@ -15,5 +15,5 @@ IMGUI_IMPL_API bool ImGui_ImplOSX_Init(); IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView *_Nullable view); -IMGUI_IMPL_API bool ImGui_ImplOSX_HandleEvent(NSEvent *_Nonnull event, NSView *_Nullable view); +IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view); +IMGUI_IMPL_API bool ImGui_ImplOSX_HandleEvent(NSEvent* _Nonnull event, NSView* _Nullable view); diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index c65b2db0..465060d5 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -221,7 +221,7 @@ static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, ui VkPhysicalDeviceMemoryProperties prop; vkGetPhysicalDeviceMemoryProperties(v->PhysicalDevice, &prop); for (uint32_t i = 0; i < prop.memoryTypeCount; i++) - if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<GetTexDataAsRGBA32(&pixels, &width, &height); - size_t upload_size = width*height*4*sizeof(char); + size_t upload_size = width * height * 4 * sizeof(char); VkResult err; diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 57d6e3ed..f6dd5b82 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -63,9 +63,9 @@ static bool g_WantUpdateHasGamepad = true; // Functions bool ImGui_ImplWin32_Init(void* hwnd) { - if (!::QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond)) + if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&g_TicksPerSecond)) return false; - if (!::QueryPerformanceCounter((LARGE_INTEGER *)&g_Time)) + if (!::QueryPerformanceCounter((LARGE_INTEGER*)&g_Time)) return false; // Setup back-end capabilities flags @@ -223,7 +223,7 @@ void ImGui_ImplWin32_NewFrame() // Setup time step INT64 current_time; - ::QueryPerformanceCounter((LARGE_INTEGER *)¤t_time); + ::QueryPerformanceCounter((LARGE_INTEGER*)¤t_time); io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond; g_Time = current_time; diff --git a/imgui.cpp b/imgui.cpp index 176326ed..295cb054 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -981,7 +981,7 @@ ImGuiIO::ImGuiIO() ConfigFlags = ImGuiConfigFlags_None; BackendFlags = ImGuiBackendFlags_None; DisplaySize = ImVec2(-1.0f, -1.0f); - DeltaTime = 1.0f/60.0f; + DeltaTime = 1.0f / 60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; @@ -1122,7 +1122,7 @@ static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; d3 = (d3 >= 0) ? d3 : -d3; - if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) { ImVec2 p_current(x4, y4); ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); @@ -1136,12 +1136,12 @@ static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, } else if (level < 10) { - float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; - float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; - float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; - float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; - float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; - float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; + float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f; + float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f; + float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f; + float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f; + float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f; + float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f; BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); } @@ -1595,7 +1595,7 @@ int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const cha { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); @@ -1642,7 +1642,7 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); - buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c ) & 0x3f)); return 3; } @@ -1679,13 +1679,13 @@ int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWch { char* buf_out = buf; const char* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else - buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); + buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c); } *buf_out = 0; return (int)(buf_out - buf); @@ -1721,7 +1721,7 @@ IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b) ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) { - float s = 1.0f/255.0f; + float s = 1.0f / 255.0f; return ImVec4( ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, @@ -1772,7 +1772,7 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& return; } - h = ImFmod(h, 1.0f) / (60.0f/360.0f); + h = ImFmod(h, 1.0f) / (60.0f / 360.0f); int i = (int)h; float f = h - (float)i; float p = v * (1.0f - s); @@ -1989,7 +1989,7 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector 0.0f) { - window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } @@ -2675,7 +2675,7 @@ void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) const float border_size = g.Style.FrameBorderSize; if (border_size > 0.0f) { - window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); + window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } @@ -2698,11 +2698,11 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl { const float THICKNESS = 2.0f; const float DISTANCE = 3.0f + THICKNESS * 0.5f; - display_rect.Expand(ImVec2(DISTANCE,DISTANCE)); + display_rect.Expand(ImVec2(DISTANCE, DISTANCE)); bool fully_visible = window->ClipRect.Contains(display_rect); if (!fully_visible) window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); - window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); + window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); if (!fully_visible) window->DrawList->PopClipRect(); } @@ -3820,7 +3820,7 @@ void ImGui::NewFrame() // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. // This fallback is particularly important as it avoid ImGui:: calls from crashing. g.WithinFrameScopeWithImplicitWindow = true; - SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); + SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true); @@ -4460,7 +4460,7 @@ ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.BeginPopupStack.Size > 0) - return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos; + return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; return g.IO.MousePos; } @@ -4662,7 +4662,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, b ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; - flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; + flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow; flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag // Size @@ -4702,7 +4702,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, b { FocusWindow(child_window); NavInitWindow(child_window, false); - SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item + SetActiveID(id + 1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item g.ActiveIdSource = ImGuiInputSource_Nav; } return ret; @@ -4752,7 +4752,7 @@ void ImGui::EndChild() // When browsing a window that has no activable items (scroll only) we keep a highlight on the child if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow) - RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); + RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); } else { @@ -4978,10 +4978,10 @@ struct ImGuiResizeGripDef static const ImGuiResizeGripDef resize_grip_def[4] = { - { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower-right - { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower-left - { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper-left (Unused) - { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper-right (Unused) + { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right + { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left + { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused) + { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }, // Upper-right (Unused) }; struct ImGuiResizeBorderDef @@ -4993,16 +4993,16 @@ struct ImGuiResizeBorderDef static const ImGuiResizeBorderDef resize_border_def[4] = { - { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top - { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right - { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom - { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left + { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Top + { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right + { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }, // Bottom + { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f } // Left }; static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) { ImRect rect = window->Rect(); - if (thickness == 0.0f) rect.Max -= ImVec2(1,1); + if (thickness == 0.0f) rect.Max -= ImVec2(1, 1); if (border_n == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom @@ -5175,8 +5175,8 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { const ImGuiResizeBorderDef& def = resize_border_def[border_held]; ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); - window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle); - window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle); + window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f); window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual } if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) @@ -5515,7 +5515,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) window->Active = true; window->HasCloseButton = (p_open != NULL); - window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); + window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX); window->IDStack.resize(1); window->DrawList->_ResetForNewFrame(); @@ -7067,10 +7067,10 @@ void ImGui::PushMultiItemsWidths(int components, float w_full) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiStyle& style = g.Style; - const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); + const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); window->DC.ItemWidthStack.push_back(w_item_last); - for (int i = 0; i < components-1; i++) + for (int i = 0; i < components - 1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; @@ -7491,7 +7491,7 @@ void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags toolt window->HiddenFramesCanSkipItems = 1; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount); } - ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; + ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; Begin(window_name, NULL, flags | extra_flags); } @@ -7564,7 +7564,7 @@ bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags) ImGuiWindow* ImGui::GetTopMostPopupModal() { ImGuiContext& g = *GImGui; - for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) + for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--) if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) if (popup->Flags & ImGuiWindowFlags_Modal) return popup; @@ -7838,7 +7838,7 @@ bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flag int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id, popup_flags); - return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) @@ -7851,7 +7851,7 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_fl if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) OpenPopupEx(id, popup_flags); - return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) @@ -7864,7 +7864,7 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flag if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) if (GetTopMostPopupModal() == NULL) OpenPopupEx(id, popup_flags); - return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); + return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) @@ -8083,7 +8083,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items if (dby != 0.0f && dbx != 0.0f) - dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); + dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); float dist_box = ImFabs(dbx) + ImFabs(dby); // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) @@ -8124,7 +8124,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) ImDrawList* draw_list = GetForegroundDrawList(window); draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100)); draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200)); - draw_list->AddRectFilled(cand.Max - ImVec2(4,4), cand.Max + CalcTextSize(buf) + ImVec2(4,4), IM_COL32(40,0,0,150)); + draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150)); draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf); } else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate. @@ -8138,7 +8138,7 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf); } } - #endif +#endif // Is it in the quadrant we're interesting in moving to? bool new_best = false; @@ -8214,7 +8214,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con // Process Move Request (scoring for navigation) // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy) - if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav))) + if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav))) { ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; #if IMGUI_DEBUG_NAV_SCORING @@ -8649,7 +8649,7 @@ static void ImGui::NavUpdate() // *Normal* Manual scroll with NavScrollXXX keys // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. - ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); + ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f); if (scroll_dir.x != 0.0f && window->ScrollbarX) { SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); @@ -8671,7 +8671,7 @@ static void ImGui::NavUpdate() if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == ImGuiNavLayer_Main) { ImGuiWindow* window = g.NavWindow; - ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1)); + ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1)); if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { float pad = window->CalcFontSize() * 0.5f; @@ -8683,7 +8683,7 @@ static void ImGui::NavUpdate() } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) - ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); + ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y); g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x); @@ -8901,7 +8901,7 @@ static void ImGui::NavEndFrame() static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; - for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--) + for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--) if (g.WindowsFocusOrder[i] == window) return i; return -1; @@ -9385,7 +9385,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop // FIXME-DRAG: Settle on a proper default visuals for drop target. r.Expand(3.5f); bool push_clip_rect = !window->ClipRect.Contains(r); - if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1)); + if (push_clip_rect) window->DrawList->PushClipRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1)); window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f); if (push_clip_rect) window->DrawList->PopClipRect(); } @@ -10222,7 +10222,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); - ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) if (node_open) ImGui::TreePop(); return; } @@ -10250,7 +10250,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", - pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, + pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (ImGui::IsItemHovered() && (show_drawcmd_mesh || show_drawcmd_aabb) && fg_draw_list) @@ -10276,11 +10276,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, true, false); // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. - ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + ImGuiListClipper clipper(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) - for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) + for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) { - char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); + char* buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangle[3]; for (int n = 0; n < 3; n++, idx_i++) { diff --git a/imgui.h b/imgui.h index 9c926c86..724aa289 100644 --- a/imgui.h +++ b/imgui.h @@ -173,7 +173,7 @@ typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: f typedef void* ImTextureID; // User data for rendering back-end to identify a texture. This is whatever to you want it to be! read the FAQ about ImTextureID for details. #endif typedef unsigned int ImGuiID; // A unique ID used by widgets, typically hashed from a stack of string. -typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data); +typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Decoded character types @@ -1254,13 +1254,13 @@ enum ImGuiColorEditFlags_ // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. - ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, // [Internal] Masks - ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB|ImGuiColorEditFlags_DisplayHSV|ImGuiColorEditFlags_DisplayHex, - ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, - ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, - ImGuiColorEditFlags__InputMask = ImGuiColorEditFlags_InputRGB|ImGuiColorEditFlags_InputHSV + ImGuiColorEditFlags__DisplayMask = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, + ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, + ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, + ImGuiColorEditFlags__InputMask = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -1375,7 +1375,7 @@ struct ImVector inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } - inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } + inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } inline void shrink(int new_size) { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation @@ -1385,10 +1385,10 @@ struct ImVector inline void push_back(const T& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } inline void push_front(const T& v) { if (Size == 0) push_back(v); else insert(Data, v); } - inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } - inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(T)); Size -= (int)count; return Data + off; } - inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } - inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } + inline T* erase(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; } + inline T* erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last > it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(T)); Size -= (int)count; return Data + off; } + inline T* erase_unsorted(const T* it) { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; } + inline T* insert(const T* it, const T& v) { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } inline bool contains(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } inline T* find(const T& v) { T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } inline const T* find(const T& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; } @@ -1651,7 +1651,7 @@ struct ImGuiPayload ImGuiID SourceId; // Source item id ImGuiID SourceParentId; // Source parent id (if available) int DataFrameCount; // Data timestamp - char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max) + char DataType[32 + 1]; // Data type tag (short user-supplied string, 32 characters max) bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. @@ -1879,8 +1879,8 @@ struct ImColor ImVec4 Value; ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } - ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } - ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } + ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f / 255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } + ImColor(ImU32 rgba) { float sc = 1.0f / 255.0f; Value.x = (float)((rgba >> IM_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } @@ -1888,7 +1888,7 @@ struct ImColor // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } - static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); } }; //----------------------------------------------------------------------------- @@ -2074,7 +2074,7 @@ struct ImDrawList // Stateful path API, add points then finish with PathFillConvex() or PathStroke() inline void PathClear() { _Path.Size = 0; } inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } - inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } // Note: Anti-aliased filling requires points to be in clockwise order. inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); _Path.Size = 0; } IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 10); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7abe7dd7..e0fc9af7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -378,12 +378,12 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Configuration##2")) { - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); ImGui::SameLine(); HelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); - ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); + ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); // The "NoMouse" option above can get us stuck with a disable mouse! Provide an alternative way to fix it: if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) @@ -396,7 +396,7 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Space))) io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; } - ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); + ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); ImGui::SameLine(); HelpMarker("Instruct back-end to not alter mouse cursor shape and visibility."); ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); ImGui::SameLine(); HelpMarker("Set to false to disable blinking cursor, for users who consider it distracting"); @@ -417,10 +417,10 @@ void ImGui::ShowDemoWindow(bool* p_open) // Make a local copy to avoid modifying actual back-end flags. ImGuiBackendFlags backend_flags = io.BackendFlags; - ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasGamepad); - ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseCursors); - ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasSetMousePos); - ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); + ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasGamepad); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasMouseCursors); + ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasSetMousePos); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int*)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); ImGui::TreePop(); ImGui::Separator(); } @@ -507,9 +507,9 @@ static void ShowDemoWindowWidgets() if (i > 0) ImGui::SameLine(); ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.6f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.7f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i/7.0f, 0.8f, 0.8f)); + ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); ImGui::Button("Click"); ImGui::PopStyleColor(3); ImGui::PopID(); @@ -615,17 +615,17 @@ static void ShowDemoWindowWidgets() ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%"); - static float f1=1.00f, f2=0.0067f; + static float f1 = 1.00f, f2 = 0.0067f; ImGui::DragFloat("drag float", &f1, 0.005f); ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); } { - static int i1=0; + static int i1 = 0; ImGui::SliderInt("slider int", &i1, -1, 3); ImGui::SameLine(); HelpMarker("CTRL+click to input value."); - static float f1=0.123f, f2=0.0f; + static float f1 = 0.123f, f2 = 0.0f; ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); ImGui::SliderFloat("slider float (curve)", &f2, -10.0f, 10.0f, "%.4f", 2.0f); @@ -644,8 +644,8 @@ static void ShowDemoWindowWidgets() } { - static float col1[3] = { 1.0f,0.0f,0.2f }; - static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; + static float col1[3] = { 1.0f, 0.0f, 0.2f }; + static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; ImGui::ColorEdit3("color 1", col1); ImGui::SameLine(); HelpMarker( "Click on the colored square to open a color picker.\n" @@ -822,8 +822,8 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Colored Text")) { // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. - ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); - ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); + ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow"); ImGui::TextDisabled("Disabled"); ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle."); ImGui::TreePop(); @@ -1079,11 +1079,11 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Grid")) { - static int selected[4*4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; - for (int i = 0; i < 4*4; i++) + static int selected[4 * 4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; + for (int i = 0; i < 4 * 4; i++) { ImGui::PushID(i); - if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50,50))) + if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50, 50))) { // Toggle selected[i] = !selected[i]; @@ -1118,7 +1118,7 @@ static void ShowDemoWindowWidgets() sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y); if (x > 0) ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment); - ImGui::Selectable(name, &selected[3*y+x], ImGuiSelectableFlags_None, ImVec2(80,80)); + ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80)); ImGui::PopStyleVar(); } } @@ -1253,9 +1253,9 @@ static void ShowDemoWindowWidgets() { static float phase = 0.0f; values[values_offset] = cosf(phase); - values_offset = (values_offset+1) % IM_ARRAYSIZE(values); - phase += 0.10f*values_offset; - refresh_time += 1.0f/60.0f; + values_offset = (values_offset + 1) % IM_ARRAYSIZE(values); + phase += 0.10f * values_offset; + refresh_time += 1.0f / 60.0f; } // Plots can display overlay texts @@ -1286,8 +1286,8 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); ImGui::SliderInt("Sample count", &display_count, 1, 400); float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; - ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); - ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); ImGui::Separator(); // Animate a simple progress bar @@ -1301,20 +1301,20 @@ static void ShowDemoWindowWidgets() // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width, // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. - ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f)); + ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f)); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::Text("Progress Bar"); float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f); char buf[32]; - sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); - ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); + sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf); ImGui::TreePop(); } if (ImGui::TreeNode("Color/Picker Widgets")) { - static ImVec4 color = ImVec4(114.0f/255.0f, 144.0f/255.0f, 154.0f/255.0f, 200.0f/255.0f); + static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f); static bool alpha_preview = true; static bool alpha_half_preview = false; @@ -1381,9 +1381,9 @@ static void ShowDemoWindowWidgets() ImGui::BeginGroup(); // Lock X position ImGui::Text("Current"); - ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40)); + ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); ImGui::Text("Previous"); - if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60,40))) + if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) color = backup_color; ImGui::Separator(); ImGui::Text("Palette"); @@ -1394,7 +1394,7 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; - if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20,20))) + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! // Allow user to drop colors into each palette entry. Note that ColorButton() is already a @@ -1417,14 +1417,14 @@ static void ShowDemoWindowWidgets() ImGui::Text("Color button only:"); static bool no_border = false; ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); - ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80,80)); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); ImGui::Text("Color picker:"); static bool alpha = true; static bool alpha_bar = true; static bool side_preview = true; static bool ref_color = false; - static ImVec4 ref_color_v(1.0f,0.0f,1.0f,0.5f); + static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f); static int display_mode = 0; static int picker_mode = 0; ImGui::Checkbox("With Alpha", &alpha); @@ -1639,7 +1639,7 @@ static void ShowDemoWindowWidgets() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); static int int_value = 0; - ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); + ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); ImGui::SameLine(); static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; @@ -1648,11 +1648,11 @@ static void ShowDemoWindowWidgets() { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i/7.0f, 0.5f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i/7.0f, 0.6f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i/7.0f, 0.7f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i/7.0f, 0.9f, 0.9f)); - ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); + ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values[i]); ImGui::PopStyleColor(4); @@ -1671,7 +1671,7 @@ static void ShowDemoWindowWidgets() ImGui::BeginGroup(); for (int ny = 0; ny < rows; ny++) { - ImGui::PushID(nx*rows+ny); + ImGui::PushID(nx * rows + ny); ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values2[nx]); @@ -1688,7 +1688,7 @@ static void ShowDemoWindowWidgets() if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); - ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); ImGui::PopStyleVar(); ImGui::PopID(); } @@ -1736,7 +1736,7 @@ static void ShowDemoWindowWidgets() ImGui::PushID(n); if ((n % 3) != 0) ImGui::SameLine(); - ImGui::Button(names[n], ImVec2(60,60)); + ImGui::Button(names[n], ImVec2(60, 60)); // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) @@ -2560,8 +2560,8 @@ static void ShowDemoWindowLayout() ImGui::PushID(n + line * 1000); char num_buf[16]; sprintf(num_buf, "%d", n); - const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : num_buf; - float hue = n*0.05f; + const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf; + float hue = n * 0.05f; ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f)); @@ -2906,7 +2906,7 @@ static void ShowDemoWindowPopups() // Testing behavior of widgets stacking their own regular popups over the modal. static int item = 1; - static float color[4] = { 0.4f,0.7f,0.0f,0.5f }; + static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); ImGui::ColorEdit4("color", color); @@ -3933,7 +3933,7 @@ static void ShowExampleMenuFile() { const char* name = ImGui::GetStyleColorName((ImGuiCol)i); ImVec2 p = ImGui::GetCursorScreenPos(); - ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x+sz, p.y+sz), ImGui::GetColorU32((ImGuiCol)i)); + ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i)); ImGui::Dummy(ImVec2(sz, sz)); ImGui::SameLine(); ImGui::MenuItem(name); @@ -4025,7 +4025,7 @@ struct ExampleAppConsole void Draw(const char* title, bool* p_open) { - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); if (!ImGui::Begin(title, p_open)) { ImGui::End(); @@ -4103,7 +4103,7 @@ struct ExampleAppConsole // If your items are of variable height: // - Split them into same height items would be simpler and facilitate random-seeking into your list. // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); for (int i = 0; i < Items.Size; i++) @@ -4163,7 +4163,7 @@ struct ExampleAppConsole // Insert into history. First find match and delete it so it can be pushed to the back. // This isn't trying to be smart or optimal. HistoryPos = -1; - for (int i = History.Size-1; i >= 0; i--) + for (int i = History.Size - 1; i >= 0; i--) if (Stricmp(History[i], command_line) == 0) { free(History[i]); @@ -4228,18 +4228,18 @@ struct ExampleAppConsole // Build a list of candidates ImVector candidates; for (int i = 0; i < Commands.Size; i++) - if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) + if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0) candidates.push_back(Commands[i]); if (candidates.Size == 0) { // No match - AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); + AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start); } else if (candidates.Size == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. - data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } @@ -4264,7 +4264,7 @@ struct ExampleAppConsole if (match_len > 0) { - data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); } @@ -4552,7 +4552,7 @@ static void ShowDummyObject(const char* prefix, int uid) ImGui::NextColumn(); if (node_open) { - static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + static float dummy_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; for (int i = 0; i < 8; i++) { ImGui::PushID(i); // Use field index as identifier. @@ -4584,7 +4584,7 @@ static void ShowDummyObject(const char* prefix, int uid) // Demonstrate create a simple property editor. static void ShowExampleAppPropertyEditor(bool* p_open) { - ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Example: Property editor", p_open)) { ImGui::End(); @@ -4597,7 +4597,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open) "Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\n" "your cursor horizontally instead of using the Columns() API."); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2)); ImGui::Columns(2); ImGui::Separator(); @@ -4618,7 +4618,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open) // Demonstrate/test rendering huge amount of text, and the incidence of clipping. static void ShowExampleAppLongText(bool* p_open) { - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); if (!ImGui::Begin("Example: Long text display", p_open)) { ImGui::End(); @@ -4639,7 +4639,7 @@ static void ShowExampleAppLongText(bool* p_open) if (ImGui::Button("Add 1000 lines")) { for (int i = 0; i < 1000; i++) - log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines+i); + log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i); lines += 1000; } ImGui::BeginChild("Log"); @@ -4996,7 +4996,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImVec2 window_size = ImGui::GetWindowSize(); ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); if (draw_bg) - ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10+4); + ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4); if (draw_fg) ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10); ImGui::EndTabItem(); @@ -5022,7 +5022,7 @@ struct MyDocument bool WantClose; // Set when the document ImVec4 Color; // An arbitrary variable associated to the document - MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f,1.0f,1.0f,1.0f)) + MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)) { Name = name; Open = OpenPrev = open; diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 49197277..87e59205 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -668,7 +668,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const ImVec2 opaque_uv = _Data->TexUvWhitePixel; int count = points_count; if (!closed) - count = points_count-1; + count = points_count - 1; const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) @@ -677,8 +677,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int idx_count = thick_line ? count*18 : count*12; - const int vtx_count = thick_line ? points_count*4 : points_count*3; + const int idx_count = thick_line ? count * 18 : count * 12; + const int vtx_count = thick_line ? points_count * 4 : points_count * 3; PrimReserve(idx_count, vtx_count); // Temporary buffer @@ -687,7 +687,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; float dx = points[i2].x - points[i1].x; float dy = points[i2].y - points[i1].y; IM_NORMALIZE2F_OVER_ZERO(dx, dy); @@ -695,7 +695,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_normals[i1].y = -dx; } if (!closed) - temp_normals[points_count-1] = temp_normals[points_count-2]; + temp_normals[points_count - 1] = temp_normals[points_count - 2]; if (!thick_line) { @@ -711,8 +711,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 unsigned int idx1 = _VtxCurrentIdx; for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; - unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -722,7 +722,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_y *= AA_SIZE; // Add temporary vertices - ImVec2* out_vtx = &temp_points[i2*2]; + 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; out_vtx[1].x = points[i2].x - dm_x; @@ -780,7 +780,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 float dm_in_y = dm_y * half_inner_thickness; // Add temporary vertices - ImVec2* out_vtx = &temp_points[i2*4]; + ImVec2* out_vtx = &temp_points[i2 * 4]; out_vtx[0].x = points[i2].x + dm_out_x; out_vtx[0].y = points[i2].y + dm_out_y; out_vtx[1].x = points[i2].x + dm_in_x; @@ -817,13 +817,13 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 else { // Non Anti-aliased Stroke - const int idx_count = count*6; - const int vtx_count = count*4; // FIXME-OPT: Not sharing edges + const int idx_count = count * 6; + const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); for (int i1 = 0; i1 < count; i1++) { - const int i2 = (i1+1) == points_count ? 0 : i1+1; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; const ImVec2& p1 = points[i1]; const ImVec2& p2 = points[i2]; @@ -860,22 +860,22 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun // Anti-aliased Fill const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int idx_count = (points_count-2)*3 + points_count*6; - const int vtx_count = (points_count*2); + const int idx_count = (points_count - 2)*3 + points_count * 6; + const int vtx_count = (points_count * 2); PrimReserve(idx_count, vtx_count); // Add indexes for fill unsigned int vtx_inner_idx = _VtxCurrentIdx; - unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + unsigned int vtx_outer_idx = _VtxCurrentIdx + 1; for (int i = 2; i < points_count; i++) { - _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1)); _IdxWritePtr += 3; } // Compute normals ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630 - for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { const ImVec2& p0 = points[i0]; const ImVec2& p1 = points[i1]; @@ -886,7 +886,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun temp_normals[i0].y = -dx; } - for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { // Average normals const ImVec2& n0 = temp_normals[i0]; @@ -903,8 +903,8 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun _VtxWritePtr += 2; // Add indexes for fringes - _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); - _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr += 6; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; @@ -912,7 +912,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun else { // Non Anti-aliased Fill - const int idx_count = (points_count-2)*3; + const int idx_count = (points_count - 2)*3; const int vtx_count = points_count; PrimReserve(idx_count, vtx_count); for (int i = 0; i < vtx_count; i++) @@ -922,7 +922,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun } for (int i = 2; i < points_count; i++) { - _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i); _IdxWritePtr += 3; } _VtxCurrentIdx += (ImDrawIdx)vtx_count; @@ -989,20 +989,20 @@ static void PathBezierToCasteljau(ImVector* path, float x1, float y1, fl float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; d3 = (d3 >= 0) ? d3 : -d3; - if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) { path->push_back(ImVec2(x4, y4)); } else if (level < 10) { - float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; - float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; - float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; - float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; - float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; - float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; - PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); - PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); + float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f; + float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f; + float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f; + float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f; + float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f; + float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f; + PathBezierToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); + PathBezierToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); } } @@ -1062,9 +1062,9 @@ void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, fl if ((col & IM_COL32_A_MASK) == 0) return; if (Flags & ImDrawListFlags_AntiAliasedLines) - PathRect(p_min + ImVec2(0.50f,0.50f), p_max - ImVec2(0.50f,0.50f), rounding, rounding_corners); + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, rounding_corners); else - PathRect(p_min + ImVec2(0.50f,0.50f), p_max - ImVec2(0.49f,0.49f), rounding, rounding_corners); // Better looking lower-right corner and rounded non-AA shapes. + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, rounding_corners); // Better looking lower-right corner and rounded non-AA shapes. PathStroke(col, true, thickness); } @@ -1092,8 +1092,8 @@ void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_ma const ImVec2 uv = _Data->TexUvWhitePixel; PrimReserve(6, 4); - PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); - PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 3)); PrimWriteVtx(p_min, uv, col_upr_left); PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right); PrimWriteVtx(p_max, uv, col_bot_right); @@ -1787,15 +1787,15 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) } // Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder) -static unsigned int stb_decompress_length(const unsigned char *input); -static unsigned int stb_decompress(unsigned char *output, const unsigned char *input, unsigned int length); +static unsigned int stb_decompress_length(const unsigned char* input); +static unsigned int stb_decompress(unsigned char* output, const unsigned char* input, unsigned int length); static const char* GetDefaultCompressedFontDataTTFBase85(); static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } static void Decode85(const unsigned char* src, unsigned char* dst) { while (*src) { - unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4])))); dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. src += 5; dst += 4; @@ -1862,7 +1862,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float si ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data); - unsigned char* buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size); + unsigned char* buf_decompressed_data = (unsigned char*)IM_ALLOC(buf_decompressed_size); stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); @@ -2149,7 +2149,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) 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; + 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). @@ -2262,7 +2262,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->CustomRectIds[0] >= 0) return; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); else atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(2, 2); } @@ -2712,7 +2712,7 @@ void ImFont::BuildLookupTable() tab_glyph.Codepoint = '\t'; tab_glyph.AdvanceX *= IM_TABSIZE; IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX; - IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size-1); + IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size - 1); } // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons) @@ -3207,7 +3207,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col // 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); - draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); draw_list->_VtxWritePtr = vtx_write; draw_list->_IdxWritePtr = idx_write; draw_list->_VtxCurrentIdx = vtx_current_idx; @@ -3293,10 +3293,10 @@ void ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, Im pos -= offset; const 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)*scale + size*scale, uv[2], uv[3], col_shadow); - draw_list->AddImage(tex_id, pos + ImVec2(2,0)*scale, pos + ImVec2(2,0)*scale + 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); + 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); draw_list->PopTextureID(); } } @@ -3551,7 +3551,7 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i // Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding). // The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size. //----------------------------------------------------------------------------- -static const char proggy_clean_ttf_compressed_data_base85[11980+1] = +static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] = "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a 1.0f) ? 1.0f : f; } -static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } -static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } -static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; } +static inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } +static inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } +static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; } static inline float ImFloor(float f) { return (float)(int)(f); } static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } static inline int ImModPositive(int a, int b) { return (a + b) % b; } @@ -1315,7 +1315,7 @@ struct ImGuiContext int WantCaptureMouseNextFrame; // Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags int WantCaptureKeyboardNextFrame; int WantTextInputNextFrame; - char TempBuffer[1024*3+1]; // Temporary text buffer + char TempBuffer[1024 * 3 + 1]; // Temporary text buffer ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(&DrawListSharedData), ForegroundDrawList(&DrawListSharedData) { @@ -1355,7 +1355,7 @@ struct ImGuiContext ActiveIdUsingNavDirMask = 0x00; ActiveIdUsingNavInputMask = 0x00; ActiveIdUsingKeyInputMask = 0x00; - ActiveIdClickOffset = ImVec2(-1,-1); + ActiveIdClickOffset = ImVec2(-1, -1); ActiveIdWindow = NULL; ActiveIdSource = ImGuiInputSource_None; ActiveIdMouseButton = 0; @@ -1650,7 +1650,7 @@ public: ImGuiID GetIDFromRectangle(const ImRect& r_abs); // We don't use g.FontSize because the window may be != g.CurrentWidow. - ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; } ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } @@ -1956,7 +1956,7 @@ namespace ImGui IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); IMGUI_API void Scrollbar(ImGuiAxis axis); IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float avail_v, float contents_v, ImDrawCornerFlags rounding_corners); - IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col); + IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col); IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowResizeID(ImGuiWindow* window, int n); // 0..3: corners, 4..7: borders diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 918dbf94..7d6bf847 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -160,7 +160,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop. const char* line = text; const float line_height = GetTextLineHeight(); - ImVec2 text_size(0,0); + ImVec2 text_size(0, 0); // Lines to skip (can't skip when logging text) ImVec2 pos = text_pos; @@ -332,8 +332,8 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); - const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); + const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2)); + const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y * 2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, 0)) return; @@ -341,7 +341,7 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) // Render const char* value_text_begin = &g.TempBuffer[0]; const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); - RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); + RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f, 0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } @@ -377,7 +377,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // Render ImU32 text_col = GetColorU32(ImGuiCol_Text); - RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, g.FontSize*0.5f), text_col); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col); RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false); } @@ -781,8 +781,8 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size) float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; ImU32 cross_col = GetColorU32(ImGuiCol_Text); center -= ImVec2(0.5f, 0.5f); - window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f); - window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f); + window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f); + window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f); return pressed; } @@ -1067,7 +1067,7 @@ bool ImGui::Checkbox(const char* label, bool* v) else if (*v) { const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f)); - RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad*2.0f); + RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f); } if (g.LogEnabled) @@ -1133,7 +1133,7 @@ bool ImGui::RadioButton(const char* label, bool active) if (style.FrameBorderSize > 0.0f) { - window->DrawList->AddCircle(center + ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); + window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize); } @@ -1166,7 +1166,7 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over const ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; - ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f); ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, 0)) @@ -1183,13 +1183,13 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over char overlay_buf[32]; if (!overlay) { - ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f); overlay = overlay_buf; } ImVec2 overlay_size = CalcTextSize(overlay, NULL); if (overlay_size.x > 0.0f) - RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb); } void ImGui::Bullet() @@ -1200,18 +1200,18 @@ void ImGui::Bullet() ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); ItemSize(bb); if (!ItemAdd(bb, 0)) { - SameLine(0, style.FramePadding.x*2); + SameLine(0, style.FramePadding.x * 2); return; } // Render and stay on same line ImU32 text_col = GetColorU32(ImGuiCol_Text); - RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col); + RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col); SameLine(0, style.FramePadding.x * 2.0f); } @@ -1484,7 +1484,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const ImVec2 label_size = CalcTextSize(label, NULL, true); const float expected_w = CalcItemWidth(); const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : expected_w; - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb)) @@ -1509,7 +1509,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF } RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding); if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) - RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), preview_value, NULL, NULL, ImVec2(0.0f,0.0f)); + RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), preview_value, NULL, NULL, ImVec2(0.0f, 0.0f)); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -2011,7 +2011,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings float adjust_delta = 0.0f; - if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f) + if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f * 1.0f) { adjust_delta = g.IO.MouseDelta[axis]; if (g.IO.KeyAlt) @@ -2148,7 +2148,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); @@ -2369,12 +2369,12 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m if (v_clamped < 0.0f) { const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min)); - return (1.0f - ImPow(f, 1.0f/power)) * linear_zero_pos; + return (1.0f - ImPow(f, 1.0f / power)) * linear_zero_pos; } else { const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min))); - return linear_zero_pos + ImPow(f, 1.0f/power) * (1.0f - linear_zero_pos); + return linear_zero_pos + ImPow(f, 1.0f / power) * (1.0f - linear_zero_pos); } } @@ -2450,7 +2450,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if ((decimal_precision > 0) || is_power) { @@ -2522,7 +2522,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } // Round to user desired precision based on format string - v_new = RoundScalarWithFormatT(format, data_type, v_new); + v_new = RoundScalarWithFormatT(format, data_type, v_new); // Apply result if (*v != v_new) @@ -2565,23 +2565,23 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } case ImGuiDataType_S32: - IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN/2 && *(const ImS32*)p_max <= IM_S32_MAX/2); + IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_U32: - IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX/2); + IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_S64: - IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN/2 && *(const ImS64*)p_max <= IM_S64_MAX/2); + IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_U64: - IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX/2); + IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2); return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_Float: - IM_ASSERT(*(const float*)p_min >= -FLT_MAX/2.0f && *(const float*)p_max <= FLT_MAX/2.0f); + IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f); return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_Double: - IM_ASSERT(*(const double*)p_min >= -DBL_MAX/2.0f && *(const double*)p_max <= DBL_MAX/2.0f); - return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, power, flags, out_grab_bb); + IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f); + return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, power, flags, out_grab_bb); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); @@ -2602,7 +2602,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); @@ -2659,7 +2659,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); - RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -2728,9 +2728,9 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl { if (format == NULL) format = "%.0f deg"; - float v_deg = (*v_rad) * 360.0f / (2*IM_PI); + float v_deg = (*v_rad) * 360.0f / (2 * IM_PI); bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); - *v_rad = v_deg * (2*IM_PI) / 360.0f; + *v_rad = v_deg * (2 * IM_PI) / 360.0f; return value_changed; } @@ -2806,7 +2806,7 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format); - RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -3097,7 +3097,7 @@ bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_dat bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) { flags |= ImGuiInputTextFlags_CharsScientific; - return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), format, flags); + return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags); } bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags) @@ -3154,7 +3154,7 @@ bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiIn { // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; - return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), format, flags); + return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags); } bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) @@ -3175,7 +3175,7 @@ bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) { flags |= ImGuiInputTextFlags_CharsScientific; - return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), format, flags); + return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags); } //------------------------------------------------------------------------- @@ -3286,10 +3286,10 @@ static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* ob } static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } -static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->TextW[idx-1] ) && !is_separator( obj->TextW[idx] ) ) : 1; } +static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator(obj->TextW[idx - 1]) && !is_separator(obj->TextW[idx]) ) : 1; } static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } #ifdef __APPLE__ // FIXME: Move setting to IO structure -static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; } +static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator(obj->TextW[idx - 1]) && is_separator(obj->TextW[idx]) ) : 1; } static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } #else static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } @@ -3495,7 +3495,7 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f // Turn a-z into A-Z if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') - *p_char = (c += (unsigned int)('A'-'a')); + *p_char = (c += (unsigned int)('A' - 'a')); if (flags & ImGuiInputTextFlags_CharsNoBlank) if (ImCharIsBlankW(c)) @@ -3556,7 +3556,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ BeginGroup(); const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y * 2.0f); // Arbitrary default of 8 lines high for multi-line const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); @@ -3746,7 +3746,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Edit in progress const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX; - const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); + const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize * 0.5f)); const bool is_osx = io.ConfigMacOSXBehaviors; if (select_all || (hovered && !is_osx && io.MouseDoubleClicked[0])) @@ -3842,9 +3842,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (!state->HasSelection()) { if (is_wordmove_key_down) - state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); + state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT); else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) - state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); + state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT); } state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } @@ -3903,7 +3903,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { // Filter pasted buffer const int clipboard_len = (int)strlen(clipboard); - ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len+1) * sizeof(ImWchar)); + ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len + 1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) { @@ -4235,7 +4235,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); if (rect_size.x <= 0.0f) rect_size.x = IM_FLOOR(g.Font->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)); + 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)) draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); @@ -4406,8 +4406,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders - const float w_item_one = ImMax(1.0f, IM_FLOOR((w_inputs - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, IM_FLOOR(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + const float w_item_one = ImMax(1.0f, IM_FLOOR((w_inputs - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); + const float w_item_last = ImMax(1.0f, IM_FLOOR(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; @@ -4434,7 +4434,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. if (flags & ImGuiColorEditFlags_Float) { - value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); + value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); value_changed_as_float |= value_changed; } else @@ -4450,9 +4450,9 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // RGB Hexadecimal Input char buf[64]; if (alpha) - ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255)); + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255)); else - ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255)); + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255)); SetNextItemWidth(w_inputs); if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { @@ -4484,7 +4484,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag // Store current color and open a picker g.ColorPickerRef = col_v4; OpenPopup("picker"); - SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y)); + SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1, style.ItemSpacing.y)); } } if (!(flags & ImGuiColorEditFlags_NoOptions)) @@ -4645,7 +4645,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl float wheel_thickness = sv_picker_size * 0.08f; float wheel_r_outer = sv_picker_size * 0.50f; float wheel_r_inner = wheel_r_outer - wheel_thickness; - ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f); + ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f); // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic. float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f); @@ -4684,10 +4684,10 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center; ImVec2 current_off = g.IO.MousePos - wheel_center; float initial_dist2 = ImLengthSqr(initial_off); - if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1)) + if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1)) { // Interactive with Hue wheel - H = ImAtan2(current_off.y, current_off.x) / IM_PI*0.5f; + H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f; if (H < 0.0f) H += 1.0f; value_changed = value_changed_h = true; @@ -4716,8 +4716,8 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size)); if (IsItemActive()) { - S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1)); - V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1)); + V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); value_changed = value_changed_sv = true; } if (!(flags & ImGuiColorEditFlags_NoOptions)) @@ -4728,7 +4728,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl InvisibleButton("hue", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { - H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); value_changed = value_changed_h = true; } } @@ -4740,7 +4740,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { - col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); + col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1)); value_changed = true; } } @@ -4791,7 +4791,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl { if (flags & ImGuiColorEditFlags_InputRGB) { - ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]); + ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10 * 1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]); g.ColorEditLastHue = H; g.ColorEditLastSat = S; memcpy(g.ColorEditLastColor, col, sizeof(float) * 3); @@ -4894,17 +4894,17 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // Paint colors over existing vertices ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner); ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner); - ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n+1]); + ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1]); } // Render Cursor + preview on Hue Wheel float cos_hue_angle = ImCos(H * 2.0f * IM_PI); float sin_hue_angle = ImSin(H * 2.0f * IM_PI); - ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f); + ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f); float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f; int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32); draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments); - draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, col_midgrey, hue_cursor_segments); + draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments); draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments); // Render SV triangle (rotated according to hue) @@ -4942,7 +4942,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f; draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, 12); - draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, col_midgrey, 12); + draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, 12); draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, 12); // Render alpha bar @@ -5014,8 +5014,8 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) { float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f); - RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight); - window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft); + RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight); + window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft); } else { @@ -5133,7 +5133,7 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) if (allow_opt_inputs || allow_opt_datatype) Separator(); - if (Button("Copy as..", ImVec2(-1,0))) + if (Button("Copy as..", ImVec2(-1, 0))) OpenPopup("Copy"); if (BeginPopup("Copy")) { @@ -5177,7 +5177,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl // Draw small/thumbnail version of each picker type (over an invisible button for selection) if (picker_type > 0) Separator(); PushID(picker_type); - ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha); + ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha); if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar; if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel; ImVec2 backup_pos = GetCursorScreenPos(); @@ -5361,7 +5361,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l const ImVec2 label_size = CalcTextSize(label, label_end, false); // We vertically grow up to current line height up the typical widget height. - const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2); ImRect frame_bb; frame_bb.Min.x = (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x; frame_bb.Min.y = window->DC.CursorPos.y; @@ -5375,9 +5375,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l frame_bb.Max.x += IM_FLOOR(window->WindowPadding.x * 0.5f); } - const float text_offset_x = g.FontSize + (display_frame ? padding.x*3 : padding.x*2); // Collapser arrow width + Spacing + const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapser arrow width + Spacing const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it - const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x * 2 : 0.0f); // Include collapser ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y); ItemSize(ImVec2(text_width, frame_height), padding.y); @@ -5511,9 +5511,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. const char log_prefix[] = "\n##"; const char log_suffix[] = "##"; - LogRenderedText(&text_pos, log_prefix, log_prefix+3); + LogRenderedText(&text_pos, log_prefix, log_prefix + 3); RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); - LogRenderedText(&text_pos, log_suffix, log_suffix+2); + LogRenderedText(&text_pos, log_suffix, log_suffix + 2); } else { @@ -5988,7 +5988,7 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) - SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1); else if (plot_type == ImGuiPlotType_Histogram) SetTooltip("%d: %8.4g", v_idx, v0); idx_hovered = v_idx; @@ -6034,7 +6034,7 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get // Text overlay if (overlay_text) - RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f, 0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); @@ -7538,7 +7538,7 @@ void ImGui::SetColumnOffset(int column_index, float offset) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); - const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1); + const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count - 1); const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) diff --git a/misc/fonts/binary_to_compressed_c.cpp b/misc/fonts/binary_to_compressed_c.cpp index 4c6f1200..1f621e16 100644 --- a/misc/fonts/binary_to_compressed_c.cpp +++ b/misc/fonts/binary_to_compressed_c.cpp @@ -28,7 +28,7 @@ // stb_compress* from stb.h - declaration typedef unsigned int stb_uint; typedef unsigned char stb_uchar; -stb_uint stb_compress(stb_uchar *out,stb_uchar *in,stb_uint len); +stb_uint stb_compress(stb_uchar* out, stb_uchar* in, stb_uint len); static bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression); @@ -54,7 +54,7 @@ int main(int argc, char** argv) } } - bool ret = binary_to_compressed_c(argv[argn], argv[argn+1], use_base85_encoding, use_compression); + bool ret = binary_to_compressed_c(argv[argn], argv[argn + 1], use_base85_encoding, use_compression); if (!ret) fprintf(stderr, "Error opening or reading file: '%s'\n", argv[argn]); return ret ? 0 : 1; @@ -63,7 +63,7 @@ int main(int argc, char** argv) char Encode85Byte(unsigned int x) { x = (x % 85) + 35; - return (x>='\\') ? x+1 : x; + return (x >= '\\') ? x + 1 : x; } bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression) @@ -73,7 +73,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b if (!f) return false; int data_sz; if (fseek(f, 0, SEEK_END) || (data_sz = (int)ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return false; } - char* data = new char[data_sz+4]; + char* data = new char[data_sz + 4]; if (fread(data, 1, data_sz, f) != (size_t)data_sz) { fclose(f); delete[] data; return false; } memset((void*)(((char*)data) + data_sz), 0, 4); fclose(f); @@ -83,16 +83,16 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b char* compressed = use_compression ? new char[maxlen] : data; int compressed_sz = use_compression ? stb_compress((stb_uchar*)compressed, (stb_uchar*)data, data_sz) : data_sz; if (use_compression) - memset(compressed + compressed_sz, 0, maxlen - compressed_sz); + memset(compressed + compressed_sz, 0, maxlen - compressed_sz); // Output as Base85 encoded FILE* out = stdout; fprintf(out, "// File: '%s' (%d bytes)\n", filename, (int)data_sz); fprintf(out, "// Exported using binary_to_compressed_c.cpp\n"); - const char* compressed_str = use_compression ? "compressed_" : ""; + const char* compressed_str = use_compression ? "compressed_" : ""; if (use_base85_encoding) { - fprintf(out, "static const char %s_%sdata_base85[%d+1] =\n \"", symbol, compressed_str, (int)((compressed_sz+3)/4)*5); + fprintf(out, "static const char %s_%sdata_base85[%d+1] =\n \"", symbol, compressed_str, (int)((compressed_sz + 3) / 4)*5); char prev_c = 0; for (int src_i = 0; src_i < compressed_sz; src_i += 4) { @@ -104,7 +104,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b fprintf(out, (c == '?' && prev_c == '?') ? "\\%c" : "%c", c); prev_c = c; } - if ((src_i % 112) == 112-4) + if ((src_i % 112) == 112 - 4) fprintf(out, "\"\n \""); } fprintf(out, "\";\n\n"); @@ -112,7 +112,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b else { fprintf(out, "static const unsigned int %s_%ssize = %d;\n", symbol, compressed_str, (int)compressed_sz); - fprintf(out, "static const unsigned int %s_%sdata[%d/4] =\n{", symbol, compressed_str, (int)((compressed_sz+3)/4)*4); + fprintf(out, "static const unsigned int %s_%sdata[%d/4] =\n{", symbol, compressed_str, (int)((compressed_sz + 3) / 4)*4); int column = 0; for (int i = 0; i < compressed_sz; i += 4) { @@ -128,7 +128,7 @@ bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_b // Cleanup delete[] data; if (use_compression) - delete[] compressed; + delete[] compressed; return true; } diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 20a3be0e..b76bc6e0 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -13,7 +13,7 @@ // - v0.60: (2019/01/10) re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding. // - v0.61: (2019/01/15) added support for imgui allocators + added FreeType only override function SetAllocatorFunctions(). // - v0.62: (2019/02/09) added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!) -// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. +// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails. // Gamma Correct Blending: // FreeType assumes blending in linear space rather than gamma space. @@ -502,7 +502,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns 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; + 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). @@ -609,8 +609,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns } // Default memory allocators -static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); } -static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); } +static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); } +static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); } // Current memory allocators static void* (*GImFreeTypeAllocFunc)(size_t size, void* user_data) = ImFreeTypeDefaultAllocFunc; From ab4ef822f0e85a6dd65723db9e0e632a1e1a45d8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 16:56:09 +0200 Subject: [PATCH 122/959] Version 1.78 WIP --- docs/CHANGELOG.txt | 5 +++++ examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 14 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4d757e0b..c62a140d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -31,6 +31,11 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.78 WIP (In Progress) +----------------------------------------------------------------------- + + ----------------------------------------------------------------------- VERSION 1.77 (Released 2020-06-29) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 2137fe09..35ee87b9 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.77 + dear imgui, v1.78 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 295cb054..d8bf40be 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 724aa289..dc4fa453 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (headers) // Help: @@ -59,8 +59,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.77" -#define IMGUI_VERSION_NUM 17701 +#define IMGUI_VERSION "1.78 WIP" +#define IMGUI_VERSION_NUM 17702 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e0fc9af7..a2208ebe 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 87e59205..ade1290d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index f55a061b..b57b01b5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7d6bf847..86295bcd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.77 +// dear imgui, v1.78 WIP // (widgets code) /* From 2b9d88196e76c988bc28e615aa4fe12dc51c8fc8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 18:52:02 +0200 Subject: [PATCH 123/959] Docking: Rework size allocations to recover when there's no enough room for nodes + do not hold on WantLockSizeOnce forever (#3328) (Ensure if the fact that WantLockSizeOnce was kept when only 1 child is visible was desired/desirable) --- imgui.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cf5f13b5..3936fd32 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13793,16 +13793,14 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si IM_ASSERT(!(child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)); if (child_0->WantLockSizeOnce) { - child_0->WantLockSizeOnce = false; - child_0_size[axis] = child_0->SizeRef[axis] = child_0->Size[axis]; + child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]); child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } else if (child_1->WantLockSizeOnce) { - child_1->WantLockSizeOnce = false; - child_1_size[axis] = child_1->SizeRef[axis] = child_1->Size[axis]; + child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]); child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]); IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } @@ -13825,8 +13823,11 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5F)); child_1_size[axis] = (size_avail - child_0_size[axis]); } + child_1_pos[axis] += spacing + child_0_size[axis]; } + child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false; + if (child_0->IsVisible) DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size); if (child_1->IsVisible) @@ -15584,7 +15585,12 @@ void ImGui::ShowMetricsWindow(bool* p_open) NodeWindow(node->HostWindow, "HostWindow"); NodeWindow(node->VisibleWindow, "VisibleWindow"); ImGui::BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId); - ImGui::BulletText("Misc:%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : ""); + ImGui::BulletText("Misc:%s%s%s%s%s", + node->IsDockSpace() ? " IsDockSpace" : "", + node->IsCentralNode() ? " IsCentralNode" : "", + (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", + (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : "", + node->WantLockSizeOnce ? " WantLockSizeOnce" : ""); if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) { ImGui::CheckboxFlags("LocalFlags: NoDocking", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoDocking); From 4bdbea8375557fcd3c8b46abde7cc0119c2c57d4 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 18:53:13 +0200 Subject: [PATCH 124/959] Docking: Rework size allocation to allow user code to override node sizes. Not all edge cases will be properly handled but this is a step toward toolbar emitting size constraints. --- imgui.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3936fd32..efcfc3c5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13790,20 +13790,27 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f); // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) - IM_ASSERT(!(child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)); - if (child_0->WantLockSizeOnce) + if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce) { child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]); child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); - } - else if (child_1->WantLockSizeOnce) + else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce) { child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]); child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]); IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } + else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce) + { + // FIXME-DOCK: We cannot honor the requested size, so apply ratio. + // Currently this path will only be taken if code programmatically sets WantLockSizeOnce + float ratio_0 = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]); + child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * ratio_0); + child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); + IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); + } // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node else if (child_1->IsCentralNode() && child_0->SizeRef[axis] != 0.0f) From a1d2c6fad96ec7a3e444094a1522dc1796ab68fe Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 30 Jun 2020 19:00:31 +0200 Subject: [PATCH 125/959] Fixed invalid comment (#3327) --- imgui.h | 2 +- imgui_demo.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index dc4fa453..2da0d21a 100644 --- a/imgui.h +++ b/imgui.h @@ -740,7 +740,7 @@ namespace ImGui IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held? IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down) IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) - IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. + IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? (note that a double-click will also report IsMouseClicked() == true) IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available IMGUI_API bool IsAnyMouseDown(); // is any mouse button held? diff --git a/imgui_demo.cpp b/imgui_demo.cpp index a2208ebe..ed38e52f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3224,7 +3224,7 @@ static void ShowDemoWindowMisc() ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y); ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } - ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } ImGui::Text("Mouse wheel: %.1f", io.MouseWheel); From fc9d6b6cb5956eb5a07e09c1d5e4685b1037109e Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 29 Nov 2019 17:52:30 +0100 Subject: [PATCH 126/959] Docking: Added experimental flags to perform more docking filtering and disable resize per axis. Designed for toolbar patterns. The local/shared flags specs, saving and inheriting rules are pretty inconsistent at the moment. --- imgui.cpp | 19 ++++++++++++++----- imgui.h | 2 +- imgui_internal.h | 11 +++++++++-- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index efcfc3c5..08fbff28 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13486,22 +13486,27 @@ static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockN IM_ASSERT(ref_node_for_rect->IsVisible); // Filter, figure out where we are allowed to dock - ImGuiDockNodeFlags host_node_flags = host_node ? host_node->GetMergedFlags() : 0; + ImGuiDockNodeFlags src_node_flags = root_payload_as_host ? root_payload_as_host->GetMergedFlags() : root_payload->WindowClass.DockNodeFlagsOverrideSet; + ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->GetMergedFlags() : host_window->WindowClass.DockNodeFlagsOverrideSet; data->IsCenterAvailable = true; if (is_outer_docking) data->IsCenterAvailable = false; - else if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDocking)) + else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking) data->IsCenterAvailable = false; - else if (host_node && (host_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode()) + else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode()) data->IsCenterAvailable = false; else if ((!host_node || !host_node->IsEmpty()) && root_payload_as_host && root_payload_as_host->IsSplitNode() && (root_payload_as_host->OnlyNodeWithWindows == NULL)) // Is _visibly_ split? data->IsCenterAvailable = false; + else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther)) + data->IsCenterAvailable = false; data->IsSidesAvailable = true; - if ((host_node && (host_node_flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) + if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit) data->IsSidesAvailable = false; else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode()) data->IsSidesAvailable = false; + else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)) + data->IsSidesAvailable = false; // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton); @@ -13877,7 +13882,9 @@ void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) bb.Max[axis ^ 1] += child_1->Size[axis ^ 1]; //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)); - if ((child_0->GetMergedFlags() | child_1->GetMergedFlags()) & ImGuiDockNodeFlags_NoResize) + const ImGuiDockNodeFlags merged_flags = child_0->GetMergedFlags() | child_1->GetMergedFlags(); + const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY; + if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag)) { ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding); @@ -15603,6 +15610,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::CheckboxFlags("LocalFlags: NoDocking", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoDocking); ImGui::CheckboxFlags("LocalFlags: NoSplit", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoSplit); ImGui::CheckboxFlags("LocalFlags: NoResize", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResize); + ImGui::CheckboxFlags("LocalFlags: NoResizeX", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResizeX); + ImGui::CheckboxFlags("LocalFlags: NoResizeY", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoResizeY); ImGui::CheckboxFlags("LocalFlags: NoTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoTabBar); ImGui::CheckboxFlags("LocalFlags: HiddenTabBar", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); ImGui::CheckboxFlags("LocalFlags: NoWindowMenuButton", (ImU32*)&node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton); diff --git a/imgui.h b/imgui.h index d91a343f..233d2841 100644 --- a/imgui.h +++ b/imgui.h @@ -1739,7 +1739,7 @@ struct ImGuiWindowClass ImGuiDockNodeFlags DockNodeFlagsOverrideSet; // [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) ImGuiDockNodeFlags DockNodeFlagsOverrideClear; // [EXPERIMENTAL] bool DockingAlwaysTabBar; // Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) - bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. + bool DockingAllowUnclassed; // Set to true to allow windows of this class to be docked/merged with an unclassed window. // FIXME-DOCK: Move to DockNodeFlags override? ImGuiWindowClass() { ClassId = 0; ParentViewportId = 0; ViewportFlagsOverrideSet = ViewportFlagsOverrideClear = 0x00; DockNodeFlagsOverrideSet = DockNodeFlagsOverrideClear = 0x00; DockingAlwaysTabBar = false; DockingAllowUnclassed = true; } }; diff --git a/imgui_internal.h b/imgui_internal.h index 16b41d11..3934034b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1086,10 +1086,17 @@ enum ImGuiDockNodeFlagsPrivate_ ImGuiDockNodeFlags_NoWindowMenuButton = 1 << 14, // Local, Saved // Disable window/docking menu (that one that appears instead of the collapse button) ImGuiDockNodeFlags_NoCloseButton = 1 << 15, // Local, Saved // ImGuiDockNodeFlags_NoDocking = 1 << 16, // Local, Saved // Disable any form of docking in this dockspace or individual node. (On a whole dockspace, this pretty much defeat the purpose of using a dockspace at all). Note: when turned on, existing docked nodes will be preserved. + ImGuiDockNodeFlags_NoDockingSplitMe = 1 << 17, // [EXPERIMENTAL] Prevent another window/node from splitting this node. + ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 18, // [EXPERIMENTAL] Prevent this node from splitting another window/node. + ImGuiDockNodeFlags_NoDockingOverMe = 1 << 19, // [EXPERIMENTAL] Prevent another window/node to be docked over this node. + ImGuiDockNodeFlags_NoDockingOverOther = 1 << 20, // [EXPERIMENTAL] Prevent this node to be docked over another window/node. + ImGuiDockNodeFlags_NoResizeX = 1 << 21, // [EXPERIMENTAL] + ImGuiDockNodeFlags_NoResizeY = 1 << 22, // [EXPERIMENTAL] ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, - ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking, + ImGuiDockNodeFlags_NoResizeFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, + ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking, ImGuiDockNodeFlags_LocalFlagsTransferMask_ = ImGuiDockNodeFlags_LocalFlagsMask_ & ~ImGuiDockNodeFlags_DockSpace, // When splitting those flags are moved to the inheriting child, never duplicated - ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking + ImGuiDockNodeFlags_SavedFlagsMask_ = ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking }; // Store the source authority (dock node vs window) of a field From 4f5aac319e3561284833db90f35d218de8b282c1 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 Jul 2020 15:51:05 +0200 Subject: [PATCH 127/959] Docking: moved local-ish IMGUI_DOCK_SPLITTER_SIZE to DOCKING_SPLITTER_SIZE at the top of the file. --- imgui.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 08fbff28..7b31979c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -811,6 +811,7 @@ static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock // Docking static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport. +static const float DOCKING_SPLITTER_SIZE = 2.0f; //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS @@ -11602,8 +11603,6 @@ void ImGui::DestroyPlatformWindows() // - ImGuiDockContext //----------------------------------------------------------------------------- -static float IMGUI_DOCK_SPLITTER_SIZE = 2.0f; - enum ImGuiDockRequestType { ImGuiDockRequestType_None = 0, @@ -13697,7 +13696,7 @@ void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImG parent_node->VisibleWindow = NULL; parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode; - float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE); + float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE); size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f); IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. child_0->SizeRef = child_1->SizeRef = parent_node->Size; @@ -13785,7 +13784,7 @@ void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 si ImVec2 child_0_size = size, child_1_size = size; if (child_0->IsVisible && child_1->IsVisible) { - const float spacing = IMGUI_DOCK_SPLITTER_SIZE; + const float spacing = DOCKING_SPLITTER_SIZE; const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; const float size_avail = ImMax(size[axis] - spacing, 0.0f); From 0d03e1fafafb8d1cebcb6268b3a8014dff08d97c Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Tue, 7 Jul 2020 12:49:25 +0300 Subject: [PATCH 128/959] CI: Fix emscripten builds that broke due behavior change of emscripten SDK. --- .github/workflows/build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8edef47b..b3b910f2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -394,7 +394,9 @@ jobs: - name: Build example_emscripten run: | - source emsdk-master/emsdk_env.sh + pushd emsdk-master + source ./emsdk_env.sh + popd make -C examples/example_emscripten Static-Analysis: From 8e4046e13ba3642de7aa5e2795021c035259f710 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Wed, 8 Jul 2020 17:17:52 +0200 Subject: [PATCH 129/959] Atlas build use GetCustomRectByIndex() + comments, rename, and shallow merge from tex_antialiasing_lines branch. --- imgui.cpp | 4 +- imgui.h | 25 ++++++------ imgui_demo.cpp | 1 + imgui_draw.cpp | 101 +++++++++++++++++++++++++++---------------------- 4 files changed, 72 insertions(+), 59 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d8bf40be..d09d61ed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -934,8 +934,8 @@ ImGuiStyle::ImGuiStyle() DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. - AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. diff --git a/imgui.h b/imgui.h index 2da0d21a..adb2ab1c 100644 --- a/imgui.h +++ b/imgui.h @@ -151,7 +151,7 @@ typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect(), AddRectFilled() etc. typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList -typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas +typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags @@ -1438,8 +1438,8 @@ struct ImGuiStyle ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. - bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. ImVec4 Colors[ImGuiCol_COUNT]; @@ -1994,10 +1994,10 @@ enum ImDrawCornerFlags_ enum ImDrawListFlags_ { - ImDrawListFlags_None = 0, - ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles) - ImDrawListFlags_AntiAliasedFill = 1 << 1, // Filled shapes have anti-aliased edges (*2 the number of vertices) - ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). + ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; // Draw command list @@ -2211,11 +2211,12 @@ struct ImFontAtlasCustomRect bool IsPacked() const { return X != 0xFFFF; } }; +// Flags for ImFontAtlas build enum ImFontAtlasFlags_ { ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two - ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas + ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas (save a little texture memory) }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2289,7 +2290,7 @@ struct ImFontAtlas // 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)); - const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } + 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; @@ -2315,8 +2316,10 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel 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 ConfigData; // Internal data - int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList + ImVector ConfigData; // Configuration data + + // [Internal] Packing data + int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index ed38e52f..b481c305 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -405,6 +405,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly); ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor); ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something)."); + ImGui::Text("Also see Style->Rendering for rendering options."); ImGui::TreePop(); ImGui::Separator(); } diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ade1290d..30b9b9fe 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -666,11 +666,9 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 return; const ImVec2 opaque_uv = _Data->TexUvWhitePixel; - int count = points_count; - if (!closed) - count = points_count - 1; - + const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw const bool thick_line = (thickness > 1.0f); + if (Flags & ImDrawListFlags_AntiAliasedLines) { // Anti-aliased stroke @@ -682,9 +680,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 PrimReserve(idx_count, vtx_count); // Temporary buffer + // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; + // Calculate normals (tangents) for each line segment for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; @@ -707,12 +707,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; } + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. - unsigned int idx1 = _VtxCurrentIdx; - for (int i1 = 0; i1 < count; i1++) + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; - unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; + const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -721,14 +723,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 dm_x *= AA_SIZE; dm_y *= AA_SIZE; - // Add temporary vertices + // Add temporary vertexes 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; out_vtx[1].x = points[i2].x - dm_x; out_vtx[1].y = points[i2].y - dm_y; - // Add indexes + // Add indexes for four triangles _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); @@ -738,7 +740,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 idx1 = idx2; } - // Add vertices + // Add vertexes for each point on the line for (int i = 0; i < points_count; i++) { _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; @@ -749,7 +751,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { + // Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) { const int points_last = points_count - 1; @@ -763,9 +768,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); } + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. - unsigned int idx1 = _VtxCurrentIdx; - for (int i1 = 0; i1 < count; i1++) + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment @@ -816,7 +823,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { - // Non Anti-aliased Stroke + // Non texture-based, Non anti-aliased lines const int idx_count = count * 6; const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); @@ -1656,8 +1663,7 @@ ImFontAtlas::ImFontAtlas() TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); - for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) - CustomRectIds[n] = -1; + PackIdMouseCursors = -1; } ImFontAtlas::~ImFontAtlas() @@ -1685,8 +1691,7 @@ void ImFontAtlas::ClearInputData() } ConfigData.clear(); CustomRects.clear(); - for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++) - CustomRectIds[n] = -1; + PackIdMouseCursors = -1; } void ImFontAtlas::ClearTexData() @@ -1926,9 +1931,9 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou if (Flags & ImFontAtlasFlags_NoMouseCursors) return false; - IM_ASSERT(CustomRectIds[0] != -1); - ImFontAtlasCustomRect& r = CustomRects[CustomRectIds[0]]; - ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y); + IM_ASSERT(PackIdMouseCursors != -1); + ImFontAtlasCustomRect* r = GetCustomRectByIndex(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]; @@ -2256,17 +2261,6 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) return true; } -// Register default custom rectangles (this is called/shared by both the stb_truetype and the FreeType builder) -void ImFontAtlasBuildInit(ImFontAtlas* atlas) -{ - if (atlas->CustomRectIds[0] >= 0) - return; - if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - else - atlas->CustomRectIds[0] = atlas->AddCustomRectRegular(2, 2); -} - void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) { if (!font_config->MergeMode) @@ -2310,20 +2304,18 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { - IM_ASSERT(atlas->CustomRectIds[0] >= 0); - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; - IM_ASSERT(r.IsPacked()); + ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); + IM_ASSERT(r->IsPacked()); const int w = atlas->TexWidth; if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) { // Render/copy pixels - IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); + IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++) for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) { - const int offset0 = (int)(r.X + x) + (int)(r.Y + y) * w; + const int offset0 = (int)(r->X + x) + (int)(r->Y + y) * w; const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00; atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00; @@ -2331,29 +2323,46 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) } else { - IM_ASSERT(r.Width == 2 && r.Height == 2); - const int offset = (int)(r.X) + (int)(r.Y) * w; + // Render 4 white pixels + IM_ASSERT(r->Width == 2 && r->Height == 2); + const int offset = (int)r->X + (int)r->Y * w; atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF; } - atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y); + atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } + +// Note: this is called / shared by both the stb_truetype and the FreeType builder +void ImFontAtlasBuildInit(ImFontAtlas* atlas) +{ + // Register texture region for mouse cursors or standard white pixels + if (atlas->PackIdMouseCursors < 0) + { + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + else + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); + } +} + +// This is called/shared by both the stb_truetype and the FreeType builder. void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { - // Render into our custom data block + // Render into our custom data blocks + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) { - const ImFontAtlasCustomRect& r = atlas->CustomRects[i]; - if (r.Font == NULL || r.GlyphID == 0) + const ImFontAtlasCustomRect* r = &atlas->CustomRects[i]; + if (r->Font == NULL || r->GlyphID == 0) continue; - IM_ASSERT(r.Font->ContainerAtlas == atlas); + IM_ASSERT(r->Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&r, &uv0, &uv1); - r.Font->AddGlyph((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); + atlas->CalcCustomRectUV(r, &uv0, &uv1); + r->Font->AddGlyph((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); } // Build all fonts lookup tables From 1d3c3070d8462b6ca2d84e3ca0f05d28896018ec Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Mon, 13 Jan 2020 14:24:55 +0900 Subject: [PATCH 130/959] Texture-based thick lines: Initial version of AA line drawing using textures (press SHIFT to enable) --- imgui.cpp | 6 ++ imgui.h | 10 ++- imgui_demo.cpp | 57 +++++++++++++++++ imgui_draw.cpp | 156 +++++++++++++++++++++++++++++++++++++++-------- imgui_internal.h | 4 ++ 5 files changed, 206 insertions(+), 27 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index d09d61ed..34b63566 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,6 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + TexturedAntiAliasedLines= true; // Draw anti-aliased lines using textures where possible. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3688,10 +3689,14 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; + if (g.Style.TexturedAntiAliasedLines) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; + if ((g.Style.TexturedAntiAliasedLines) && (!(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; g.BackgroundDrawList._ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); @@ -6158,6 +6163,7 @@ void ImGui::SetCurrentFont(ImFont* font) ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; + g.DrawListSharedData.TexUvAALines = &atlas->TexUvAALines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } diff --git a/imgui.h b/imgui.h index adb2ab1c..09d92309 100644 --- a/imgui.h +++ b/imgui.h @@ -1439,6 +1439,7 @@ struct ImGuiStyle ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + bool TexturedAntiAliasedLines; // Draw anti-aliased lines using textures where possible. bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1997,7 +1998,8 @@ enum ImDrawListFlags_ ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AllowVtxOffset = 1 << 2 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. + ImDrawListFlags_AllowVtxOffset = 1 << 2, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. + ImDrawListFlags_TexturedAALines = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? }; // Draw command list @@ -2216,7 +2218,8 @@ enum ImFontAtlasFlags_ { ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two - ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) + ImFontAtlasFlags_NoAALines = 1 << 2 // Don't build anti-aliased line textures into the atlas }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2320,6 +2323,9 @@ struct ImFontAtlas // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors + int AALineMaxWidth; // Maximum line width to build anti-aliased textures for + ImVector AALineRectIds; // Custom texture rectangle IDs for anti-aliased lines + ImVector TexUvAALines; // UVs for anti-aliased line textures #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b481c305..f06d8526 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -297,6 +297,62 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); + // Test lines + + if (ImGui::Begin("Lines")) + { + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + const int num_cols = 16; + const int num_rows = 3; + const float line_len = 64.0f; + const float line_spacing = 128.0f; + + static float base_rot = 0.0f; + ImGui::SliderFloat("Base rotation", &base_rot, 0.0f, 360.0f); + static float line_width = 1.0f; + ImGui::SliderFloat("Line width", &line_width, 1.0f, 10.0f); + + ImVec2 window_pos = ImGui::GetWindowPos(); + ImVec2 cursor_pos = ImGui::GetCursorPos(); + ImVec2 base_pos(window_pos.x + cursor_pos.x + (line_spacing * 0.5f), window_pos.y + cursor_pos.y); + + for (int i = 0; i < num_rows; i++) + { + const char* name = ""; + switch (i) + { + case 0: name = "No AA"; draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; break; + case 1: name = "AA no texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags &= ~ImDrawListFlags_TexturedAALines; break; + case 2: name = "AA with texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags |= ImDrawListFlags_TexturedAALines; break; + } + + int initial_vtx_count = draw_list->VtxBuffer.Size; + int initial_idx_count = draw_list->IdxBuffer.Size; + + for (int j = 0; j < num_cols; j++) + { + const float pi = 3.14159265359f; + float r = (base_rot * pi / 180.0f) + ((j * pi * 0.5f) / (num_cols - 1)); + + ImVec2 center = ImVec2(base_pos.x + (line_spacing * (j * 0.5f)), base_pos.y + (line_spacing * (i + 0.5f))); + ImVec2 start = ImVec2(center.x + (sinf(r) * line_len * 0.5f), center.y + (cosf(r) * line_len * 0.5f)); + ImVec2 end = ImVec2(center.x - (sinf(r) * line_len * 0.5f), center.y - (cosf(r) * line_len * 0.5f)); + + draw_list->AddLine(start, end, IM_COL32(255, 255, 255, 255), line_width); + } + + ImGui::SetCursorPosY(cursor_pos.y + (i * line_spacing)); + ImGui::Text("%s - %d vertices, %d indices", name, draw_list->VtxBuffer.Size - initial_vtx_count, draw_list->IdxBuffer.Size - initial_idx_count); + } + + ImGui::SetCursorPosY(cursor_pos.y + (num_rows * line_spacing)); + + //ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); + //ImGui::Image(ImGui::GetFont()->ContainerAtlas->TexID, ImVec2((float)ImGui::GetFont()->ContainerAtlas->TexWidth, (float)ImGui::GetFont()->ContainerAtlas->TexHeight)); + } + ImGui::End(); + // Main body of the Demo window starts here. if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags)) { @@ -3831,6 +3887,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); + ImGui::Checkbox("Use textures for anti-aliased lines", &style.TexturedAntiAliasedLines); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 30b9b9fe..7c845f94 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -667,6 +667,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const ImVec2 opaque_uv = _Data->TexUvWhitePixel; const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw + const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) @@ -675,13 +676,24 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int idx_count = thick_line ? count * 18 : count * 12; - const int vtx_count = thick_line ? points_count * 4 : points_count * 3; + const int integer_thickness = (int)thickness; + + // Do we want to draw this line using a texture? + bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && + (integer_thickness >= 1) && + (integer_thickness <= _Data->Font->ContainerAtlas->AALineMaxWidth) && + ImGui::GetIO().KeyShift; // FIXME-AALINES: Remove this debug code + + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_TexturedAALines unless ImFontAtlasFlags_NoAALines is off + IM_ASSERT_PARANOID((!use_textures) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); + + const int idx_count = use_textures ? (count * 6) : (thick_line ? count * 18 : count * 12); + const int vtx_count = use_textures ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); PrimReserve(idx_count, vtx_count); // Temporary buffer // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point - ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630 + ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_textures) ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; // Calculate normals (tangents) for each line segment @@ -697,14 +709,19 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (!closed) temp_normals[points_count - 1] = temp_normals[points_count - 2]; - if (!thick_line) + // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point + if ((!thick_line) || (use_textures)) { + // The width of the geometry we need to draw + const float half_draw_size = (!thick_line) ? AA_SIZE : (AA_SIZE + (thickness * 0.5f)); + + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) { - temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; - temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; - temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; - temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; + temp_points[0] = points[0] + temp_normals[0] * half_draw_size; + temp_points[1] = points[0] - temp_normals[0] * half_draw_size; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size; } // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges @@ -713,15 +730,15 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { - const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; - const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : idx1 + 3; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment + unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_textures ? 2 : 3)); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; IM_FIXNORMAL2F(dm_x, dm_y); - dm_x *= AA_SIZE; - dm_y *= AA_SIZE; + 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 ImVec2* out_vtx = &temp_points[i2 * 2]; @@ -730,28 +747,54 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 out_vtx[1].x = points[i2].x - dm_x; out_vtx[1].y = points[i2].y - dm_y; - // Add indexes for four triangles - _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); - _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); - _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); - _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); - _IdxWritePtr += 12; + if (use_textures) + { + // Add indices for two triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri + _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri + _IdxWritePtr += 6; + } + else + { + // Add indexes for four triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1 + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2 + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1 + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2 + _IdxWritePtr += 12; + } idx1 = idx2; } // Add vertexes for each point on the line - for (int i = 0; i < points_count; i++) + if (use_textures) + { + // If we're using textures we only need to emit the left/right edge vertices + const ImVec4 tex_uvs = (*_Data->TexUvAALines)[integer_thickness - 1]; + + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = ImVec2(tex_uvs.x, tex_uvs.y); _VtxWritePtr[0].col = col; // Left-side outer edge + _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = ImVec2(tex_uvs.z, tex_uvs.y); _VtxWritePtr[1].col = col; // Right-side outer edge + _VtxWritePtr += 2; + } + } + else { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; - _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; - _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; - _VtxWritePtr += 3; + // If we're not using a texture, we need the centre vertex as well + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Centre of line + _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge + _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge + _VtxWritePtr += 3; + } } } else { - // Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point + // For untextured lines that are greater than a pixel in width, we need to draw the solid line core and thus require four vertices per point const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend @@ -1664,6 +1707,8 @@ ImFontAtlas::ImFontAtlas() TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); PackIdMouseCursors = -1; + + AALineMaxWidth = 8; } ImFontAtlas::~ImFontAtlas() @@ -2010,6 +2055,7 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) IM_ASSERT(atlas->ConfigData.Size > 0); ImFontAtlasBuildInit(atlas); + ImFontAtlasBuildRegisterAALineCustomRects(atlas); // Clear atlas atlas->TexID = (ImTextureID)NULL; @@ -2331,7 +2377,6 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } - // Note: this is called / shared by both the stb_truetype and the FreeType builder void ImFontAtlasBuildInit(ImFontAtlas* atlas) { @@ -2346,12 +2391,73 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) } // This is called/shared by both the stb_truetype and the FreeType builder. +const unsigned int FONT_ATLAS_AA_LINE_TEX_HEIGHT = 1; // Technically we only need 1 pixel in the ideal case but this can be increased if necessary to give a border to avoid sampling artifacts + +void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) +{ + if (atlas->AALineRectIds.size() > 0) + return; + + if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) + return; + + const int max = atlas->AALineMaxWidth; + + for (int n = 0; n < max; n++) + { + const int width = n + 1; // The line width this entry corresponds to + // The "width + 3" here is interesting - +2 is to give space for the end caps, but the remaining +1 is because (empirically) to match the behaviour of the untextured render path we need to draw lines one pixel wider + atlas->AALineRectIds.push_back(atlas->AddCustomRectRegular(width + 3, FONT_ATLAS_AA_LINE_TEX_HEIGHT)); + } +} + +void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) +{ + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); + IM_ASSERT(atlas->TexUvAALines.size() == 0); + + if (atlas->Flags & ImFontAtlasFlags_NoAALines) + return; + + const int w = atlas->TexWidth; + const unsigned int max = atlas->AALineMaxWidth; + + for (unsigned int n = 0; n < max; n++) + { + IM_ASSERT(atlas->AALineRectIds.size() > (int)n); + ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; + IM_ASSERT(r.IsPacked()); + + // We fill as many lines as we were given, to allow for >1 lines being used to work around sampling weirdness + for (unsigned int y = 0; y < r.Height; y++) + { + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + + // Each line consists of two empty pixels at the ends, with a line of solid pixels in the middle + *(write_ptr++) = 0; + for (unsigned short x = 0; x < (r.Width - 2U); x++) + { + *(write_ptr++) = 0xFF; + } + *(write_ptr++) = 0; + } + + ImVec2 uv0, uv1; + atlas->CalcCustomRectUV(&r, &uv0, &uv1); + float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the texture as we want a horizontal slice (with some padding either side to avoid sampling artifacts) + atlas->TexUvAALines.push_back(ImVec4(uv0.x, halfV, uv1.x, halfV)); + } +} + void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data blocks IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); + // Render anti-aliased line textures + ImFontAtlasBuildAALinesTexData(atlas); + // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) { diff --git a/imgui_internal.h b/imgui_internal.h index b57b01b5..2035f324 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -545,6 +545,8 @@ struct IMGUI_API ImDrawListSharedData ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) + ImVector* TexUvAALines; // UV of anti-aliased lines in the atlas + ImDrawListSharedData(); void SetCircleSegmentMaxError(float max_error); }; @@ -2018,8 +2020,10 @@ namespace ImGui // ImFontAtlas internals IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); +IMGUI_API void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); 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); From 741ab74b5575f0b4b5db82db549f07fda130d244 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Wed, 15 Jan 2020 16:33:09 +0900 Subject: [PATCH 131/959] Texture-based thick lines: Improvements to code for drawing anti-aliased lines using textures Moved line width into a constant Removed test code (now in imgui-tests) Improved matching between geometry and texture rendering at non-integer sizes --- imgui.h | 1 - imgui_demo.cpp | 56 ------------------------------------------------ imgui_draw.cpp | 14 +++++------- imgui_internal.h | 3 +++ 4 files changed, 8 insertions(+), 66 deletions(-) diff --git a/imgui.h b/imgui.h index 09d92309..cc4be5e0 100644 --- a/imgui.h +++ b/imgui.h @@ -2323,7 +2323,6 @@ struct ImFontAtlas // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int AALineMaxWidth; // Maximum line width to build anti-aliased textures for ImVector AALineRectIds; // Custom texture rectangle IDs for anti-aliased lines ImVector TexUvAALines; // UVs for anti-aliased line textures diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f06d8526..2afa7a4f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -297,62 +297,6 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver); - // Test lines - - if (ImGui::Begin("Lines")) - { - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - - const int num_cols = 16; - const int num_rows = 3; - const float line_len = 64.0f; - const float line_spacing = 128.0f; - - static float base_rot = 0.0f; - ImGui::SliderFloat("Base rotation", &base_rot, 0.0f, 360.0f); - static float line_width = 1.0f; - ImGui::SliderFloat("Line width", &line_width, 1.0f, 10.0f); - - ImVec2 window_pos = ImGui::GetWindowPos(); - ImVec2 cursor_pos = ImGui::GetCursorPos(); - ImVec2 base_pos(window_pos.x + cursor_pos.x + (line_spacing * 0.5f), window_pos.y + cursor_pos.y); - - for (int i = 0; i < num_rows; i++) - { - const char* name = ""; - switch (i) - { - case 0: name = "No AA"; draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; break; - case 1: name = "AA no texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags &= ~ImDrawListFlags_TexturedAALines; break; - case 2: name = "AA with texturing"; draw_list->Flags |= ImDrawListFlags_AntiAliasedLines; draw_list->Flags |= ImDrawListFlags_TexturedAALines; break; - } - - int initial_vtx_count = draw_list->VtxBuffer.Size; - int initial_idx_count = draw_list->IdxBuffer.Size; - - for (int j = 0; j < num_cols; j++) - { - const float pi = 3.14159265359f; - float r = (base_rot * pi / 180.0f) + ((j * pi * 0.5f) / (num_cols - 1)); - - ImVec2 center = ImVec2(base_pos.x + (line_spacing * (j * 0.5f)), base_pos.y + (line_spacing * (i + 0.5f))); - ImVec2 start = ImVec2(center.x + (sinf(r) * line_len * 0.5f), center.y + (cosf(r) * line_len * 0.5f)); - ImVec2 end = ImVec2(center.x - (sinf(r) * line_len * 0.5f), center.y - (cosf(r) * line_len * 0.5f)); - - draw_list->AddLine(start, end, IM_COL32(255, 255, 255, 255), line_width); - } - - ImGui::SetCursorPosY(cursor_pos.y + (i * line_spacing)); - ImGui::Text("%s - %d vertices, %d indices", name, draw_list->VtxBuffer.Size - initial_vtx_count, draw_list->IdxBuffer.Size - initial_idx_count); - } - - ImGui::SetCursorPosY(cursor_pos.y + (num_rows * line_spacing)); - - //ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); - //ImGui::Image(ImGui::GetFont()->ContainerAtlas->TexID, ImVec2((float)ImGui::GetFont()->ContainerAtlas->TexWidth, (float)ImGui::GetFont()->ContainerAtlas->TexHeight)); - } - ImGui::End(); - // Main body of the Demo window starts here. if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags)) { diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7c845f94..72ccb963 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -676,13 +676,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - const int integer_thickness = (int)thickness; + // The -0.5f here is to better match the geometry-based code, and also shift the transition point from one width texture to another off the integer values (where it will be less noticeable) + const int integer_thickness = ImMax((int)(thickness - 0.5f), 1); // Do we want to draw this line using a texture? - bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && - (integer_thickness >= 1) && - (integer_thickness <= _Data->Font->ContainerAtlas->AALineMaxWidth) && - ImGui::GetIO().KeyShift; // FIXME-AALINES: Remove this debug code + bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_TexturedAALines unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_textures) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); @@ -1707,8 +1705,6 @@ ImFontAtlas::ImFontAtlas() TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); PackIdMouseCursors = -1; - - AALineMaxWidth = 8; } ImFontAtlas::~ImFontAtlas() @@ -2401,7 +2397,7 @@ void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - const int max = atlas->AALineMaxWidth; + const int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; for (int n = 0; n < max; n++) { @@ -2420,7 +2416,7 @@ void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) return; const int w = atlas->TexWidth; - const unsigned int max = atlas->AALineMaxWidth; + const unsigned int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; for (unsigned int n = 0; n < max; n++) { diff --git a/imgui_internal.h b/imgui_internal.h index 2035f324..643aea4d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -529,6 +529,9 @@ struct IMGUI_API ImChunkStream #define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 #endif +// The maximum line width to build anti-aliased textures for +#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX 65 + // Data shared between all ImDrawList instances // You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. struct IMGUI_API ImDrawListSharedData From 222b7ddbfa16635905772faed268e33501ee22ae Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jan 2020 15:23:23 +0100 Subject: [PATCH 132/959] Texture-based thick lines: Tweaks, fix for truetype builder. --- imgui.cpp | 8 ++--- imgui.h | 4 +-- imgui_demo.cpp | 3 +- imgui_draw.cpp | 84 ++++++++++++++++++++++-------------------------- imgui_internal.h | 2 -- 5 files changed, 46 insertions(+), 55 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 34b63566..e6fe1184 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,7 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - TexturedAntiAliasedLines= true; // Draw anti-aliased lines using textures where possible. + AntiAliasedLinesUseTexData = true; // Draw anti-aliased lines using textures where possible. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3689,14 +3689,12 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; - if (g.Style.TexturedAntiAliasedLines) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; + if (g.Style.AntiAliasedLinesUseTexData && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTexData; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; - if ((g.Style.TexturedAntiAliasedLines) && (!(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_TexturedAALines; g.BackgroundDrawList._ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); diff --git a/imgui.h b/imgui.h index cc4be5e0..f361102c 100644 --- a/imgui.h +++ b/imgui.h @@ -1439,7 +1439,7 @@ struct ImGuiStyle ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - bool TexturedAntiAliasedLines; // Draw anti-aliased lines using textures where possible. + bool AntiAliasedLinesUseTexData; // Draw anti-aliased lines using textures where possible. bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1999,7 +1999,7 @@ enum ImDrawListFlags_ ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1 << 2, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. - ImDrawListFlags_TexturedAALines = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AntiAliasedLinesUseTexData = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? }; // Draw command list diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2afa7a4f..e90fd517 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3831,7 +3831,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); - ImGui::Checkbox("Use textures for anti-aliased lines", &style.TexturedAntiAliasedLines); + ImGui::Checkbox("Anti-aliased lines use texture data", &style.AntiAliasedLinesUseTexData); + ImGui::SameLine(); HelpMarker("Faster lines using texture data. Requires texture to use bilinear sampling (not nearest)."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 72ccb963..41d25955 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -358,6 +358,7 @@ ImDrawListSharedData::ImDrawListSharedData() ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } memset(CircleSegmentCounts, 0, sizeof(CircleSegmentCounts)); // This will be set by SetCircleSegmentMaxError() + TexUvAALines = NULL; } void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) @@ -680,18 +681,18 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const int integer_thickness = ImMax((int)(thickness - 0.5f), 1); // Do we want to draw this line using a texture? - bool use_textures = (Flags & ImDrawListFlags_TexturedAALines) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); - // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_TexturedAALines unless ImFontAtlasFlags_NoAALines is off - IM_ASSERT_PARANOID((!use_textures) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off + IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); - const int idx_count = use_textures ? (count * 6) : (thick_line ? count * 18 : count * 12); - const int vtx_count = use_textures ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); + const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); + const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); PrimReserve(idx_count, vtx_count); // Temporary buffer // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point - ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_textures) ? 5 : 3) * sizeof(ImVec2)); //-V630 + ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_texture) ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; // Calculate normals (tangents) for each line segment @@ -708,7 +709,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_normals[points_count - 1] = temp_normals[points_count - 2]; // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point - if ((!thick_line) || (use_textures)) + if (!thick_line || use_texture) { // The width of the geometry we need to draw const float half_draw_size = (!thick_line) ? AA_SIZE : (AA_SIZE + (thickness * 0.5f)); @@ -729,7 +730,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment - unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_textures ? 2 : 3)); // Vertex index for end of segment + unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -745,7 +746,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 out_vtx[1].x = points[i2].x - dm_x; out_vtx[1].y = points[i2].y - dm_y; - if (use_textures) + if (use_texture) { // Add indices for two triangles _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri @@ -766,7 +767,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } // Add vertexes for each point on the line - if (use_textures) + if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices const ImVec4 tex_uvs = (*_Data->TexUvAALines)[integer_thickness - 1]; @@ -2051,7 +2052,6 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) IM_ASSERT(atlas->ConfigData.Size > 0); ImFontAtlasBuildInit(atlas); - ImFontAtlasBuildRegisterAALineCustomRects(atlas); // Clear atlas atlas->TexID = (ImTextureID)NULL; @@ -2373,68 +2373,49 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } -// Note: this is called / shared by both the stb_truetype and the FreeType builder -void ImFontAtlasBuildInit(ImFontAtlas* atlas) -{ - // Register texture region for mouse cursors or standard white pixels - if (atlas->PackIdMouseCursors < 0) - { - if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); - else - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); - } -} - // This is called/shared by both the stb_truetype and the FreeType builder. const unsigned int FONT_ATLAS_AA_LINE_TEX_HEIGHT = 1; // Technically we only need 1 pixel in the ideal case but this can be increased if necessary to give a border to avoid sampling artifacts -void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) +static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) { - if (atlas->AALineRectIds.size() > 0) + if (atlas->AALineRectIds.Size > 0) return; if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - const int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; - - for (int n = 0; n < max; n++) + for (int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) { + // The "width + 3" here is interesting. +2 is to give space for the end caps, but the remaining +1 is + // because (empirically) to match the behavior of the untextured render path we need to draw lines one pixel wider. const int width = n + 1; // The line width this entry corresponds to - // The "width + 3" here is interesting - +2 is to give space for the end caps, but the remaining +1 is because (empirically) to match the behaviour of the untextured render path we need to draw lines one pixel wider atlas->AALineRectIds.push_back(atlas->AddCustomRectRegular(width + 3, FONT_ATLAS_AA_LINE_TEX_HEIGHT)); } } -void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) +static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - IM_ASSERT(atlas->TexUvAALines.size() == 0); + IM_ASSERT(atlas->TexUvAALines.Size == 0); if (atlas->Flags & ImFontAtlasFlags_NoAALines) return; const int w = atlas->TexWidth; - const unsigned int max = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; - - for (unsigned int n = 0; n < max; n++) + for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) { - IM_ASSERT(atlas->AALineRectIds.size() > (int)n); - ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; + IM_ASSERT(atlas->AALineRectIds.Size > (int)n); + ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; IM_ASSERT(r.IsPacked()); // We fill as many lines as we were given, to allow for >1 lines being used to work around sampling weirdness for (unsigned int y = 0; y < r.Height; y++) { - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; - // Each line consists of two empty pixels at the ends, with a line of solid pixels in the middle + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; *(write_ptr++) = 0; for (unsigned short x = 0; x < (r.Width - 2U); x++) - { *(write_ptr++) = 0xFF; - } *(write_ptr++) = 0; } @@ -2445,14 +2426,27 @@ void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas) } } +// Note: this is called / shared by both the stb_truetype and the FreeType builder +void ImFontAtlasBuildInit(ImFontAtlas* atlas) +{ + // Register texture region for mouse cursors or standard white pixels + if (atlas->PackIdMouseCursors < 0) + { + if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + else + atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); + } + + ImFontAtlasBuildRegisterAALineCustomRects(atlas); +} + +// This is called/shared by both the stb_truetype and the FreeType builder. void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data blocks - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); - - // Render anti-aliased line textures - ImFontAtlasBuildAALinesTexData(atlas); + ImFontAtlasBuildRenderAALinesTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) diff --git a/imgui_internal.h b/imgui_internal.h index 643aea4d..d38d9b78 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2023,10 +2023,8 @@ namespace ImGui // ImFontAtlas internals IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); -IMGUI_API void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); -IMGUI_API void ImFontAtlasBuildAALinesTexData(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); 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); From 403bf45245901031e112f8de4828cdd8c7eee805 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Thu, 6 Feb 2020 14:30:29 +0900 Subject: [PATCH 133/959] Texture-based thick lines: Allow interpolation between textures for non-integer line widths --- imgui.h | 2 +- imgui_draw.cpp | 84 +++++++++++++++++++++++++++++------------------- imgui_internal.h | 2 +- 3 files changed, 53 insertions(+), 35 deletions(-) diff --git a/imgui.h b/imgui.h index f361102c..47f15fb1 100644 --- a/imgui.h +++ b/imgui.h @@ -2323,7 +2323,7 @@ struct ImFontAtlas // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - ImVector AALineRectIds; // Custom texture rectangle IDs for anti-aliased lines + int AALineRectId; // Custom texture rectangle ID for anti-aliased lines ImVector TexUvAALines; // UVs for anti-aliased line textures #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 41d25955..376d4141 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -677,11 +677,12 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - // The -0.5f here is to better match the geometry-based code, and also shift the transition point from one width texture to another off the integer values (where it will be less noticeable) - const int integer_thickness = ImMax((int)(thickness - 0.5f), 1); + // The thick_line test is an attempt to compensate for the way half_draw_size gets calculated later, which special-cases 1.0f width lines + const int integer_thickness = thick_line ? ImMax((int)(thickness), 1) : 2; + const float fractional_thickness = thick_line ? (thickness) - integer_thickness : 0.0f; // Do we want to draw this line using a texture? - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness <= IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); @@ -711,8 +712,9 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point if (!thick_line || use_texture) { - // The width of the geometry we need to draw - const float half_draw_size = (!thick_line) ? AA_SIZE : (AA_SIZE + (thickness * 0.5f)); + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA + // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code + const float half_draw_size = (thickness * 0.5f) + 1; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) @@ -770,7 +772,18 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices - const ImVec4 tex_uvs = (*_Data->TexUvAALines)[integer_thickness - 1]; + + ImVec4 tex_uvs; + + if (fractional_thickness == 0.0f) // Fast path for pure integer widths + tex_uvs = (*_Data->TexUvAALines)[integer_thickness]; + else + { + // Calculate UV by interpolating between the two nearest integer line widths + const ImVec4 tex_uvs_0 = (*_Data->TexUvAALines)[integer_thickness]; + const ImVec4 tex_uvs_1 = (*_Data->TexUvAALines)[integer_thickness + 1]; + tex_uvs = ImLerp(tex_uvs_0, tex_uvs_1, fractional_thickness); + } for (int i = 0; i < points_count; i++) { @@ -2373,24 +2386,14 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } -// This is called/shared by both the stb_truetype and the FreeType builder. -const unsigned int FONT_ATLAS_AA_LINE_TEX_HEIGHT = 1; // Technically we only need 1 pixel in the ideal case but this can be increased if necessary to give a border to avoid sampling artifacts - static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) { - if (atlas->AALineRectIds.Size > 0) - return; - if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - for (int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) - { - // The "width + 3" here is interesting. +2 is to give space for the end caps, but the remaining +1 is - // because (empirically) to match the behavior of the untextured render path we need to draw lines one pixel wider. - const int width = n + 1; // The line width this entry corresponds to - atlas->AALineRectIds.push_back(atlas->AddCustomRectRegular(width + 3, FONT_ATLAS_AA_LINE_TEX_HEIGHT)); - } + const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate + // The "max_width + 2" here is to give space for the end caps, whilst height (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX+1) is to accommodate the fact we have a zero-width row + atlas->AALineRectId = atlas->AddCustomRectRegular(max_width + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); } static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) @@ -2401,27 +2404,42 @@ static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) if (atlas->Flags & ImFontAtlasFlags_NoAALines) return; + ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectId]; + IM_ASSERT(r.IsPacked()); + + // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them const int w = atlas->TexWidth; - for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; n++) + for (unsigned int n = 0; n < (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); n++) // +1 because of the zero-width row { - IM_ASSERT(atlas->AALineRectIds.Size > (int)n); - ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectIds[n]]; - IM_ASSERT(r.IsPacked()); + unsigned int y = n; + unsigned int line_width = n; + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + unsigned int pad_left = (r.Width - line_width) / 2; + unsigned int pad_right = r.Width - (pad_left + line_width); - // We fill as many lines as we were given, to allow for >1 lines being used to work around sampling weirdness - for (unsigned int y = 0; y < r.Height; y++) - { - // Each line consists of two empty pixels at the ends, with a line of solid pixels in the middle - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + // Make sure we're inside the texture bounds before we start writing pixels + IM_ASSERT_PARANOID(pad_left + line_width + pad_right == r.Width); + IM_ASSERT_PARANOID(y < r.Height); + + // Write each slice + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + for (unsigned int x = 0; x < pad_left; x++) *(write_ptr++) = 0; - for (unsigned short x = 0; x < (r.Width - 2U); x++) - *(write_ptr++) = 0xFF; + for (unsigned int x = 0; x < line_width; x++) + *(write_ptr++) = 0xFF; + for (unsigned int x = 0; x < pad_right; x++) *(write_ptr++) = 0; - } + + // Calculate UVs for this line + ImFontAtlasCustomRect line_rect = r; + line_rect.X += (unsigned short)(pad_left - 1); + line_rect.Width = (unsigned short)(line_width + 2); + line_rect.Y += (unsigned short)y; + line_rect.Height = 1; ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&r, &uv0, &uv1); - float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the texture as we want a horizontal slice (with some padding either side to avoid sampling artifacts) + atlas->CalcCustomRectUV(&line_rect, &uv0, &uv1); + float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts atlas->TexUvAALines.push_back(ImVec4(uv0.x, halfV, uv1.x, halfV)); } } diff --git a/imgui_internal.h b/imgui_internal.h index d38d9b78..4f3882c9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -529,7 +529,7 @@ struct IMGUI_API ImChunkStream #define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 #endif -// The maximum line width to build anti-aliased textures for +// The maximum line width to build anti-aliased textures for (note that this needs to be one greater than the maximum line width you want to be able to draw using the textured path) #define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX 65 // Data shared between all ImDrawList instances From 21d9e8e1f44b52a1f12eb04f650db99d7c34ac8a Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Tue, 11 Feb 2020 11:23:43 +0900 Subject: [PATCH 134/959] Texture-based thick lines: Simplified line width calculation code and removed hack for thickness 1.0 lines --- imgui_draw.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 376d4141..18ca4bd8 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -677,9 +677,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const float AA_SIZE = 1.0f; const ImU32 col_trans = col & ~IM_COL32_A_MASK; - // The thick_line test is an attempt to compensate for the way half_draw_size gets calculated later, which special-cases 1.0f width lines - const int integer_thickness = thick_line ? ImMax((int)(thickness), 1) : 2; - const float fractional_thickness = thick_line ? (thickness) - integer_thickness : 0.0f; + // Thicknesses <1.0 should behave like thickness 1.0 + thickness = ImMax(thickness, 1.0f); + + const int integer_thickness = (int)thickness ; + const float fractional_thickness = (thickness) - integer_thickness; // Do we want to draw this line using a texture? const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); @@ -714,7 +716,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 { // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code - const float half_draw_size = (thickness * 0.5f) + 1; + const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : 1.0f; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) From a07c8b69991af2988fce91fabab975ffcb976a41 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 17 Feb 2020 11:58:22 +0100 Subject: [PATCH 135/959] Texture-based thick lines: Fixes for AddCustomRect api, add IMGUI_HAS_TEXLINES define (temporarily) to facilitate working with test cases, Demo allows growing FrameBorderSize for testing --- imgui.h | 2 ++ imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 47f15fb1..e5e54290 100644 --- a/imgui.h +++ b/imgui.h @@ -1993,6 +1993,8 @@ enum ImDrawCornerFlags_ ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience }; +#define IMGUI_HAS_TEXLINES 1 + enum ImDrawListFlags_ { ImDrawListFlags_None = 0, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e90fd517..f599e034 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3698,7 +3698,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) 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"); + ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 4.0f, "%.1f"); ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::Text("Rounding"); ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 18ca4bd8..a4f68f9d 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2393,8 +2393,8 @@ static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) return; - const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate // The "max_width + 2" here is to give space for the end caps, whilst height (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX+1) is to accommodate the fact we have a zero-width row + const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate atlas->AALineRectId = atlas->AddCustomRectRegular(max_width + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); } From 78d6bdf08036fdeea08ee9e6a0191f058f89dca0 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 16 May 2020 16:55:05 +0200 Subject: [PATCH 136/959] Texture-based thick lines: Remove unnecessary indirection in fetching UV data, removed lerp call, renames, tweaks. --- imgui.cpp | 8 ++--- imgui.h | 17 ++++++---- imgui_demo.cpp | 4 +-- imgui_draw.cpp | 84 +++++++++++++++++++++++------------------------- imgui_internal.h | 5 +-- 5 files changed, 58 insertions(+), 60 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e6fe1184..b9c300fa 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,7 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - AntiAliasedLinesUseTexData = true; // Draw anti-aliased lines using textures where possible. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3689,8 +3689,8 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; - if (g.Style.AntiAliasedLinesUseTexData && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines)) - g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTexData; + if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) @@ -6161,7 +6161,7 @@ void ImGui::SetCurrentFont(ImFont* font) ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; - g.DrawListSharedData.TexUvAALines = &atlas->TexUvAALines; + g.DrawListSharedData.TexUvAALines = atlas->TexUvAALines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } diff --git a/imgui.h b/imgui.h index e5e54290..5e86bae5 100644 --- a/imgui.h +++ b/imgui.h @@ -1439,7 +1439,7 @@ struct ImGuiStyle ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - bool AntiAliasedLinesUseTexData; // Draw anti-aliased lines using textures where possible. + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1897,6 +1897,11 @@ struct ImColor // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoAALines to disable baking. +#ifndef IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX (63) +#endif + // ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] // NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, // you can poke into the draw list for that! Draw callback may be useful for example to: @@ -2000,8 +2005,8 @@ enum ImDrawListFlags_ ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AllowVtxOffset = 1 << 2, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. - ImDrawListFlags_AntiAliasedLinesUseTexData = 1 << 3 // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 2, // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; // Draw command list @@ -2221,7 +2226,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoAALines = 1 << 2 // Don't build anti-aliased line textures into the atlas + ImFontAtlasFlags_NoAntiAliasedLines = 1 << 2 // Don't build anti-aliased line textures into the atlas (save a little texture memory). They will be rendered using polygons (a little bit more expensive) }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2322,11 +2327,11 @@ struct ImFontAtlas 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 ConfigData; // Configuration data + ImVec4 TexUvAALines[IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1]; // UVs for anti-aliased line textures // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int AALineRectId; // Custom texture rectangle ID for anti-aliased lines - ImVector TexUvAALines; // UVs for anti-aliased line textures + int PackIdAALines; // Custom texture rectangle ID for anti-aliased lines #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f599e034..8b5d57d4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3698,7 +3698,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) 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, 4.0f, "%.1f"); + ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f"); ImGui::Text("Rounding"); ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f"); @@ -3831,7 +3831,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::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 data", &style.AntiAliasedLinesUseTexData); + ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); ImGui::SameLine(); HelpMarker("Faster lines using texture data. Requires texture to use bilinear sampling (not nearest)."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index a4f68f9d..24e8a654 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -668,7 +668,6 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const ImVec2 opaque_uv = _Data->TexUvWhitePixel; const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw - const bool thick_line = (thickness > 1.0f); if (Flags & ImDrawListFlags_AntiAliasedLines) @@ -679,12 +678,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Thicknesses <1.0 should behave like thickness 1.0 thickness = ImMax(thickness, 1.0f); - - const int integer_thickness = (int)thickness ; - const float fractional_thickness = (thickness) - integer_thickness; + const int integer_thickness = (int)thickness; + const float fractional_thickness = thickness - integer_thickness; // Do we want to draw this line using a texture? - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTexData) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); @@ -712,8 +710,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 temp_normals[points_count - 1] = temp_normals[points_count - 2]; // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point - if (!thick_line || use_texture) + if (use_texture || !thick_line) { + // [PATH 1] Texture-based lines (thick or non-thick) + // [PATH 2] Non texture-based lines (non-thick) + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : 1.0f; @@ -734,7 +735,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment { const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment - unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment + const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -774,32 +775,30 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices - - ImVec4 tex_uvs; - - if (fractional_thickness == 0.0f) // Fast path for pure integer widths - tex_uvs = (*_Data->TexUvAALines)[integer_thickness]; - else + ImVec4 tex_uvs = _Data->TexUvAALines[integer_thickness]; + if (fractional_thickness != 0.0f) { - // Calculate UV by interpolating between the two nearest integer line widths - const ImVec4 tex_uvs_0 = (*_Data->TexUvAALines)[integer_thickness]; - const ImVec4 tex_uvs_1 = (*_Data->TexUvAALines)[integer_thickness + 1]; - tex_uvs = ImLerp(tex_uvs_0, tex_uvs_1, fractional_thickness); + const ImVec4 tex_uvs_1 = _Data->TexUvAALines[integer_thickness + 1]; + tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() + tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; + tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; + tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; } - + ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y); + ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w); for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = ImVec2(tex_uvs.x, tex_uvs.y); _VtxWritePtr[0].col = col; // Left-side outer edge - _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = ImVec2(tex_uvs.z, tex_uvs.y); _VtxWritePtr[1].col = col; // Right-side outer edge + _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge + _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge _VtxWritePtr += 2; } } else { - // If we're not using a texture, we need the centre vertex as well + // If we're not using a texture, we need the center vertex as well for (int i = 0; i < points_count; i++) { - _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Centre of line + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Center of line _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge _VtxWritePtr += 3; @@ -808,7 +807,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { - // For untextured lines that are greater than a pixel in width, we need to draw the solid line core and thus require four vertices per point + // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend @@ -880,7 +879,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 } else { - // Non texture-based, Non anti-aliased lines + // [PATH 4] Non texture-based, Non anti-aliased lines const int idx_count = count * 6; const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges PrimReserve(idx_count, vtx_count); @@ -1720,7 +1719,7 @@ ImFontAtlas::ImFontAtlas() TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); - PackIdMouseCursors = -1; + PackIdMouseCursors = PackIdAALines = -1; } ImFontAtlas::~ImFontAtlas() @@ -1748,7 +1747,7 @@ void ImFontAtlas::ClearInputData() } ConfigData.clear(); CustomRects.clear(); - PackIdMouseCursors = -1; + PackIdMouseCursors = PackIdAALines = -1; } void ImFontAtlas::ClearTexData() @@ -2390,41 +2389,38 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) { - if ((atlas->Flags & ImFontAtlasFlags_NoAALines)) + if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) return; - // The "max_width + 2" here is to give space for the end caps, whilst height (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX+1) is to accommodate the fact we have a zero-width row - const int max_width = IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX; // The maximum line width we want to generate - atlas->AALineRectId = atlas->AddCustomRectRegular(max_width + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); + // 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 + atlas->PackIdAALines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); } static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - IM_ASSERT(atlas->TexUvAALines.Size == 0); - - if (atlas->Flags & ImFontAtlasFlags_NoAALines) + if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) return; - ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->AALineRectId]; - IM_ASSERT(r.IsPacked()); + ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdAALines); + IM_ASSERT(r->IsPacked()); // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them const int w = atlas->TexWidth; - for (unsigned int n = 0; n < (IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); n++) // +1 because of the zero-width row + for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_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 unsigned int y = n; unsigned int line_width = n; - // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle - unsigned int pad_left = (r.Width - line_width) / 2; - unsigned int pad_right = r.Width - (pad_left + line_width); + unsigned int pad_left = (r->Width - line_width) / 2; + unsigned int pad_right = r->Width - (pad_left + line_width); // Make sure we're inside the texture bounds before we start writing pixels IM_ASSERT_PARANOID(pad_left + line_width + pad_right == r.Width); IM_ASSERT_PARANOID(y < r.Height); // Write each slice - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r.X + ((r.Y + y) * w)]; + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * w)]; for (unsigned int x = 0; x < pad_left; x++) *(write_ptr++) = 0; for (unsigned int x = 0; x < line_width; x++) @@ -2433,16 +2429,16 @@ static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) *(write_ptr++) = 0; // Calculate UVs for this line - ImFontAtlasCustomRect line_rect = r; + ImFontAtlasCustomRect line_rect = *r; line_rect.X += (unsigned short)(pad_left - 1); - line_rect.Width = (unsigned short)(line_width + 2); line_rect.Y += (unsigned short)y; + line_rect.Width = (unsigned short)(line_width + 2); line_rect.Height = 1; ImVec2 uv0, uv1; atlas->CalcCustomRectUV(&line_rect, &uv0, &uv1); - float halfV = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - atlas->TexUvAALines.push_back(ImVec4(uv0.x, halfV, uv1.x, halfV)); + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvAALines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } diff --git a/imgui_internal.h b/imgui_internal.h index 4f3882c9..629ddc32 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -529,9 +529,6 @@ struct IMGUI_API ImChunkStream #define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1 #endif -// The maximum line width to build anti-aliased textures for (note that this needs to be one greater than the maximum line width you want to be able to draw using the textured path) -#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX 65 - // Data shared between all ImDrawList instances // You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. struct IMGUI_API ImDrawListSharedData @@ -548,7 +545,7 @@ struct IMGUI_API ImDrawListSharedData ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) - ImVector* TexUvAALines; // UV of anti-aliased lines in the atlas + const ImVec4* TexUvAALines; // UV of anti-aliased lines in the atlas ImDrawListSharedData(); void SetCircleSegmentMaxError(float max_error); From b5bae9781df1204a7dc6ae8b4b1f605c05f0fd74 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Tue, 7 Jul 2020 16:19:27 +0900 Subject: [PATCH 137/959] Texture-based thick lines: Only use textured lines for integer line widths --- imgui_draw.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 24e8a654..15a6c6f2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -681,8 +681,8 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const int integer_thickness = (int)thickness; const float fractional_thickness = thickness - integer_thickness; - // Do we want to draw this line using a texture? - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX); + // Do we want to draw this line using a texture? (for now, only draw integer-width lines using textures to avoid issues with the way scaling occurs) + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX) && (fractional_thickness >= -0.00001f) && (fractional_thickness <= 0.00001f); // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); From 3a6c9907cd182795f82c67df5d77e88bcfe9563c Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 7 Jul 2020 13:24:10 +0200 Subject: [PATCH 138/959] Texture-based thick lines: Minor tweaks and rename toward merging in master. Changes to allow changing AA_SIZE (disable texture path). --- docs/CHANGELOG.txt | 9 +++++ imgui.cpp | 6 ++-- imgui.h | 28 +++++++-------- imgui_demo.cpp | 2 +- imgui_draw.cpp | 85 +++++++++++++++++++--------------------------- imgui_internal.h | 3 +- 6 files changed, 63 insertions(+), 70 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c62a140d..8043bf47 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,15 @@ HOW TO UPDATE? VERSION 1.78 WIP (In Progress) ----------------------------------------------------------------------- +Other Changes: + +- ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based + path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] + - This change will facilitate the wider use of thick borders in future style changes. + - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. + - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. + - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. + ----------------------------------------------------------------------- VERSION 1.77 (Released 2020-06-29) diff --git a/imgui.cpp b/imgui.cpp index b9c300fa..37e611ad 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -935,7 +935,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require back-end to render with bilinear filtering. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3689,7 +3689,7 @@ void ImGui::NewFrame() g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; - if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines)) + if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; @@ -6161,7 +6161,7 @@ void ImGui::SetCurrentFont(ImFont* font) ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; - g.DrawListSharedData.TexUvAALines = atlas->TexUvAALines; + g.DrawListSharedData.TexUvLines = atlas->TexUvLines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } diff --git a/imgui.h b/imgui.h index 5e86bae5..6f4dec52 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.78 WIP" -#define IMGUI_VERSION_NUM 17702 +#define IMGUI_VERSION_NUM 17703 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -1438,9 +1438,9 @@ struct ImGuiStyle ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Requires back-end to render with bilinear filtering. - bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require back-end to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. ImVec4 Colors[ImGuiCol_COUNT]; @@ -1897,9 +1897,9 @@ struct ImColor // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- -// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoAALines to disable baking. -#ifndef IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX (63) +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63) #endif // ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] @@ -1998,14 +1998,14 @@ enum ImDrawCornerFlags_ ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience }; -#define IMGUI_HAS_TEXLINES 1 - +// Flags for ImDrawList. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. +// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. enum ImDrawListFlags_ { ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) - ImDrawListFlags_AntiAliasedFill = 1 << 1, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). - ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 2, // Should anti-aliased lines be drawn using textures where possible? + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require back-end to render with bilinear filtering. + ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; @@ -2226,7 +2226,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoAntiAliasedLines = 1 << 2 // Don't build anti-aliased line textures into the atlas (save a little texture memory). They will be rendered using polygons (a little bit more expensive) + ImFontAtlasFlags_NoBakedLines = 1 << 2 // Don't build thick line textures into the atlas (save a little texture memory). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -2327,11 +2327,11 @@ struct ImFontAtlas 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 ConfigData; // Configuration data - ImVec4 TexUvAALines[IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1]; // UVs for anti-aliased line textures + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors - int PackIdAALines; // Custom texture rectangle ID for anti-aliased lines + int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8b5d57d4..d66bf014 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3832,7 +3832,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::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(); HelpMarker("Faster lines using texture data. Requires texture to use bilinear sampling (not nearest)."); + ImGui::SameLine(); HelpMarker("Faster lines using texture data. Require back-end to render with bilinear filtering (not point/nearest filtering)."); ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 15a6c6f2..942c2d90 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -358,7 +358,7 @@ ImDrawListSharedData::ImDrawListSharedData() ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } memset(CircleSegmentCounts, 0, sizeof(CircleSegmentCounts)); // This will be set by SetCircleSegmentMaxError() - TexUvAALines = NULL; + TexUvLines = NULL; } void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) @@ -681,11 +681,13 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 const int integer_thickness = (int)thickness; const float fractional_thickness = thickness - integer_thickness; - // Do we want to draw this line using a texture? (for now, only draw integer-width lines using textures to avoid issues with the way scaling occurs) - const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX) && (fractional_thickness >= -0.00001f) && (fractional_thickness <= 0.00001f); + // Do we want to draw this line using a texture? + // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. + // - If AA_SIZE is not 1.0f we cannot use the texture path. + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f); - // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTexData unless ImFontAtlasFlags_NoAALines is off - IM_ASSERT_PARANOID((!use_texture) || (!(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoAALines))); + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off + IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); @@ -693,7 +695,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // Temporary buffer // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point - ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((thick_line && !use_texture) ? 5 : 3) * sizeof(ImVec2)); //-V630 + ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((use_texture || !thick_line) ? 3 : 5) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; // Calculate normals (tangents) for each line segment @@ -717,7 +719,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code - const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : 1.0f; + const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend if (!closed) @@ -775,10 +777,10 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 if (use_texture) { // If we're using textures we only need to emit the left/right edge vertices - ImVec4 tex_uvs = _Data->TexUvAALines[integer_thickness]; + ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness]; if (fractional_thickness != 0.0f) { - const ImVec4 tex_uvs_1 = _Data->TexUvAALines[integer_thickness + 1]; + const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1]; tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; @@ -1719,7 +1721,7 @@ ImFontAtlas::ImFontAtlas() TexWidth = TexHeight = 0; TexUvScale = ImVec2(0.0f, 0.0f); TexUvWhitePixel = ImVec2(0.0f, 0.0f); - PackIdMouseCursors = PackIdAALines = -1; + PackIdMouseCursors = PackIdLines = -1; } ImFontAtlas::~ImFontAtlas() @@ -1747,7 +1749,7 @@ void ImFontAtlas::ClearInputData() } ConfigData.clear(); CustomRects.clear(); - PackIdMouseCursors = PackIdAALines = -1; + PackIdMouseCursors = PackIdLines = -1; } void ImFontAtlas::ClearTexData() @@ -2387,27 +2389,15 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y); } -static void ImFontAtlasBuildRegisterAALineCustomRects(ImFontAtlas* atlas) +static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas) { - if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) + if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) return; - // 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 - atlas->PackIdAALines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1); -} - -static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) -{ - IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - if (atlas->Flags & ImFontAtlasFlags_NoAntiAliasedLines) - return; - - ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdAALines); - IM_ASSERT(r->IsPacked()); - // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them - const int w = atlas->TexWidth; - for (unsigned int n = 0; n < IM_DRAWLIST_TEX_AA_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row + ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines); + IM_ASSERT(r->IsPacked()); + for (unsigned 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 unsigned int y = n; @@ -2415,30 +2405,18 @@ static void ImFontAtlasBuildRenderAALinesTexData(ImFontAtlas* atlas) unsigned int pad_left = (r->Width - line_width) / 2; unsigned int pad_right = r->Width - (pad_left + line_width); - // Make sure we're inside the texture bounds before we start writing pixels - IM_ASSERT_PARANOID(pad_left + line_width + pad_right == r.Width); - IM_ASSERT_PARANOID(y < r.Height); - // Write each slice - unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * w)]; - for (unsigned int x = 0; x < pad_left; x++) - *(write_ptr++) = 0; - for (unsigned int x = 0; x < line_width; x++) - *(write_ptr++) = 0xFF; - for (unsigned int x = 0; x < pad_right; x++) - *(write_ptr++) = 0; + 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 + unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)]; + memset(write_ptr, 0x00, pad_left); + memset(write_ptr + pad_left, 0xFF, line_width); + memset(write_ptr + pad_left + line_width, 0x00, pad_right); // Calculate UVs for this line - ImFontAtlasCustomRect line_rect = *r; - line_rect.X += (unsigned short)(pad_left - 1); - line_rect.Y += (unsigned short)y; - line_rect.Width = (unsigned short)(line_width + 2); - line_rect.Height = 1; - - ImVec2 uv0, uv1; - atlas->CalcCustomRectUV(&line_rect, &uv0, &uv1); + 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->TexUvAALines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); + atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } @@ -2454,15 +2432,22 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2); } - ImFontAtlasBuildRegisterAALineCustomRects(atlas); + // 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); + } } // This is called/shared by both the stb_truetype and the FreeType builder. void ImFontAtlasBuildFinish(ImFontAtlas* atlas) { // Render into our custom data blocks + IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); ImFontAtlasBuildRenderDefaultTexData(atlas); - ImFontAtlasBuildRenderAALinesTexData(atlas); + ImFontAtlasBuildRenderLinesTexData(atlas); // Register custom rectangle glyphs for (int i = 0; i < atlas->CustomRects.Size; i++) diff --git a/imgui_internal.h b/imgui_internal.h index 629ddc32..a6245d1a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -544,8 +544,7 @@ struct IMGUI_API ImDrawListSharedData // [Internal] Lookup tables ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead) - - const ImVec4* TexUvAALines; // UV of anti-aliased lines in the atlas + const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas ImDrawListSharedData(); void SetCircleSegmentMaxError(float max_error); From 89685b346c7b02b7d557678fd9d5d11a80967f83 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 Jul 2020 11:21:31 +0200 Subject: [PATCH 139/959] ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra unrequired vertex. Actual missing code for d3b37180a3ff186b481d93d09664bb244a428d10, thanks @domgho! --- docs/CHANGELOG.txt | 8 ++++---- imgui_draw.cpp | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8043bf47..8f4de8d9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,12 +37,14 @@ HOW TO UPDATE? Other Changes: -- ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based +- ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - - This change will facilitate the wider use of thick borders in future style changes. + - This change will facilitate the wider use of thick borders in future style changes. - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. +- ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate + an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] ----------------------------------------------------------------------- @@ -112,8 +114,6 @@ Other Changes: VtxOffset was not zero would lead to draw commands with wrong VtxOffset. (#2591) - ImDrawList, ImDrawListSplitter, Columns: Fixed an issue where starting a split right after a callback draw command would incorrectly override the callback draw command. -- ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would - generate an extra unrequired vertex. [@ShironekoBen] - Misc, Freetype: Fix for rare case where FT_Get_Char_Index() succeeds but FT_Load_Glyph() fails. - Docs: Improved and moved font documentation to docs/FONTS.md so it can be readable on the web. Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 942c2d90..cdaa34fa 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1235,7 +1235,7 @@ void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int nu // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; if (num_segments == 12) - PathArcToFast(center, radius - 0.5f, 0, 12); + PathArcToFast(center, radius - 0.5f, 0, 12 - 1); else PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); PathStroke(col, true, thickness); @@ -1265,7 +1265,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; if (num_segments == 12) - PathArcToFast(center, radius, 0, 12); + PathArcToFast(center, radius, 0, 12 - 1); else PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); PathFillConvex(col); From cb1d5784707503b2a1a82be81dabcbe5529e4e5f Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 12:09:24 +0200 Subject: [PATCH 140/959] Backends: DX12, Viewports: Fixed issue on shutdown when viewports are disabled. (#3347) --- examples/imgui_impl_dx12.cpp | 38 ++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 40559b71..e4480e99 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -49,6 +49,7 @@ static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {}; static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL; static UINT g_numFramesInFlight = 0; +// Buffers used during the rendering of a frame struct FrameResources { ID3D12Resource* IndexBuffer; @@ -57,6 +58,7 @@ struct FrameResources int VertexBufferSize; }; +// Buffers used for secondary viewports created by the multi-viewports systems struct FrameContext { ID3D12CommandAllocator* CommandAllocator; @@ -64,7 +66,7 @@ struct FrameContext D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; }; -// Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data. +// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. struct ImGuiViewportDataDx12 { ID3D12CommandQueue* CommandQueue; @@ -133,6 +135,13 @@ static void SafeRelease(T*& res) res = NULL; } +static void ImGui_ImplDX12_DestroyFrameResources(FrameResources* resources) +{ + SafeRelease(resources->IndexBuffer); + SafeRelease(resources->VertexBuffer); + resources->IndexBufferSize = resources->VertexBufferSize = 0; +} + struct VERTEX_CONSTANT_BUFFER { float mvp[4][4]; @@ -699,6 +708,8 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO g_numFramesInFlight = num_frames_in_flight; g_pd3dSrvDescHeap = cbv_srv_heap; + // Create a dummy ImGuiViewportDataDx12 holder for the main viewport, + // Since this is created and managed by the application, we will only use the ->Resources[] fields. ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->RendererUserData = IM_NEW(ImGuiViewportDataDx12)(); @@ -712,6 +723,18 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO void ImGui_ImplDX12_Shutdown() { + // Manually delete main viewport render resources in-case we haven't initialized for viewports + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + if (ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)main_viewport->RendererUserData) + { + // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[] + for (UINT i = 0; i < g_numFramesInFlight; i++) + ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + IM_DELETE(data); + main_viewport->RendererUserData = NULL; + } + + // Clean up windows and device objects ImGui_ImplDX12_ShutdownPlatformInterface(); ImGui_ImplDX12_InvalidateDeviceObjects(); @@ -720,11 +743,6 @@ void ImGui_ImplDX12_Shutdown() g_hFontSrvGpuDescHandle.ptr = 0; g_numFramesInFlight = 0; g_pd3dSrvDescHeap = NULL; - - ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - if (ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)main_viewport->RendererUserData) - IM_DELETE(data); - main_viewport->RendererUserData = NULL; } void ImGui_ImplDX12_NewFrame() @@ -841,10 +859,7 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) } for (UINT i = 0; i < g_numFramesInFlight; i++) - { - SafeRelease(data->Resources[i].IndexBuffer); - SafeRelease(data->Resources[i].VertexBuffer); - } + ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); } static void ImGui_WaitForPendingOperations(ImGuiViewportDataDx12* data) @@ -880,8 +895,7 @@ static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport) { SafeRelease(data->FrameCtx[i].RenderTarget); SafeRelease(data->FrameCtx[i].CommandAllocator); - SafeRelease(data->Resources[i].IndexBuffer); - SafeRelease(data->Resources[i].VertexBuffer); + ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); } IM_DELETE(data); } From b626dd57d3f11a2ea91ea2f0b7d9be50d7506d21 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 12:20:03 +0200 Subject: [PATCH 141/959] Backends: DX12, Viewports: Tidying up, renaming. --- examples/imgui_impl_dx12.cpp | 74 ++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 36 deletions(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index e4480e99..690f3a8b 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -50,7 +50,7 @@ static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL; static UINT g_numFramesInFlight = 0; // Buffers used during the rendering of a frame -struct FrameResources +struct ImGui_ImplDX12_RenderBuffers { ID3D12Resource* IndexBuffer; ID3D12Resource* VertexBuffer; @@ -59,28 +59,31 @@ struct FrameResources }; // Buffers used for secondary viewports created by the multi-viewports systems -struct FrameContext +struct ImGui_ImplDX12_FrameContext { - ID3D12CommandAllocator* CommandAllocator; - ID3D12Resource* RenderTarget; - D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; + ID3D12CommandAllocator* CommandAllocator; + ID3D12Resource* RenderTarget; + D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; }; // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. +// Main viewport created by application will only use the Resources field. +// Secondary viewports created by this back-end will use all the fields (including Window fields), struct ImGuiViewportDataDx12 { - ID3D12CommandQueue* CommandQueue; - ID3D12GraphicsCommandList* CommandList; - ID3D12DescriptorHeap* RtvDescHeap; - IDXGISwapChain3* SwapChain; - - ID3D12Fence* Fence; - UINT64 FenceSignaledValue; - HANDLE FenceEvent; - - UINT FrameIndex; - FrameContext* FrameCtx; - FrameResources* Resources; + // Window + ID3D12CommandQueue* CommandQueue; + ID3D12GraphicsCommandList* CommandList; + ID3D12DescriptorHeap* RtvDescHeap; + IDXGISwapChain3* SwapChain; + ID3D12Fence* Fence; + UINT64 FenceSignaledValue; + HANDLE FenceEvent; + ImGui_ImplDX12_FrameContext* FrameCtx; + + // Render buffers + UINT FrameIndex; + ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers; ImGuiViewportDataDx12() { @@ -88,13 +91,12 @@ struct ImGuiViewportDataDx12 CommandList = NULL; RtvDescHeap = NULL; SwapChain = NULL; - Fence = NULL; FenceSignaledValue = 0; FenceEvent = NULL; + FrameCtx = new ImGui_ImplDX12_FrameContext[g_numFramesInFlight]; FrameIndex = UINT_MAX; - FrameCtx = new FrameContext[g_numFramesInFlight]; - Resources = new FrameResources[g_numFramesInFlight]; + FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[g_numFramesInFlight]; for (UINT i = 0; i < g_numFramesInFlight; ++i) { @@ -102,10 +104,10 @@ struct ImGuiViewportDataDx12 FrameCtx[i].RenderTarget = NULL; // Create buffers with a default size (they will later be grown as needed) - Resources[i].IndexBuffer = NULL; - Resources[i].VertexBuffer = NULL; - Resources[i].VertexBufferSize = 5000; - Resources[i].IndexBufferSize = 10000; + FrameRenderBuffers[i].IndexBuffer = NULL; + FrameRenderBuffers[i].VertexBuffer = NULL; + FrameRenderBuffers[i].VertexBufferSize = 5000; + FrameRenderBuffers[i].IndexBufferSize = 10000; } } ~ImGuiViewportDataDx12() @@ -119,11 +121,11 @@ struct ImGuiViewportDataDx12 for (UINT i = 0; i < g_numFramesInFlight; ++i) { IM_ASSERT(FrameCtx[i].CommandAllocator == NULL && FrameCtx[i].RenderTarget == NULL); - IM_ASSERT(Resources[i].IndexBuffer == NULL && Resources[i].VertexBuffer == NULL); + IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == NULL && FrameRenderBuffers[i].VertexBuffer == NULL); } delete[] FrameCtx; FrameCtx = NULL; - delete[] Resources; Resources = NULL; + delete[] FrameRenderBuffers; FrameRenderBuffers = NULL; } }; @@ -135,11 +137,11 @@ static void SafeRelease(T*& res) res = NULL; } -static void ImGui_ImplDX12_DestroyFrameResources(FrameResources* resources) +static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers) { - SafeRelease(resources->IndexBuffer); - SafeRelease(resources->VertexBuffer); - resources->IndexBufferSize = resources->VertexBufferSize = 0; + SafeRelease(render_buffers->IndexBuffer); + SafeRelease(render_buffers->VertexBuffer); + render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0; } struct VERTEX_CONSTANT_BUFFER @@ -151,7 +153,7 @@ struct VERTEX_CONSTANT_BUFFER static void ImGui_ImplDX12_InitPlatformInterface(); static void ImGui_ImplDX12_ShutdownPlatformInterface(); -static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, FrameResources* fr) +static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr) { // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). @@ -216,7 +218,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL ImGuiViewportDataDx12* render_data = (ImGuiViewportDataDx12*)draw_data->OwnerViewport->RendererUserData; render_data->FrameIndex++; - FrameResources* fr = &render_data->Resources[render_data->FrameIndex % g_numFramesInFlight]; + ImGui_ImplDX12_RenderBuffers* fr = &render_data->FrameRenderBuffers[render_data->FrameIndex % g_numFramesInFlight]; // Create and grow vertex/index buffers if needed if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount) @@ -729,7 +731,7 @@ void ImGui_ImplDX12_Shutdown() { // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[] for (UINT i = 0; i < g_numFramesInFlight; i++) - ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + ImGui_ImplDX12_DestroyRenderBuffers(&data->FrameRenderBuffers[i]); IM_DELETE(data); main_viewport->RendererUserData = NULL; } @@ -859,7 +861,7 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) } for (UINT i = 0; i < g_numFramesInFlight; i++) - ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + ImGui_ImplDX12_DestroyRenderBuffers(&data->FrameRenderBuffers[i]); } static void ImGui_WaitForPendingOperations(ImGuiViewportDataDx12* data) @@ -895,7 +897,7 @@ static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport) { SafeRelease(data->FrameCtx[i].RenderTarget); SafeRelease(data->FrameCtx[i].CommandAllocator); - ImGui_ImplDX12_DestroyFrameResources(&data->Resources[i]); + ImGui_ImplDX12_DestroyRenderBuffers(&data->FrameRenderBuffers[i]); } IM_DELETE(data); } @@ -928,7 +930,7 @@ static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*) { ImGuiViewportDataDx12* data = (ImGuiViewportDataDx12*)viewport->RendererUserData; - FrameContext* frame_context = &data->FrameCtx[data->FrameIndex % g_numFramesInFlight]; + ImGui_ImplDX12_FrameContext* frame_context = &data->FrameCtx[data->FrameIndex % g_numFramesInFlight]; UINT back_buffer_idx = data->SwapChain->GetCurrentBackBufferIndex(); const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); From 06f7854b160200ac942aba1137e76be7600d7fc5 Mon Sep 17 00:00:00 2001 From: Moritz Heinemann Date: Wed, 1 Jul 2020 23:13:59 +0200 Subject: [PATCH 142/959] Backends: OpenGL3: Add glad 2 to OpenGL loaders. (#3330) --- examples/example_glfw_opengl3/Makefile | 4 ++++ examples/example_glfw_opengl3/main.cpp | 4 ++++ examples/example_sdl_opengl3/Makefile | 4 ++++ examples/example_sdl_opengl3/main.cpp | 4 ++++ examples/imgui_impl_opengl3.cpp | 5 +++++ examples/imgui_impl_opengl3.h | 3 +++ 6 files changed, 24 insertions(+) diff --git a/examples/example_glfw_opengl3/Makefile b/examples/example_glfw_opengl3/Makefile index 3bc72b6f..0e7faa12 100644 --- a/examples/example_glfw_opengl3/Makefile +++ b/examples/example_glfw_opengl3/Makefile @@ -42,6 +42,10 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W # SOURCES += ../libs/glad/src/glad.c # CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD +## Using OpenGL loader: glad2 +# SOURCES += ../libs/glad/src/gl.c +# CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD2 + ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 6a3592f1..fa4e4bb9 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -17,6 +17,8 @@ #include // Initialize with glewInit() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Initialize with gladLoadGL() +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) +#include // Initialize with gladLoadGL(...) or gladLoaderLoadGL() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. #include // Initialize with glbinding::Binding::initialize() @@ -84,6 +86,8 @@ int main(int, char**) bool err = glewInit() != GLEW_OK; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) + bool err = gladLoadGL(glfwGetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index 41826741..e8009a4c 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -42,6 +42,10 @@ CXXFLAGS += -I../libs/gl3w -DIMGUI_IMPL_OPENGL_LOADER_GL3W # SOURCES += ../libs/glad/src/glad.c # CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD +## Using OpenGL loader: glad2 +# SOURCES += ../libs/glad/src/gl.c +# CXXFLAGS += -I../libs/glad/include -DIMGUI_IMPL_OPENGL_LOADER_GLAD2 + ## Using OpenGL loader: glbinding ## This assumes a system-wide installation ## of either version 3.0.0 (or newer) diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 3146084d..96e5617b 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -19,6 +19,8 @@ #include // Initialize with glewInit() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Initialize with gladLoadGL() +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) +#include // Initialize with gladLoadGL(...) or gladLoaderLoadGL() #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. #include // Initialize with glbinding::Binding::initialize() @@ -79,6 +81,8 @@ int main(int, char**) bool err = glewInit() != GLEW_OK; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) + bool err = gladLoadGL((GLADloadfunc) SDL_GL_GetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 028a704b..df64bfa2 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-07-01: 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. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. @@ -101,6 +102,8 @@ #include // Needs to be initialized with glewInit() in user's code. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) #include // Needs to be initialized with gladLoadGL() in user's code. +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) +#include // Needs to be initialized with gladLoadGL(...) or gladLoaderLoadGL() in user's code. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) #ifndef GLFW_INCLUDE_NONE #define GLFW_INCLUDE_NONE // GLFW including OpenGL headers causes ambiguity or multiple definition errors. @@ -189,6 +192,8 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) gl_loader = "GLEW"; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) gl_loader = "GLAD"; +#elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) + gl_loader = "GLAD2"; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) gl_loader = "glbinding2"; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index 07d35219..14eb2842 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -49,6 +49,7 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); && !defined(IMGUI_IMPL_OPENGL_LOADER_GL3W) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLEW) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) \ + && !defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING3) \ && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) @@ -68,6 +69,8 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); #define IMGUI_IMPL_OPENGL_LOADER_GLEW #elif __has_include() #define IMGUI_IMPL_OPENGL_LOADER_GLAD +#elif __has_include() + #define IMGUI_IMPL_OPENGL_LOADER_GLAD2 #elif __has_include() #define IMGUI_IMPL_OPENGL_LOADER_GL3W #elif __has_include() From fb7f6cab8c322731da336e553915e944bf386e62 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 14:36:00 +0200 Subject: [PATCH 143/959] Backends: Amend, docs + extra comments. (#3330, #3245) --- docs/CHANGELOG.txt | 1 + examples/README.txt | 4 ++-- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_sdl_opengl3/main.cpp | 2 +- examples/imgui_impl_opengl3.cpp | 2 +- imgui_draw.cpp | 7 +++++-- 6 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8f4de8d9..6ee96d78 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other Changes: - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] +- Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 35ee87b9..8c89ef00 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -204,7 +204,7 @@ example_glfw_opengl2/ GLFW + OpenGL2 example (legacy, fixed pipeline). = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp **DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** - **Prefer using OPENGL3 code (with gl3w/glew/glad/glbinding, you can replace the OpenGL function loader)** + **Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)** This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to make things more complicated, will require your code to reset many OpenGL attributes to their initial @@ -253,7 +253,7 @@ example_sdl_opengl2/ SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline). = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp **DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** - **Prefer using OPENGL3 code (with gl3w/glew/glad/glbinding, you can replace the OpenGL function loader)** + **Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)** This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to make things more complicated, will require your code to reset many OpenGL attributes to their initial diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index fa4e4bb9..30943301 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -87,7 +87,7 @@ int main(int, char**) #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) - bool err = gladLoadGL(glfwGetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. + bool err = gladLoadGL(glfwGetProcAddress) == 0; // glad2 recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 96e5617b..92d03138 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -82,7 +82,7 @@ int main(int, char**) #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD) bool err = gladLoadGL() == 0; #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLAD2) - bool err = gladLoadGL((GLADloadfunc) SDL_GL_GetProcAddress) == 0; // glad docs recommend using the windowing library loader instead of the (optionally) bundled one. + bool err = gladLoadGL((GLADloadfunc)SDL_GL_GetProcAddress) == 0; // glad2 recommend using the windowing library loader instead of the (optionally) bundled one. #elif defined(IMGUI_IMPL_OPENGL_LOADER_GLBINDING2) bool err = false; glbinding::Binding::initialize(); diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index df64bfa2..cb60304d 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,7 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2020-07-01: OpenGL: Added support for glad2 OpenGL 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. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index cdaa34fa..864364e9 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -717,8 +717,11 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 // [PATH 1] Texture-based lines (thick or non-thick) // [PATH 2] Non texture-based lines (non-thick) - // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus one pixel for AA - // We don't use AA_SIZE here because the +1 is tied to the generated texture and so alternate values won't work without changes to that code + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus "one pixel" for AA. + // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture + // (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code. + // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to + // allow scaling geometry while preserving one-screen-pixel AA fringe). const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; // If line is not closed, the first and last points need to be generated differently as there are no normals to blend From cbade7b16d3b7f1bbcd257a9639209e937a88224 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 10 Jul 2020 19:04:58 +0200 Subject: [PATCH 144/959] Docking: Workaround recovery for node created without the _ockSpace flags later becoming DockSpace. (#3340) --- imgui.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 7b31979c..36d27145 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14145,6 +14145,17 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla node->OnlyNodeWithWindows = NULL; IM_ASSERT(node->IsRootNode()); + + // We need to handle the rare case were a central node is missing. + // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace. + // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. + // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. + // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, + // as it doesn't make sense for an empty dockspace to not have this property. + if (node->IsLeafNode() && !node->IsCentralNode()) + node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; + + // Update the node DockNodeUpdate(node); g.WithinEndChild = true; @@ -15765,14 +15776,16 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("Dock nodes")) { + static bool root_nodes_only = true; ImGuiDockContext* dc = &g.DockContext; + ImGui::Checkbox("List root nodes", &root_nodes_only); ImGui::Checkbox("Ctrl shows window dock info", &show_docking_nodes); if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ImGui::SameLine(); if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) - if (node->IsRootNode()) + if (!root_nodes_only || node->IsRootNode()) Funcs::NodeDockNode(node, "Node"); ImGui::TreePop(); } From 550f110354fc922d1a471906360558b14374c863 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 12 Jul 2020 23:51:13 +0200 Subject: [PATCH 145/959] InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (#3349) --- docs/CHANGELOG.txt | 5 +++++ docs/TODO.txt | 3 ++- imgui_draw.cpp | 5 ++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6ee96d78..0264e314 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,11 @@ HOW TO UPDATE? Other Changes: +- InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more + than ~16 KB characters. (Note that current code is going to show corrupted display if after + clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText + call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare + but it will be addressed later). (#3349) - ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - This change will facilitate the wider use of thick borders in future style changes. diff --git a/docs/TODO.txt b/docs/TODO.txt index abb9d513..9502e264 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -308,7 +308,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font/atlas: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. - font/draw: vertical and/or rotated text renderer (#705) - vertical is easier clipping wise - font/draw: need to be able to specify wrap start position. - - font/draw: better reserve policy for large horizontal block of text (shouldn't reserve for all clipped lines) + - font/draw: better reserve policy for large horizontal block of text (shouldn't reserve for all clipped lines). also see #3349. + - font/draw: fix for drawing 16k+ visible characters in same call. - font/draw: underline, squiggle line rendering helpers. - font: optimization: for monospace font (like the default one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance (need to make sure TAB is still correct), would save on cache line. - font: add support for kerning, probably optional. A) perhaps default to (32..128)^2 matrix ~ 9K entries = 36KB, then hash for non-ascii?. B) or sparse lookup into per-char list? diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 864364e9..09b5a413 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -517,7 +517,7 @@ void ImDrawList::_OnChangedVtxOffset() // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this. _VtxCurrentIdx = 0; ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1]; - IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); + //IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); // See #3349 if (curr_cmd->ElemCount != 0) { AddDrawCmd(); @@ -582,6 +582,9 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { + // FIXME: In theory we should be testing that vtx_count <64k here. + // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us + // to not make that check until we rework the text functions to handle clipping and large horizontal lines better. _CmdHeader.VtxOffset = VtxBuffer.Size; _OnChangedVtxOffset(); } From eefae082617cd36d9b1d412e481a7913ab0ef3f2 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 14 Jul 2020 18:36:35 +0200 Subject: [PATCH 146/959] Nav: Fixed clicking on void from not clearing focused window. Amend d31fe97f7. (#3344, #2880) This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. --- docs/CHANGELOG.txt | 5 ++++- imgui.cpp | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0264e314..b11ed192 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,9 @@ HOW TO UPDATE? Other Changes: +- Nav: Fixed clicking on void from not clearing focused window. + This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard + flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (Note that current code is going to show corrupted display if after clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText @@ -62,7 +65,7 @@ Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.77 Breaking Changes: - Removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular() function. Please - note that this is a Beta api and will likely be reworked in order to support multi-DPI accross + note that this is a Beta api and will likely be reworked in order to support multi-DPI across multiple monitors. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor diff --git a/imgui.cpp b/imgui.cpp index 37e611ad..b17e2ee8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3367,7 +3367,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; } - else if (root_window != NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) + else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { // Clicking on void disable focus FocusWindow(NULL); From 825f2ae455b90862fd9637115f4a70bfb17c9290 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 16 Jul 2020 17:20:24 +0200 Subject: [PATCH 147/959] Demo: Tweak "child windows" section. (#3318) --- docs/CHANGELOG.txt | 1 + imgui_demo.cpp | 22 +++++++--------------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b11ed192..ebce7da0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,7 @@ Other Changes: - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] +- Demo: Tweak "Child Windows" section. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d66bf014..97e2951d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1969,12 +1969,6 @@ static void ShowDemoWindowLayout() ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel); ImGui::Checkbox("Disable Menu", &disable_menu); - static int line = 50; - bool goto_line = ImGui::Button("Goto"); - ImGui::SameLine(); - ImGui::SetNextItemWidth(100); - goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); - // Child 1: no border, enable horizontal scrollbar { ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; @@ -1982,13 +1976,7 @@ static void ShowDemoWindowLayout() window_flags |= ImGuiWindowFlags_NoScrollWithMouse; ImGui::BeginChild("ChildL", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags); for (int i = 0; i < 100; i++) - { ImGui::Text("%04d: scrollable region", i); - if (goto_line && line == i) - ImGui::SetScrollHereY(); - } - if (goto_line && line >= 100) - ImGui::SetScrollHereY(); ImGui::EndChild(); } @@ -2034,15 +2022,21 @@ static void ShowDemoWindowLayout() // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from // the POV of the parent window). See 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details. { - ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 10); + static int offset_x = 0; + ImGui::SetNextItemWidth(100); + ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000); + + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x); ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); ImGui::BeginChild("Red", ImVec2(200, 100), true, ImGuiWindowFlags_None); for (int n = 0; n < 50; n++) ImGui::Text("Some test %d", n); ImGui::EndChild(); + bool child_is_hovered = ImGui::IsItemHovered(); ImVec2 child_rect_min = ImGui::GetItemRectMin(); ImVec2 child_rect_max = ImGui::GetItemRectMax(); ImGui::PopStyleColor(); + ImGui::Text("Hovered: %d", child_is_hovered); ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y); } @@ -2428,8 +2422,6 @@ static void ShowDemoWindowLayout() static float scroll_to_pos_px = 200.0f; ImGui::Checkbox("Decoration", &enable_extra_decorations); - ImGui::SameLine(); - HelpMarker("We expose this for testing because scrolling sometimes had issues with window decoration such as menu-bars."); ImGui::Checkbox("Track", &enable_track); ImGui::PushItemWidth(100); From 4be8155002b2248335eeac57fb185f2020f8f8bb Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 16 Jul 2020 21:51:49 +0200 Subject: [PATCH 148/959] Style Editor: Added preview of circle auto-tessellation when editing the corresponding value.. --- docs/CHANGELOG.txt | 3 ++- imgui_demo.cpp | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ebce7da0..4e3a5a1a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Other Changes: - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] - Demo: Tweak "Child Windows" section. +- Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] @@ -129,7 +130,7 @@ Other Changes: Updated various links/wiki accordingly. Added FAQ entry about DPI. (#2861) [@ButternCream, @ocornut] - CI: Added CI test to verify we're never accidentally dragging libstdc++ (on some compiler setups, static constructors for non-pod data seems to drag in libstdc++ due to thread-safety concerns). - Fixed a static constructor which led to this dependency on some compiler setups. + Fixed a static constructor which led to this dependency on some compiler setups. [@rokups] - Backends: Win32: Support for #define NOGDI, won't try to call GetDeviceCaps(). (#3137, #2327) - Backends: Win32: Fix _WIN32_WINNT < 0x0600 (MinGW defaults to 0x502 == Windows 2003). (#3183) - Backends: SDL: Report a zero display-size when window is minimized, consistent with other backends, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 97e2951d..49ac4180 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3829,7 +3829,28 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f; - ImGui::DragFloat("Circle segment Max Error", &style.CircleSegmentMaxError, 0.01f, 0.10f, 10.0f, "%.2f"); + + // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. + ImGui::DragFloat("Circle Segment Max Error", &style.CircleSegmentMaxError, 0.01f, 0.10f, 10.0f, "%.2f"); + if (ImGui::IsItemActive()) + { + ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); + ImGui::BeginTooltip(); + ImVec2 p = ImGui::GetCursorScreenPos(); + float RAD_MIN = 10.0f, RAD_MAX = 80.0f; + float off_x = 10.0f; + for (int n = 0; n < 7; n++) + { + const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (7.0f - 1.0f); + ImGui::GetWindowDrawList()->AddCircle(ImVec2(p.x + off_x + rad, p.y + RAD_MAX), rad, ImGui::GetColorU32(ImGuiCol_Text), 0); + off_x += 10.0f + rad * 2.0f; + } + ImGui::Dummy(ImVec2(off_x, RAD_MAX * 2.0f)); + ImGui::EndTooltip(); + } + ImGui::SameLine(); + HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation 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::PopItemWidth(); From e223bd8177f15eb60698d8cb0f8a9d455b77b783 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 16 Jul 2020 22:25:23 +0200 Subject: [PATCH 149/959] ImDrawList: changed AddCircle(), AddCircleFilled() default num_segments from 12 to 0. --- docs/CHANGELOG.txt | 5 ++++- imgui.h | 5 +++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4e3a5a1a..7846eace 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,7 +37,7 @@ HOW TO UPDATE? Other Changes: -- Nav: Fixed clicking on void from not clearing focused window. +- Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more @@ -51,6 +51,9 @@ Other Changes: - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. +- ImDrawList: changed AddCircle(), AddCircleFilled() default num_segments from 12 to 0, effectively + enabling auto-tessellation by default. Tweak tessellation in Style Editor->Rendering section, or + by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] - Demo: Tweak "Child Windows" section. diff --git a/imgui.h b/imgui.h index 6f4dec52..4517aabc 100644 --- a/imgui.h +++ b/imgui.h @@ -2052,6 +2052,7 @@ struct ImDrawList // Primitives // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). + // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. // In future versions we will use textures to provide cheaper and higher-quality circles. // Use AddNgon() and AddNgonFilled() functions if you need to guaranteed a specific number of sides. IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); @@ -2062,8 +2063,8 @@ struct ImDrawList IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); - IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); From cba52b66afa44a886f82b4c78e12e4ed389c7068 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 17 Jul 2020 18:11:01 +0200 Subject: [PATCH 150/959] Backends: GLFW: Fixed enabling ImGuiBackendFlags_HasMouseHoveredViewport broken by 950539b7. As it turns out, back-end passing NULL hovered with HasMouseHoveredViewport is also broken which defeats some of its purpose. --- examples/imgui_impl_glfw.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 1fab7634..d163a72a 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -166,7 +166,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy) #endif io.BackendPlatformName = "imgui_impl_glfw"; @@ -348,7 +348,7 @@ static void ImGui_ImplGlfw_UpdateMousePosAndButtons() // rectangles and last focused time of every viewports it knows about. It will be unaware of other windows that may be sitting between or over your windows. // [GLFW] FIXME: This is currently only correct on Win32. See what we do below with the WM_NCHITTEST, missing an equivalent for other systems. // See https://github.com/glfw/glfw/issues/1236 if you want to help in making this a GLFW feature. -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !(viewport->Flags & ImGuiViewportFlags_NoInputs)) io.MouseHoveredViewport = viewport->ID; #endif @@ -586,7 +586,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) { if (data->WindowOwned) { -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) HWND hwnd = (HWND)viewport->PlatformHandleRaw; ::RemovePropA(hwnd, "IMGUI_VIEWPORT"); #endif @@ -600,7 +600,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) // We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs". // In the meanwhile we implement custom per-platform workarounds here (FIXME-VIEWPORT: Implement same work-around for Linux/OSX!) -#if defined(_WIN32) && GLFW_HAS_GLFW_HOVERED +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) static WNDPROC g_GlfwWndProc = NULL; static LRESULT CALLBACK WndProcNoInputs(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { @@ -634,7 +634,7 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) } // GLFW hack: install hook for WM_NCHITTEST message handler -#if GLFW_HAS_GLFW_HOVERED && defined(_WIN32) +#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) ::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport); if (g_GlfwWndProc == NULL) g_GlfwWndProc = (WNDPROC)::GetWindowLongPtr(hwnd, GWLP_WNDPROC); From 3d4af15d1d5f5d3746b69859308949c357e0c21e Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 17 Jul 2020 16:57:50 +0300 Subject: [PATCH 151/959] Backends GLFW: Use GLFW_MOUSE_PASSTHROUGH when available. --- examples/imgui_impl_glfw.cpp | 24 ++++++++++++++++++------ examples/imgui_impl_glfw.h | 3 +++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index d163a72a..e7dc10ca 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -10,6 +10,9 @@ // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// Issues: +// [ ] Platform: Multi-viewport support: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). + // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui @@ -63,6 +66,11 @@ #else #define GLFW_HAS_NEW_CURSORS (0) #endif +#ifdef GLFW_MOUSE_PASSTHROUGH // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2020-07-17 (passthrough) +#define GLFW_HAS_MOUSE_PASSTHROUGH (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_MOUSE_PASSTHROUGH +#else +#define GLFW_HAS_MOUSE_PASSTHROUGH (0) +#endif // Data enum GlfwClientApi @@ -166,7 +174,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)) io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can set io.MouseHoveredViewport correctly (optional, not easy) #endif io.BackendPlatformName = "imgui_impl_glfw"; @@ -348,8 +356,12 @@ static void ImGui_ImplGlfw_UpdateMousePosAndButtons() // rectangles and last focused time of every viewports it knows about. It will be unaware of other windows that may be sitting between or over your windows. // [GLFW] FIXME: This is currently only correct on Win32. See what we do below with the WM_NCHITTEST, missing an equivalent for other systems. // See https://github.com/glfw/glfw/issues/1236 if you want to help in making this a GLFW feature. -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) - if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !(viewport->Flags & ImGuiViewportFlags_NoInputs)) +#if GLFW_HAS_MOUSE_PASSTHROUGH || (GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)) + const bool window_no_input = (viewport->Flags & ImGuiViewportFlags_NoInputs) != 0; +#if GLFW_HAS_MOUSE_PASSTHROUGH + glfwSetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH, window_no_input); +#endif + if (glfwGetWindowAttrib(window, GLFW_HOVERED) && !window_no_input) io.MouseHoveredViewport = viewport->ID; #endif } @@ -586,7 +598,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) { if (data->WindowOwned) { -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) HWND hwnd = (HWND)viewport->PlatformHandleRaw; ::RemovePropA(hwnd, "IMGUI_VIEWPORT"); #endif @@ -600,7 +612,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport) // We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs". // In the meanwhile we implement custom per-platform workarounds here (FIXME-VIEWPORT: Implement same work-around for Linux/OSX!) -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) static WNDPROC g_GlfwWndProc = NULL; static LRESULT CALLBACK WndProcNoInputs(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { @@ -634,7 +646,7 @@ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport) } // GLFW hack: install hook for WM_NCHITTEST message handler -#if GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) +#if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32) ::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport); if (g_GlfwWndProc == NULL) g_GlfwWndProc = (WNDPROC)::GetWindowLongPtr(hwnd, GWLP_WNDPROC); diff --git a/examples/imgui_impl_glfw.h b/examples/imgui_impl_glfw.h index bea576a0..9ad0d9b3 100644 --- a/examples/imgui_impl_glfw.h +++ b/examples/imgui_impl_glfw.h @@ -9,6 +9,9 @@ // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// Issues: +// [ ] Platform: Multi-viewport support: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor). + // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui From b335225caa7816ceb833703ebde4c82a5c46e0f0 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 17:24:52 +0200 Subject: [PATCH 152/959] Internals: Extract ImFontAtlasBuildRender1bppRectFromString() out of ImFontAtlasBuildRenderDefaultTexData() + minor renaming, comments --- imgui_draw.cpp | 36 +++++++++++++++++++++--------------- imgui_internal.h | 1 + 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 09b5a413..137e2494 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1667,10 +1667,10 @@ ImFontConfig::ImFontConfig() //----------------------------------------------------------------------------- // A work of art lies ahead! (. = white layer, X = black layer, others are blank) -// The white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. -const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 108; -const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; -static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = +// The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. +const int FONT_ATLAS_DEFAULT_TEX_DATA_W = 108; // Actual texture will be 2 times that + 1 spacing. +const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27; +static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX " "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X " @@ -2003,7 +2003,7 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; out_uv_border[0] = (pos) * TexUvScale; out_uv_border[1] = (pos + size) * TexUvScale; - pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; + pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1; out_uv_fill[0] = (pos) * TexUvScale; out_uv_fill[1] = (pos + size) * TexUvScale; return true; @@ -2366,6 +2366,16 @@ void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opa } } +void ImFontAtlasBuildRender1bppRectFromString(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; +} + static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors); @@ -2375,15 +2385,11 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) { // Render/copy pixels - IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H); - for (int y = 0, n = 0; y < FONT_ATLAS_DEFAULT_TEX_DATA_H; y++) - for (int x = 0; x < FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF; x++, n++) - { - const int offset0 = (int)(r->X + x) + (int)(r->Y + y) * w; - const int offset1 = offset0 + FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF + 1; - atlas->TexPixelsAlpha8[offset0] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == '.' ? 0xFF : 0x00; - atlas->TexPixelsAlpha8[offset1] = FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[n] == 'X' ? 0xFF : 0x00; - } + 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; + ImFontAtlasBuildRender1bppRectFromString(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); + ImFontAtlasBuildRender1bppRectFromString(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 { @@ -2433,7 +2439,7 @@ void ImFontAtlasBuildInit(ImFontAtlas* atlas) if (atlas->PackIdMouseCursors < 0) { if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors)) - atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H); + 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); } diff --git a/imgui_internal.h b/imgui_internal.h index a6245d1a..27212402 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2022,6 +2022,7 @@ IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); +IMGUI_API void ImFontAtlasBuildRender1bppRectFromString(ImFontAtlas* atlas, int atlas_x, int atlas_y, int w, int h, const char* in_str, char in_marker_char, unsigned char 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); From fdc526e8f81b74752c6d057e7e28629336e66f30 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 18:18:30 +0200 Subject: [PATCH 153/959] Stop advertisting for Drag v_min>v_max which was introduced in 1.73 likely for 0537ac00 then made unnecessary with 32c33c66, added undocumented ImGuiItemFlags_ReadOnly as possible replacement (unused), (#211) --- imgui.h | 1 - imgui_internal.h | 1 + imgui_widgets.cpp | 6 ++++++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 4517aabc..bc056857 100644 --- a/imgui.h +++ b/imgui.h @@ -464,7 +464,6 @@ namespace ImGui // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - // - Use v_min > v_max to lock edits. IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); diff --git a/imgui_internal.h b/imgui_internal.h index 27212402..5399a122 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -575,6 +575,7 @@ enum ImGuiItemFlags_ ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) + ImGuiItemFlags_ReadOnly = 1 << 7, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags_Default_ = 0 }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 86295bcd..9b3ec52d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2113,6 +2113,8 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } if (g.ActiveId != id) return false; + if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + return false; switch (data_type) { @@ -2558,6 +2560,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { + ImGuiContext& g = *GImGui; + if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + return false; + switch (data_type) { case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } From b8c22bdb2849577d27314fd61df96c4978c7359c Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 19:03:48 +0200 Subject: [PATCH 154/959] DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) --- docs/CHANGELOG.txt | 2 ++ imgui_demo.cpp | 3 ++- imgui_widgets.cpp | 22 ++++++++++++++++++---- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7846eace..c2850811 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,8 @@ Other Changes: - Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) +- DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both + min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (Note that current code is going to show corrupted display if after clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 49ac4180..647e4298 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1491,7 +1491,8 @@ static void ShowDemoWindowWidgets() { static float begin = 10, end = 90; static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9b3ec52d..c0de761a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2278,10 +2278,17 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); - bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power); + float min = (v_min >= v_max) ? -FLT_MAX : v_min; + float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, format_max ? format_max : format, power); + + min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + max = (v_min >= v_max) ? FLT_MAX : v_max; + if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2323,10 +2330,17 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); - bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format); + int min = (v_min >= v_max) ? INT_MIN : v_min; + int max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit + bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, format_max ? format_max : format); + + min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + max = (v_min >= v_max) ? INT_MAX : v_max; + if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit + value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); From bbd061538cf42c850b9a0b88f03741393db18fb4 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 Jul 2020 13:00:56 +0200 Subject: [PATCH 155/959] Internals: Drag/Sliders: simplified some code. --- imgui_widgets.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c0de761a..ecae7d0a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2166,7 +2166,6 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Tabbing or CTRL-clicking on Drag turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); bool temp_input_is_active = TempInputIsActive(id); - bool temp_input_start = false; if (!temp_input_is_active) { const bool focus_requested = FocusableItemRegister(window, id); @@ -2180,14 +2179,14 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); if (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id) { - temp_input_start = true; + temp_input_is_active = true; FocusableItemUnregister(window); } } } // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. - if (temp_input_is_active || temp_input_start) + if (temp_input_is_active) return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame @@ -2638,7 +2637,6 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Tabbing or CTRL-clicking on Slider turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); bool temp_input_is_active = TempInputIsActive(id); - bool temp_input_start = false; if (!temp_input_is_active) { const bool focus_requested = FocusableItemRegister(window, id); @@ -2651,14 +2649,14 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); if (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id) { - temp_input_start = true; + temp_input_is_active = true; FocusableItemUnregister(window); } } } // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. - if (temp_input_is_active || temp_input_start) + if (temp_input_is_active) return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); // Draw frame From c7f5876f8ac6e9fdbe47da444da0d5eaa1270f09 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 Jul 2020 14:44:58 +0200 Subject: [PATCH 156/959] Internals: backport window HitTestHole code from docking branch + RenderRectFilledWithHole() helper. (#1512, #3368) --- imgui.cpp | 20 ++++++++++++++++++++ imgui_draw.cpp | 16 ++++++++++++++++ imgui_internal.h | 4 ++++ 3 files changed, 40 insertions(+) diff --git a/imgui.cpp b/imgui.cpp index b17e2ee8..59845af7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4295,6 +4295,16 @@ static void FindHoveredWindow() if (!bb.Contains(g.IO.MousePos)) continue; + // Support for one rectangular hole in any given window + // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) + if (window->HitTestHoleSize.x != 0) + { + ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y); + ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y); + if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos)) + continue; + } + // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches. if (hovered_window == NULL) hovered_window = window; @@ -5940,6 +5950,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if (!(flags & ImGuiWindowFlags_NoTitleBar)) RenderWindowTitleBarContents(window, title_bar_rect, name, p_open); + // Clear hit test shape every frame + window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0; + // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. // Maybe we can support CTRL+C on every element? @@ -6429,6 +6442,13 @@ void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond co window->Collapsed = collapsed; } +void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) +{ + IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters + window->HitTestHoleSize = ImVec2ih(size); + window->HitTestHoleOffset = ImVec2ih(pos - window->Pos); +} + void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) { SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 137e2494..ad44b671 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -3501,6 +3501,22 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im draw_list->PathFillConvex(col); } +void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding) +{ + const bool fill_L = (inner.Min.x > outer.Min.x); + const bool fill_R = (inner.Max.x < outer.Max.x); + const bool fill_U = (inner.Min.y > outer.Min.y); + const bool fill_D = (inner.Max.y < outer.Max.y); + if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, (fill_U ? 0 : ImDrawCornerFlags_TopLeft) | (fill_D ? 0 : ImDrawCornerFlags_BotLeft)); + if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, (fill_U ? 0 : ImDrawCornerFlags_TopRight) | (fill_D ? 0 : ImDrawCornerFlags_BotRight)); + if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, (fill_L ? 0 : ImDrawCornerFlags_TopLeft) | (fill_R ? 0 : ImDrawCornerFlags_TopRight)); + if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, (fill_L ? 0 : ImDrawCornerFlags_BotLeft) | (fill_R ? 0 : ImDrawCornerFlags_BotRight)); + if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawCornerFlags_TopLeft); + if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawCornerFlags_TopRight); + if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawCornerFlags_BotLeft); + if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawCornerFlags_BotRight); +} + // Helper for ColorPicker4() // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. // Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. diff --git a/imgui_internal.h b/imgui_internal.h index 5399a122..ea135fce 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1615,6 +1615,8 @@ struct IMGUI_API ImGuiWindow ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. + ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. + ImVec2ih HitTestHoleOffset; int LastFrameActive; // Last frame number the window was Active. float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) @@ -1775,6 +1777,7 @@ namespace ImGui IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); + IMGUI_API void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window); @@ -1943,6 +1946,7 @@ namespace ImGui IMGUI_API void RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow); IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); + IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // [1.71: 2019/06/07: Updating prototypes of some of the internal functions. Leaving those for reference for a short while] From 218ff3a2a5186a91bf1a053468e66727d1c34d73 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 Jul 2020 15:04:29 +0200 Subject: [PATCH 157/959] Internals: Backport one ->WasActive test in NavRestoreLastChildNavWindow() from 9bf6509c6 + minor/shallow bits from docking branch. --- imgui.cpp | 42 ++++++++++++++++++++++++++---------------- imgui.h | 4 ++-- imgui_demo.cpp | 5 +++-- imgui_internal.h | 4 ++++ 4 files changed, 35 insertions(+), 20 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 59845af7..a74e96a5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2467,6 +2467,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) return "Unknown"; } + //----------------------------------------------------------------------------- // [SECTION] RENDER HELPERS // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, @@ -5590,6 +5591,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f) window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); + // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. + window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); + window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; + // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) @@ -5912,8 +5917,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f); window->DC.MenuBarAppending = false; - window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); - window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); window->DC.TreeDepth = 0; window->DC.TreeJumpToParentOnPopMask = 0x00; @@ -7624,7 +7627,7 @@ void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; - //IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id); + IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id); if (g.OpenPopupStack.Size < current_stack_size + 1) { g.OpenPopupStack.push_back(popup_ref); @@ -7685,7 +7688,7 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to } if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below { - //IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep); + IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep); ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup); } } @@ -7693,6 +7696,7 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; + IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup); IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); // Trim open popup stack @@ -7737,7 +7741,7 @@ void ImGui::CloseCurrentPopup() break; popup_idx--; } - //IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); + IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); ClosePopupToLevel(popup_idx, true); // A common pattern is to close a popup when selecting a menu item/selectable that will open another window. @@ -8322,18 +8326,20 @@ void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags mov // This way we could find the last focused window among our children. It would be much less confusing this way? static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window) { - ImGuiWindow* parent_window = nav_window; - while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) - parent_window = parent_window->ParentWindow; - if (parent_window && parent_window != nav_window) - parent_window->NavLastChildNavWindow = nav_window; + ImGuiWindow* parent = nav_window; + while (parent && (parent->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) + parent = parent->ParentWindow; + if (parent && parent != nav_window) + parent->NavLastChildNavWindow = nav_window; } // Restore the last focused child. // Call when we are expected to land on the Main Layer (0) after FocusWindow() static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window) { - return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window; + if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive) + return window->NavLastChildNavWindow; + return window; } static void NavRestoreLayer(ImGuiNavLayer layer) @@ -9651,6 +9657,7 @@ void ImGui::LogButtons() LogToClipboard(); } + //----------------------------------------------------------------------------- // [SECTION] SETTINGS //----------------------------------------------------------------------------- @@ -9905,9 +9912,9 @@ static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; int x, y; int i; - if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) settings->Pos = ImVec2ih((short)x, (short)y); - else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) settings->Size = ImVec2ih((short)x, (short)y); - else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); + if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); } + else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); } + else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } } // Apply to existing windows (if any) @@ -10514,7 +10521,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Details for Docking #ifdef IMGUI_HAS_DOCK - if (ImGui::TreeNode("Docking")) + if (ImGui::TreeNode("Dock nodes")) { ImGui::TreePop(); } @@ -10526,6 +10533,9 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear")) ImGui::ClearIniSettings(); ImGui::SameLine(); + if (ImGui::SmallButton("Save to memory")) + ImGui::SaveIniSettingsToMemory(); + ImGui::SameLine(); if (ImGui::SmallButton("Save to disk")) ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); ImGui::SameLine(); @@ -10537,7 +10547,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) { for (int n = 0; n < g.SettingsHandlers.Size; n++) - ImGui::TextUnformatted(g.SettingsHandlers[n].TypeName); + ImGui::BulletText("%s", g.SettingsHandlers[n].TypeName); ImGui::TreePop(); } if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) diff --git a/imgui.h b/imgui.h index bc056857..00ea2f3d 100644 --- a/imgui.h +++ b/imgui.h @@ -723,7 +723,7 @@ namespace ImGui IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); // Inputs Utilities: Keyboard - // - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[]. + // - For 'int user_key_index' you can use your own indices/enums according to how your back-end/engine stored them in io.KeysDown[]. // - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index. IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. @@ -1434,7 +1434,7 @@ struct ImGuiStyle 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. - ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. + ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 647e4298..2acee763 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -228,8 +228,8 @@ void ImGui::ShowDemoWindow(bool* p_open) IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!"); // Examples Apps (accessible from the "Examples" menu) - static bool show_app_documents = false; static bool show_app_main_menu_bar = false; + static bool show_app_documents = false; static bool show_app_console = false; static bool show_app_log = false; static bool show_app_layout = false; @@ -241,8 +241,9 @@ void ImGui::ShowDemoWindow(bool* p_open) static bool show_app_window_titles = false; static bool show_app_custom_rendering = false; - if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); + if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); + if (show_app_console) ShowExampleAppConsole(&show_app_console); if (show_app_log) ShowExampleAppLog(&show_app_log); if (show_app_layout) ShowExampleAppLayout(&show_app_layout); diff --git a/imgui_internal.h b/imgui_internal.h index ea135fce..e5d72c74 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -163,6 +163,10 @@ namespace ImStb #define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__) #endif +// Debug Logging for selected systems. Remove the '((void)0) //' to enable. +//#define IMGUI_DEBUG_LOG_POPUP IMGUI_DEBUG_LOG // Enable log +#define IMGUI_DEBUG_LOG_POPUP(...) ((void)0) // Disable log + // Static Asserts #if (__cplusplus >= 201100) #define IM_STATIC_ASSERT(_COND) static_assert(_COND, "") From 76ddacd2a12f713a218116c849928ef2274d3f8b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 29 Jul 2020 15:26:31 +0200 Subject: [PATCH 158/959] Internals: Backport HoveredWindowUnderMovingWindow code from Docking branch. (effectively allowing a window to be a drag payload without have to make it _NoInputs) --- imgui.cpp | 29 +++++++++++++++++------------ imgui_internal.h | 2 ++ 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a74e96a5..28c975e2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3593,15 +3593,14 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // - 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. FindHoveredWindow(); - // Modal windows prevents cursor from hovering behind them. + // Modal windows prevents mouse from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); - if (modal_window) - if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) - g.HoveredRootWindow = g.HoveredWindow = NULL; + if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // Disabled mouse? if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) - g.HoveredWindow = g.HoveredRootWindow = NULL; + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward. int mouse_earliest_button_down = -1; @@ -3621,7 +3620,7 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) - g.HoveredWindow = g.HoveredRootWindow = NULL; + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app) if (g.WantCaptureMouseNextFrame != -1) @@ -3935,7 +3934,7 @@ void ImGui::Shutdown(ImGuiContext* context) g.CurrentWindowStack.clear(); g.WindowsById.Clear(); g.NavWindow = NULL; - g.HoveredWindow = g.HoveredRootWindow = NULL; + g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; g.MovingWindow = NULL; g.ColorModifiers.clear(); @@ -4274,6 +4273,7 @@ static void FindHoveredWindow() ImGuiContext& g = *GImGui; ImGuiWindow* hovered_window = NULL; + ImGuiWindow* hovered_window_ignoring_moving_window = NULL; if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) hovered_window = g.MovingWindow; @@ -4306,16 +4306,17 @@ static void FindHoveredWindow() continue; } - // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches. if (hovered_window == NULL) hovered_window = window; - if (hovered_window) + if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow)) + hovered_window_ignoring_moving_window = window; + if (hovered_window && hovered_window_ignoring_moving_window) break; } g.HoveredWindow = hovered_window; g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; - + g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window; } // Test if mouse cursor is hovering given rectangle @@ -9145,6 +9146,7 @@ void ImGui::NavUpdateWindowingOverlay() PopStyleVar(); } + //----------------------------------------------------------------------------- // [SECTION] DRAG AND DROP //----------------------------------------------------------------------------- @@ -9334,7 +9336,8 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) return false; ImGuiWindow* window = g.CurrentWindow; - if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow) return false; IM_ASSERT(id != 0); if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) @@ -9362,7 +9365,8 @@ bool ImGui::BeginDragDropTarget() ImGuiWindow* window = g.CurrentWindow; if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; - if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) + ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; + if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow) return false; const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect; @@ -10584,6 +10588,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); diff --git a/imgui_internal.h b/imgui_internal.h index e5d72c74..317288a2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1136,6 +1136,7 @@ struct ImGuiContext ImGuiWindow* CurrentWindow; // Window being drawn into ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; @@ -1342,6 +1343,7 @@ struct ImGuiContext CurrentWindow = NULL; HoveredWindow = NULL; HoveredRootWindow = NULL; + HoveredWindowUnderMovingWindow = NULL; MovingWindow = NULL; WheelingWindow = NULL; WheelingWindowTimer = 0.0f; From 5d87941451c8e0fc2ebf589b08b7e18cb13fd21b Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 2 Aug 2020 11:54:34 +0200 Subject: [PATCH 159/959] Fixed ImFontConfig::GlyphExtraSpacing and ImFontConfig::PixelSnapH settings being pulled from the merged/target font settings when merging fonts, instead of being pulled from the source font settings. --- docs/CHANGELOG.txt | 3 ++ imgui.h | 2 +- imgui_draw.cpp | 51 +++++++++++++++++++++----------- misc/freetype/imgui_freetype.cpp | 15 ++++------ 4 files changed, 44 insertions(+), 27 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c2850811..118813b7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -47,6 +47,9 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- Fonts: Fixed ImFontConfig::GlyphExtraSpacing and ImFontConfig::PixelSnapH settings being pulled + from the merged/target font settings when merging fonts, instead of being pulled from the source + font settings. - ImDrawList: Thick anti-aliased strokes (> 1.0f) with integer thickness now use a texture-based path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - This change will facilitate the wider use of thick borders in future style changes. diff --git a/imgui.h b/imgui.h index 00ea2f3d..80dcf771 100644 --- a/imgui.h +++ b/imgui.h @@ -2386,7 +2386,7 @@ struct ImFont IMGUI_API void BuildLookupTable(); IMGUI_API void ClearOutputData(); IMGUI_API void GrowIndex(int new_size); - IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); + IMGUI_API void AddGlyph(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 SetGlyphVisible(ImWchar c, bool visible); IMGUI_API void SetFallbackChar(ImWchar c); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index ad44b671..e9529e01 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2285,8 +2285,11 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) if (src_tmp.GlyphsCount == 0) continue; + // When merging fonts with MergeMode=true: + // - We can have multiple input fonts writing into a same destination font. + // - dst_font->ConfigData is != from cfg which is our source configuration. ImFontConfig& cfg = atlas->ConfigData[src_i]; - ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) + ImFont* dst_font = cfg.DstFont; const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels); int unscaled_ascent, unscaled_descent, unscaled_line_gap; @@ -2300,20 +2303,13 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) 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]; - - const float char_advance_x_org = pc.xadvance; - const float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX); - float char_off_x = font_off_x; - if (char_advance_x_org != char_advance_x_mod) - char_off_x += cfg.PixelSnapH ? ImFloor((char_advance_x_mod - char_advance_x_org) * 0.5f) : (char_advance_x_mod - char_advance_x_org) * 0.5f; - - // Register glyph stbtt_aligned_quad q; float dummy_x = 0.0f, dummy_y = 0.0f; stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &dummy_x, &dummy_y, &q, 0); - dst_font->AddGlyph((ImWchar)codepoint, q.x0 + char_off_x, q.y0 + font_off_y, q.x1 + char_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, char_advance_x_mod); + dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance); } } @@ -2468,10 +2464,11 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas) if (r->Font == NULL || r->GlyphID == 0) continue; + // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, GlyphExtraSpacing, PixelSnapH IM_ASSERT(r->Font->ContainerAtlas == atlas); ImVec2 uv0, uv1; atlas->CalcCustomRectUV(r, &uv0, &uv1); - r->Font->AddGlyph((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); + 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); } // Build all fonts lookup tables @@ -2881,8 +2878,29 @@ void ImFont::GrowIndex(int new_size) // 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). -void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +// 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font. +void ImFont::AddGlyph(ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) { + if (cfg != NULL) + { + // Clamp & recenter if needed + const float advance_x_original = advance_x; + advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX); + if (advance_x != advance_x_original) + { + float char_off_x = cfg->PixelSnapH ? ImFloor((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; + x0 += char_off_x; + x1 += char_off_x; + } + + // Snap to pixel + if (cfg->PixelSnapH) + advance_x = IM_ROUND(advance_x); + + // Bake spacing + advance_x += cfg->GlyphExtraSpacing.x; + } + Glyphs.resize(Glyphs.Size + 1); ImFontGlyph& glyph = Glyphs.back(); glyph.Codepoint = (unsigned int)codepoint; @@ -2895,14 +2913,13 @@ void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, glyph.V0 = v0; glyph.U1 = u1; glyph.V1 = v1; - glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX - - if (ConfigData->PixelSnapH) - glyph.AdvanceX = IM_ROUND(glyph.AdvanceX); + glyph.AdvanceX = advance_x; // 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 + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f); + MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad); } void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index b76bc6e0..1a03be0c 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -544,8 +544,11 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns if (src_tmp.GlyphsCount == 0) continue; + // When merging fonts with MergeMode=true: + // - We can have multiple input fonts writing into a same destination font. + // - dst_font->ConfigData is != from cfg which is our source configuration. ImFontConfig& cfg = atlas->ConfigData[src_i]; - ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) + ImFont* dst_font = cfg.DstFont; const float ascent = src_tmp.Font.Info.Ascender; const float descent = src_tmp.Font.Info.Descender; @@ -576,14 +579,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns for (int y = info.Height; y > 0; y--, blit_dst += blit_dst_stride, blit_src += blit_src_stride) memcpy(blit_dst, blit_src, blit_src_stride); - float char_advance_x_org = info.AdvanceX; - float char_advance_x_mod = ImClamp(char_advance_x_org, cfg.GlyphMinAdvanceX, cfg.GlyphMaxAdvanceX); - float char_off_x = font_off_x; - if (char_advance_x_org != char_advance_x_mod) - char_off_x += cfg.PixelSnapH ? IM_FLOOR((char_advance_x_mod - char_advance_x_org) * 0.5f) : (char_advance_x_mod - char_advance_x_org) * 0.5f; - // Register glyph - float x0 = info.OffsetX + char_off_x; + float x0 = info.OffsetX + font_off_x; float y0 = info.OffsetY + font_off_y; float x1 = x0 + info.Width; float y1 = y0 + info.Height; @@ -591,7 +588,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns 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((ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, char_advance_x_mod); + dst_font->AddGlyph(&cfg, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX); } src_tmp.Rects = NULL; From a876ad877db800061ac87a370c41488d6f1a5fe1 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 18:04:58 +0200 Subject: [PATCH 160/959] Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. + comments --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 14 ++++++++++++-- imgui_internal.h | 7 ++++--- imgui_widgets.cpp | 3 +++ 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 118813b7..bd308f37 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,6 +40,8 @@ Other Changes: - Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. This would be problematic e.g. in situation where the application relies on io.WantCaptureKeyboard flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) +- Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) + from marking the window as moved. - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.cpp b/imgui.cpp index 28c975e2..2778bc32 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3061,10 +3061,13 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) return false; if (!IsMouseHoveringRect(bb.Min, bb.Max)) return false; - if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) + if (g.NavDisableMouseHover) return false; - if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) + if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None) || (window->DC.ItemFlags & ImGuiItemFlags_Disabled)) + { + g.HoveredIdDisabled = true; return false; + } // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level // hover test in widgets code. We could also decide to split this function is two. @@ -3364,9 +3367,15 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (root_window != NULL && !is_closed_popup) { StartMouseMovingWindow(g.HoveredWindow); + + // Cancel moving if clicked outside of title bar if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; + + // Cancel moving if clicked over an item which was disabled or inhibited by popups + if (g.HoveredId == 0 && g.HoveredIdDisabled) + g.MovingWindow = NULL; } else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { @@ -3723,6 +3732,7 @@ void ImGui::NewFrame() g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; + g.HoveredIdDisabled = false; // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore) if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) diff --git a/imgui_internal.h b/imgui_internal.h index 317288a2..f587637f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1144,8 +1144,9 @@ struct ImGuiContext // Item/widgets state and tracking information ImGuiID HoveredId; // Hovered widget - bool HoveredIdAllowOverlap; ImGuiID HoveredIdPreviousFrame; + bool HoveredIdAllowOverlap; + bool HoveredIdDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. float HoveredIdTimer; // Measure contiguous hovering time float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active ImGuiID ActiveId; // Active widget @@ -1348,9 +1349,9 @@ struct ImGuiContext WheelingWindow = NULL; WheelingWindowTimer = 0.0f; - HoveredId = 0; + HoveredId = HoveredIdPreviousFrame = 0; HoveredIdAllowOverlap = false; - HoveredIdPreviousFrame = 0; + HoveredIdDisabled = false; HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; ActiveId = 0; ActiveIdIsAlive = 0; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ecae7d0a..ee4d1a8a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -595,6 +595,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } } + // Process while held bool held = false; if (g.ActiveId == id) { @@ -615,6 +616,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0; if ((release_in || release_anywhere) && !g.DragDropActive) { + // Report as pressed when releasing the mouse (this is the most common path) bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[mouse_button]; bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps if (!is_double_click_release && !is_repeating_already) @@ -627,6 +629,7 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { + // When activated using Nav, we hold on the ActiveID until activation button is released if (g.NavActivateDownId != id) ClearActiveID(); } From 4929a8e4a5795ba2148a59621aa579f490b03427 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 18:37:19 +0200 Subject: [PATCH 161/959] InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) and allowed to pass them to InvisibleButton(). --- docs/CHANGELOG.txt | 5 +++++ docs/TODO.txt | 1 + imgui.cpp | 2 ++ imgui.h | 19 +++++++++++++++++-- imgui_internal.h | 43 ++++++++++++++++++------------------------- imgui_widgets.cpp | 6 +++--- 6 files changed, 46 insertions(+), 30 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bd308f37..ea67baa6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,11 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) + and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. + This is a small but rather important change because lots of multi-button behaviors could previously + only be achieved using lower-level/internal API. Now also available via high-level InvisibleButton() + with is a de-facto versatile building block to creating custom widgets with the public API. - Fonts: Fixed ImFontConfig::GlyphExtraSpacing and ImFontConfig::PixelSnapH settings being pulled from the merged/target font settings when merging fonts, instead of being pulled from the source font settings. diff --git a/docs/TODO.txt b/docs/TODO.txt index 9502e264..413301d0 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -207,6 +207,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - popups: clicking outside (to close popup) and holding shouldn't drag window below. - popups: add variant using global identifier similar to Begin/End (#402) - popups: border options. richer api like BeginChild() perhaps? (#197) + - popups: flags could be reworked to allow both mouse buttons as index (0..5 and as flags using higher-bit) allowing to or them. - popups/modals: although it is sometimes convenient that popups/modals lifetime is owned by imgui, we could also a bool-owned-by-user api as long as Begin() return value testing is enforced. - tooltip: drag and drop with tooltip near monitor edges lose/changes its last direction instead of locking one. The drag and drop tooltip should always follow without changing direction. diff --git a/imgui.cpp b/imgui.cpp index 2778bc32..efa38ffe 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4455,6 +4455,7 @@ bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button) return g.IO.MouseDoubleClicked[button]; } +// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame. // [Internal] This doesn't test if the button is pressed bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold) { @@ -7848,6 +7849,7 @@ void ImGui::EndPopup() g.WithinEndChild = false; } +// Open a popup if mouse is released over the item bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui.h b/imgui.h index 80dcf771..f3b28d74 100644 --- a/imgui.h +++ b/imgui.h @@ -153,6 +153,7 @@ typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: f typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags +typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() @@ -437,7 +438,7 @@ namespace ImGui // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text - IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); 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)); // <0 frame_padding uses default frame padding settings. 0 for no padding @@ -446,7 +447,7 @@ namespace ImGui IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1, 0), const char* overlay = NULL); - IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + 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 // Widgets: Combo Box // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. @@ -877,6 +878,7 @@ enum ImGuiTreeNodeFlags_ // small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. // It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. // - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. +// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). enum ImGuiPopupFlags_ { ImGuiPopupFlags_None = 0, @@ -1221,6 +1223,19 @@ enum ImGuiStyleVar_ #endif }; +// Flags for InvisibleButton() [extended in imgui_internal.h] +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_None = 0, + ImGuiButtonFlags_MouseButtonLeft = 1 << 0, // React on left mouse button (default) + ImGuiButtonFlags_MouseButtonRight = 1 << 1, // React on right mouse button + ImGuiButtonFlags_MouseButtonMiddle = 1 << 2, // React on center mouse button + + // [Internal] + ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, + ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft +}; + // Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() enum ImGuiColorEditFlags_ { diff --git a/imgui_internal.h b/imgui_internal.h index f587637f..e0f8ae02 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -604,32 +604,25 @@ enum ImGuiItemStatusFlags_ #endif }; -enum ImGuiButtonFlags_ +// Extend ImGuiButtonFlags_ +enum ImGuiButtonFlagsPrivate_ { - ImGuiButtonFlags_None = 0, - ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat - ImGuiButtonFlags_PressedOnClick = 1 << 1, // return true on click (mouse down event) - ImGuiButtonFlags_PressedOnClickRelease = 1 << 2, // [Default] return true on click + release on same item <-- this is what the majority of Button are using - ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 3, // return true on click + release even if the release event is not done while hovering the item - ImGuiButtonFlags_PressedOnRelease = 1 << 4, // return true on release (default requires click+release) - ImGuiButtonFlags_PressedOnDoubleClick = 1 << 5, // return true on double-click (default requires click+release) - ImGuiButtonFlags_PressedOnDragDropHold = 1 << 6, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) - ImGuiButtonFlags_FlattenChildren = 1 << 7, // allow interactions even if a child window is overlapping - ImGuiButtonFlags_AllowItemOverlap = 1 << 8, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap() - ImGuiButtonFlags_DontClosePopups = 1 << 9, // disable automatically closing parent popup on press // [UNUSED] - ImGuiButtonFlags_Disabled = 1 << 10, // disable interactions - ImGuiButtonFlags_AlignTextBaseLine = 1 << 11, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine - ImGuiButtonFlags_NoKeyModifiers = 1 << 12, // disable mouse interaction if a key modifier is held - ImGuiButtonFlags_NoHoldingActiveId = 1 << 13, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) - ImGuiButtonFlags_NoNavFocus = 1 << 14, // don't override navigation focus when activated - ImGuiButtonFlags_NoHoveredOnFocus = 1 << 15, // don't report as hovered when nav focus is on this item - ImGuiButtonFlags_MouseButtonLeft = 1 << 16, // [Default] react on left mouse button - ImGuiButtonFlags_MouseButtonRight = 1 << 17, // react on right mouse button - ImGuiButtonFlags_MouseButtonMiddle = 1 << 18, // react on center mouse button - - ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, - ImGuiButtonFlags_MouseButtonShift_ = 16, - ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft, + ImGuiButtonFlags_PressedOnClick = 1 << 4, // return true on click (mouse down event) + ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, // [Default] return true on click + release on same item <-- this is what the majority of Button are using + ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item + ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release) + ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) + ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat + ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping + ImGuiButtonFlags_AllowItemOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap() + ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press // [UNUSED] + ImGuiButtonFlags_Disabled = 1 << 14, // disable interactions + ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + ImGuiButtonFlags_NoKeyModifiers = 1 << 16, // disable mouse interaction if a key modifier is held + ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) + ImGuiButtonFlags_NoNavFocus = 1 << 18, // don't override navigation focus when activated + ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ee4d1a8a..8e8bfca9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -685,7 +685,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags bool ImGui::Button(const char* label, const ImVec2& size_arg) { - return ButtonEx(label, size_arg, 0); + return ButtonEx(label, size_arg, ImGuiButtonFlags_None); } // Small buttons fits within text without additional vertical spacing. @@ -701,7 +701,7 @@ bool ImGui::SmallButton(const char* label) // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) -bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -718,7 +718,7 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held); + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); return pressed; } From 912c45ab232754ad7fe016efa880b1a066db8965 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 19:13:42 +0200 Subject: [PATCH 162/959] Demo: Improve "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. --- docs/CHANGELOG.txt | 2 + imgui_demo.cpp | 117 ++++++++++++++++++++++++++++++--------------- 2 files changed, 80 insertions(+), 39 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ea67baa6..70acf40c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,8 @@ Other Changes: by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] +- Demo: Improve "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. + Also showcase using InvisibleButton() will multiple mouse buttons flags. - Demo: Tweak "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2acee763..0ce046c5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4859,13 +4859,13 @@ static void ShowExampleAppCustomRendering(bool* p_open) // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not // exposed outside (to avoid messing with your types) In this example we are not using the maths operators! - ImDrawList* draw_list = ImGui::GetWindowDrawList(); if (ImGui::BeginTabBar("##TabBar")) { if (ImGui::BeginTabItem("Primitives")) { ImGui::PushItemWidth(-ImGui::GetFontSize() * 10); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); // Draw gradients // (note that those are currently exacerbating our sRGB/Linear issues) @@ -4949,56 +4949,95 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::BeginTabItem("Canvas")) { - static ImVector points; + struct ItemLine { ImVec2 p0, p1; ItemLine(const ImVec2& _p0, const ImVec2& _p1) { p0 = _p0; p1 = _p1; } }; + static ImVector lines; + static ImVec2 scrolling(0.0f, 0.0f); + static bool show_grid = true; static bool adding_line = false; - if (ImGui::Button("Clear")) points.clear(); - if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } - ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); - - // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use - // IsItemHovered(). But you can also draw directly and poll mouse/keyboard by yourself. - // You can manipulate the cursor using GetCursorPos() and SetCursorPos(). - // If you only use the ImDrawList API, you can notify the owner window of its extends with SetCursorPos(max). - ImVec2 canvas_p = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + + ImGui::Checkbox("Show grid", &show_grid); + ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu."); + + // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. + // Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls. + // To use a child window instead we could use, e.g: + // ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding + // ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color + // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_NoMove); + // ImGui::PopStyleColor(); + // ImGui::PopStyleVar(); + // [...] + // ImGui::EndChild(); + + // Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive() + ImVec2 canvas_p0 = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f; if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f; - draw_list->AddRectFilledMultiColor(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), IM_COL32(50, 50, 50, 255), IM_COL32(50, 50, 60, 255), IM_COL32(60, 60, 70, 255), IM_COL32(50, 50, 60, 255)); - draw_list->AddRect(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), IM_COL32(255, 255, 255, 255)); + ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y); - bool adding_preview = false; - ImGui::InvisibleButton("canvas", canvas_sz); - ImVec2 mouse_pos_global = ImGui::GetIO().MousePos; - ImVec2 mouse_pos_canvas = ImVec2(mouse_pos_global.x - canvas_p.x, mouse_pos_global.y - canvas_p.y); + // Draw border and background color + ImGuiIO& io = ImGui::GetIO(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255)); + draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255)); + + // This will catch our interactions + ImGui::InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight); + const bool is_hovered = ImGui::IsItemHovered(); // Hovered + const bool is_active = ImGui::IsItemActive(); // Held + const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin + const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y); + + // Add first and second point + if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + lines.push_back(ItemLine(mouse_pos_in_canvas, mouse_pos_in_canvas)); + adding_line = true; + } if (adding_line) { - adding_preview = true; - points.push_back(mouse_pos_canvas); - if (!ImGui::IsMouseDown(0)) - adding_line = adding_preview = false; + lines.back().p1 = mouse_pos_in_canvas; + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) + adding_line = false; } - if (ImGui::IsItemHovered()) + + // Pan (using zero mouse threshold) + if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, 0.0f)) { - if (!adding_line && ImGui::IsMouseClicked(0)) - { - points.push_back(mouse_pos_canvas); - adding_line = true; - } - if (ImGui::IsMouseClicked(1) && !points.empty()) - { - adding_line = adding_preview = false; - points.pop_back(); - points.pop_back(); - } + scrolling.x += io.MouseDelta.x; + scrolling.y += io.MouseDelta.y; } - // Draw all lines in the canvas (with a clipping rectangle so they don't stray out of it). - draw_list->PushClipRect(canvas_p, ImVec2(canvas_p.x + canvas_sz.x, canvas_p.y + canvas_sz.y), true); - for (int i = 0; i < points.Size - 1; i += 2) - draw_list->AddLine(ImVec2(canvas_p.x + points[i].x, canvas_p.y + points[i].y), ImVec2(canvas_p.x + points[i + 1].x, canvas_p.y + points[i + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); + // Context menu (under default mouse threshold) + // We intentionally use the same button to demonstrate using mouse drag threshold. Some may feel panning should rely on same threshold. + ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); + if (drag_delta.x == 0.0f && drag_delta.y == 0.0f) + ImGui::OpenPopupContextItem("context"); + if (ImGui::BeginPopup("context")) + { + if (adding_line) + lines.pop_back(); + adding_line = false; + if (ImGui::MenuItem("Remove one", NULL, false, lines.Size > 0)) { lines.pop_back(); } + if (ImGui::MenuItem("Remove all", NULL, false, lines.Size > 0)) { lines.clear(); } + ImGui::EndPopup(); + } + + // Draw grid + all lines in the canvas + draw_list->PushClipRect(canvas_p0, canvas_p1, true); + if (show_grid) + { + const float GRID_STEP = 64.0f; + for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40)); + for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP) + draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40)); + } + for (int n = 0; n < lines.Size; n++) + draw_list->AddLine(ImVec2(origin.x + lines[n].p0.x, origin.y + lines[n].p0.y), ImVec2(origin.x + lines[n].p1.x, origin.y + lines[n].p1.y), IM_COL32(255, 255, 0, 255), 2.0f); draw_list->PopClipRect(); - if (adding_preview) - points.pop_back(); + ImGui::EndTabItem(); } From 55041ac3bee2e7ac4e024103e3aa4555233f814a Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 19:25:41 +0200 Subject: [PATCH 163/959] Demo: Removed thin triangle and aligned code. --- imgui_demo.cpp | 55 ++++++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 0ce046c5..774968eb 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4869,21 +4869,22 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Draw gradients // (note that those are currently exacerbating our sRGB/Linear issues) + // Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well.. ImGui::Text("Gradients"); ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); { ImVec2 p0 = ImGui::GetCursorScreenPos(); ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); - ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 0.0f, 0.0f, 1.0f)); - ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255)); draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient1", gradient_size); } { ImVec2 p0 = ImGui::GetCursorScreenPos(); ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); - ImU32 col_a = ImGui::GetColorU32(ImVec4(0.0f, 1.0f, 0.0f, 1.0f)); - ImU32 col_b = ImGui::GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); + ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255)); + ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255)); draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); ImGui::InvisibleButton("##gradient2", gradient_size); } @@ -4904,6 +4905,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::SliderInt("Circle segments", &circle_segments_override_v, 3, 40)) circle_segments_override = true; ImGui::ColorEdit4("Color", &colf.x); + const ImVec2 p = ImGui::GetCursorScreenPos(); const ImU32 col = ImColor(colf); const float spacing = 10.0f; @@ -4911,38 +4913,39 @@ static void ShowExampleAppCustomRendering(bool* p_open) const ImDrawCornerFlags corners_all = ImDrawCornerFlags_All; const ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight; const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; - float x = p.x + 4.0f, y = p.y + 4.0f; + float x = p.x + 4.0f; + float y = p.y + 4.0f; for (int n = 0; n < 2; n++) { // First line uses a thickness of 1.0f, second line uses the configurable thickness float th = (n == 0) ? 1.0f : thickness; - draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon - draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, corners_none, th); x += sz + spacing; // Square - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_all, th); x += sz + spacing; // Square with all rounded corners - draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th); x += sz + spacing; // Triangle - draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th); x += sz*0.4f + spacing; // Thin triangle - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) - draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line + draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, corners_none, th); x += sz + spacing; // Square + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_all, th); x += sz + spacing; // Square with all rounded corners + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle + //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz*1.3f, y + sz*0.3f), ImVec2(x + sz - sz*1.3f, y + sz - sz*0.3f), ImVec2(x + sz, y + sz), col, th); x = p.x + 4; y += sz + spacing; } - draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides); x += sz + spacing; // N-gon - draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments);x += sz + spacing; // Circle - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners - draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle - draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing*2.0f; // Vertical line (faster than AddLine, but only handle integer thickness) - draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine) + draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides); x += sz + spacing; // N-gon + draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments); x += sz + spacing; // Circle + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle + //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine) draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); - ImGui::Dummy(ImVec2((sz + spacing) * 9.8f, (sz + spacing) * 3)); + ImGui::Dummy(ImVec2((sz + spacing) * 8.8f, (sz + spacing) * 3.0f)); ImGui::PopItemWidth(); ImGui::EndTabItem(); } From 963839373cf376b29eb1a5b990cccd40b50d75f3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 3 Aug 2020 21:19:12 +0200 Subject: [PATCH 164/959] Demo tweaks + general removal of the word dummy were possible with no issues (kept the API call). --- docs/CHANGELOG.txt | 8 ++-- docs/FAQ.md | 10 ++--- docs/TODO.txt | 1 - examples/example_null/main.cpp | 2 +- examples/imgui_impl_opengl3.cpp | 6 +-- imgui.cpp | 20 +++++----- imgui.h | 14 +++---- imgui_demo.cpp | 67 +++++++++++++++++---------------- imgui_draw.cpp | 4 +- imgui_widgets.cpp | 11 +++--- 10 files changed, 73 insertions(+), 70 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70acf40c..bdc30ccb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -573,7 +573,7 @@ Other Changes: because it needs application to be linked with '-framework ApplicationServices'. It can be explicitly enabled back by using '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h. Re-added equivalent using NSPasteboard api in the imgui_impl_osx.mm experimental back-end. (#2546) -- Backends: SDL2: Added dummy ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. +- Backends: SDL2: Added ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. (#2482, #2632) [@josiahmanson] - Examples: Added SDL2+DirectX11 example application. (#2632, #2612, #2482) [@vincenthamm] @@ -733,7 +733,7 @@ Other Changes: - Misc: Made IMGUI_CHECKVERSION() macro also check for matching size of ImDrawIdx. - Metrics: Added "Show windows rectangles" tool to visualize the different rectangles. - Demo: Improved trees in columns demo. -- Examples: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized +- Examples: OpenGL: Added a test GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early, and help users understand what they are missing. (#2421) - Examples: SDL: Added support for SDL_GameController gamepads (enable with ImGuiConfigFlags_NavEnableGamepad). (#2509) [@DJLink] - Examples: Emscripten: Added Emscripten+SDL+GLES2 example. (#2494, #2492, #2351, #336) [@nicolasnoble, @redblobgames] @@ -841,7 +841,7 @@ Breaking Changes: - Removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - Made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). - If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! + If for some reason your time step calculation gives you a zero value, replace it with a arbitrary small value! Other Changes: @@ -1332,7 +1332,7 @@ Other Changes: - ColorEdit: Fixed not being able to pass the ImGuiColorEditFlags_NoAlpha or ImGuiColorEditFlags_HDR flags to SetColorEditOptions(). - Nav: Fixed hovering a Selectable() with the mouse so that it update the navigation cursor (as it happened in the pre-1.60 navigation branch). (#787) - Style: Changed default style.DisplaySafeAreaPadding values from (4,4) to (3,3) so it is smaller than FramePadding and has no effect on main menu bar on a computer. (#1439) -- Fonts: When building font atlas, glyphs that are missing in the fonts are not using the glyph slot to render a dummy/default glyph. Saves space and allow merging fonts with +- Fonts: When building font atlas, glyphs that are missing in the fonts are not using the glyph slot to render the default glyph. Saves space and allow merging fonts with overlapping font ranges such as FontAwesome5 which split out the Brands separately from the Solid fonts. (#1703, #1671) - Misc: Added IMGUI_CHECKVERSION() macro to compare version string and data structure sizes in order to catch issues with mismatching compilation unit settings. (#1695, #1769) - Misc: Added IMGUI_DISABLE_MATH_FUNCTIONS in imconfig.h to make it easier to redefine wrappers for std/crt math functions. diff --git a/docs/FAQ.md b/docs/FAQ.md index adce4d40..b5fbcc90 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -111,11 +111,11 @@ e.g. `if (ImGui::GetIO().WantCaptureMouse) { ... }` **Note:** You should always pass your mouse/keyboard inputs to Dear ImGui, even when the io.WantCaptureXXX flag are set false. This is because imgui needs to detect that you clicked in the void to unfocus its own windows. -**Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs. +**Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs. -**Note:** Those flags are updated by `ImGui::NewFrame()`. However it is generally more correct and easier that you poll flags from the previous frame, then submit your inputs, then call `NewFrame()`. If you attempt to do the opposite (which is generally harder) you are likely going to submit your inputs after `NewFrame()`, and therefore too late. +**Note:** Those flags are updated by `ImGui::NewFrame()`. However it is generally more correct and easier that you poll flags from the previous frame, then submit your inputs, then call `NewFrame()`. If you attempt to do the opposite (which is generally harder) you are likely going to submit your inputs after `NewFrame()`, and therefore too late. -**Note:** If you are using a touch device, you may find use for an early call to `UpdateHoveredWindowAndCaptureFlags()` to correctly dispatch your initial touch. We will work on better out-of-the-box touch support in the future. +**Note:** If you are using a touch device, you may find use for an early call to `UpdateHoveredWindowAndCaptureFlags()` to correctly dispatch your initial touch. We will work on better out-of-the-box touch support in the future. **Note:** Text input widget releases focus on the "KeyDown" event of the Return key, so the subsequent "KeyUp" event that your application receive will typically have `io.WantCaptureKeyboard == false`. Depending on your application logic it may or not be inconvenient to receive that KeyUp event. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.) @@ -453,7 +453,7 @@ ImGui::End(); - To generate colors: you can use the macro `IM_COL32(255,255,255,255)` to generate them at compile time, or use `ImGui::GetColorU32(IM_COL32(255,255,255,255))` or `ImGui::GetColorU32(ImVec4(1.0f,1.0f,1.0f,1.0f))` to generate a color that is multiplied by the current value of `style.Alpha`. - Math operators: if you have setup `IM_VEC2_CLASS_EXTRA` in `imconfig.h` to bind your own math types, you can use your own math types and their natural operators instead of ImVec2. ImVec2 by default doesn't export any math operators in the public API. You may use `#define IMGUI_DEFINE_MATH_OPERATORS` `#include "imgui_internal.h"` to use the internally defined math operators, but instead prefer using your own math library and set it up in `imconfig.h`. - You can use `ImGui::GetBackgroundDrawList()` or `ImGui::GetForegroundDrawList()` to access draw lists which will be displayed behind and over every other dear imgui windows (one bg/fg drawlist per viewport). This is very convenient if you need to quickly display something on the screen that is not associated to a dear imgui window. -- You can also create your own dummy window and draw inside it. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags (The `ImGuiWindowFlags_NoDecoration` flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse). Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. +- You can also create your own empty window and draw inside it. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags (The `ImGuiWindowFlags_NoDecoration` flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse). Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - You can create your own ImDrawList instance. You'll need to initialize them with `ImGui::GetDrawListSharedData()`, or create your own instancing ImDrawListSharedData, and then call your renderer function with your own ImDrawList or ImDrawData data. ##### [Return to Index](#index) @@ -464,7 +464,7 @@ ImGui::End(); ### Q: How should I handle DPI in my application? -The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. +The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. Your application may want to detect DPI change and reload the font and reset style being frames. diff --git a/docs/TODO.txt b/docs/TODO.txt index 413301d0..9d9ea950 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -365,7 +365,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - misc: idle: if cursor blink if the _only_ visible animation, could even expose a dirty rectangle that optionally can be leverage by some app to render in a smaller viewport, getting rid of much pixel shading cost. - misc: no way to run a root-most GetID() with ImGui:: api since there's always a Debug window in the stack. (mentioned in #2960) - misc: make the ImGuiCond values linear (non-power-of-two). internal storage for ImGuiWindow can use integers to combine into flags (Why?) - - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) - misc: PushItemFlag(): add a flag to disable keyboard capture when used with mouse? (#1682) - misc: use more size_t in public api? - misc: possible compile-time support for string view/range instead of char* would e.g. facilitate usage with Rust (#683) diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index aa2f6dba..72381f0a 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -1,4 +1,4 @@ -// dear imgui: null/dummy example application +// dear imgui: "null" example application // (compile and link imgui, create context, run headless with NO INPUTS, NO GRAPHICS OUTPUT) // This is useful to test building, but you cannot interact with anything here! #include "imgui.h" diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index cb60304d..21e8852b 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -25,7 +25,7 @@ // 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. -// 2019-03-15: OpenGL: Added a dummy GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. +// 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). // 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. @@ -179,7 +179,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) strcpy(g_GlslVersionString, glsl_version); strcat(g_GlslVersionString, "\n"); - // Dummy construct to make it easily visible in the IDE and debugger which GL loader has been selected. + // Debugging construct to make it easily visible in the IDE and debugger which GL loader has been selected. // The code actually never uses the 'gl_loader' variable! It is only here so you can read it! // If auto-detection fails or doesn't select the same GL loader file as used by your application, // you are likely to get a crash below. @@ -204,7 +204,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) gl_loader = "none"; #endif - // Make a dummy GL call (we don't actually need the result) + // Make an arbitrary GL call (we don't actually need the result) // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code. // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above. GLint current_texture; diff --git a/imgui.cpp b/imgui.cpp index efa38ffe..057001ba 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -417,7 +417,7 @@ CODE - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). - - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! + - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrary small value! - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete). @@ -1663,8 +1663,8 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) // Not optimal but we very rarely use this function. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end) { - unsigned int dummy = 0; - return ImTextCharFromUtf8(&dummy, in_text, in_text_end); + unsigned int unused = 0; + return ImTextCharFromUtf8(&unused, in_text, in_text_end); } static inline int ImTextCountUtf8BytesFromChar(unsigned int c) @@ -2160,7 +2160,7 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items *out_items_display_end = end; } -static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) +static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height) { // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. @@ -2192,7 +2192,7 @@ void ImGuiListClipper::Begin(int count, float items_height) { ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display if (DisplayStart > 0) - SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor + SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor StepNo = 2; } } @@ -2203,7 +2203,7 @@ void ImGuiListClipper::End() return; // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX) - SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; StepNo = 3; } @@ -2237,7 +2237,7 @@ bool ImGuiListClipper::Step() StepNo = 3; return true; } - if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + if (StepNo == 2) // Step 2: empty step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. { IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); StepNo = 3; @@ -3040,7 +3040,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) return false; - // Special handling for the dummy item after Begin() which represent the title bar or tab. + // Special handling for calling after Begin() which represent the title bar or tab. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed) return false; @@ -4728,7 +4728,7 @@ bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, b { FocusWindow(child_window); NavInitWindow(child_window, false); - SetActiveID(id + 1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item + SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item g.ActiveIdSource = ImGuiInputSource_Nav; } return ret; @@ -7849,7 +7849,7 @@ void ImGui::EndPopup() g.WithinEndChild = false; } -// Open a popup if mouse is released over the item +// Open a popup if mouse button is released over the item bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui.h b/imgui.h index f3b28d74..40fa6cc8 100644 --- a/imgui.h +++ b/imgui.h @@ -1330,16 +1330,16 @@ enum ImGuiCond_ // Helpers: Memory allocations macros // IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() // We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. -// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +// Defining a custom placement new() with a custom parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. //----------------------------------------------------------------------------- -struct ImNewDummy {}; -inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } -inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symmetrical new() +struct ImNewWrapper {}; +inline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; } +inline void operator delete(void*, ImNewWrapper, void*) {} // This is only required so we can use the symmetrical new() #define IM_ALLOC(_SIZE) ImGui::MemAlloc(_SIZE) #define IM_FREE(_PTR) ImGui::MemFree(_PTR) -#define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) -#define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE +#define IM_PLACEMENT_NEW(_PTR) new(ImNewWrapper(), _PTR) +#define IM_NEW(_TYPE) new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE template void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } //----------------------------------------------------------------------------- @@ -1843,7 +1843,7 @@ struct ImGuiStorage // ImGui::Text("line number %d", i); // - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). // - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. -// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) +// - (Step 2: empty step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) // - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. struct ImGuiListClipper { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 774968eb..e267872f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1243,7 +1243,7 @@ static void ShowDemoWindowWidgets() static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); - // Create a dummy array of contiguous float values to plot + // Fill an array of contiguous float values to plot // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float // and the sizeof() of your structure in the "stride" parameter. static float values[90] = {}; @@ -1251,7 +1251,7 @@ static void ShowDemoWindowWidgets() static double refresh_time = 0.0; if (!animate || refresh_time == 0.0) refresh_time = ImGui::GetTime(); - while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 Hz rate for the demo + while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo { static float phase = 0.0f; values[values_offset] = cosf(phase); @@ -1351,7 +1351,7 @@ static void ShowDemoWindowWidgets() ImGui::Text("Color button with Custom Picker Popup:"); - // Generate a dummy default palette. The palette will persist and can be edited. + // Generate a default palette. The palette will persist and can be edited. static bool saved_palette_init = true; static ImVec4 saved_palette[32] = {}; if (saved_palette_init) @@ -1932,8 +1932,8 @@ static void ShowDemoWindowWidgets() if (embed_all_inside_a_child_window) ImGui::EndChild(); - static char dummy_str[] = "This is a dummy field to be able to tab-out of the widgets above."; - ImGui::InputText("dummy", dummy_str, IM_ARRAYSIZE(dummy_str), ImGuiInputTextFlags_ReadOnly); + static char unused_str[] = "This widget is only here to be able to tab-out of the widgets above."; + ImGui::InputText("unused", unused_str, IM_ARRAYSIZE(unused_str), ImGuiInputTextFlags_ReadOnly); // Calling IsItemHovered() after begin returns the hovered status of the title bar. // This is useful in particular if you want to create a context menu associated to the title bar of a window. @@ -2376,7 +2376,7 @@ static void ShowDemoWindowLayout() ImGui::SameLine(0.0f, spacing); if (ImGui::TreeNode("Node##1")) { - // Dummy tree data + // Placeholder tree data for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); @@ -2392,7 +2392,7 @@ static void ShowDemoWindowLayout() ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); if (node_open) { - // Dummy tree data + // Placeholder tree data for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); @@ -2693,7 +2693,7 @@ static void ShowDemoWindowLayout() ImGui::TextWrapped("(Click and drag)"); ImVec2 pos = ImGui::GetCursorScreenPos(); ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); - ImGui::InvisibleButton("##dummy", size); + ImGui::InvisibleButton("##empty", size); if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) { offset.x += ImGui::GetIO().MouseDelta.x; @@ -2869,8 +2869,8 @@ static void ShowDemoWindowPopups() ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); ImGui::Separator(); - //static int dummy_i = 0; - //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0"); + //static int unused_i = 0; + //ImGui::Combo("Combo", &unused_i, "Delete\0Delete harder\0"); static bool dont_ask_me_next_time = false; ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); @@ -2892,7 +2892,7 @@ static void ShowDemoWindowPopups() { if (ImGui::BeginMenu("File")) { - if (ImGui::MenuItem("Dummy menu item")) {} + if (ImGui::MenuItem("Some menu item")) {} ImGui::EndMenu(); } ImGui::EndMenuBar(); @@ -2911,8 +2911,8 @@ static void ShowDemoWindowPopups() // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value // of the bool actually doesn't matter here. - bool dummy_open = true; - if (ImGui::BeginPopupModal("Stacked 2", &dummy_open)) + bool unused_open = true; + if (ImGui::BeginPopupModal("Stacked 2", &unused_open)) { ImGui::Text("Hello from Stacked The Second!"); if (ImGui::Button("Close")) @@ -3247,7 +3247,7 @@ static void ShowDemoWindowMisc() if (ImGui::TreeNode("Tabbing")) { ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); - static char buf[32] = "dummy"; + static char buf[32] = "hello"; ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); @@ -3903,7 +3903,7 @@ static void ShowExampleAppMainMenuBar() // (future version will add explicit flags to BeginMenu() to request processing shortcuts) static void ShowExampleMenuFile() { - ImGui::MenuItem("(dummy menu)", NULL, false, false); + ImGui::MenuItem("(demo menu)", NULL, false, false); if (ImGui::MenuItem("New")) {} if (ImGui::MenuItem("Open", "Ctrl+O")) {} if (ImGui::BeginMenu("Open Recent")) @@ -4067,8 +4067,8 @@ struct ExampleAppConsole // TODO: display items starting from the bottom - if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); - if (ImGui::SmallButton("Add Dummy Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } @@ -4558,7 +4558,7 @@ static void ShowExampleAppLayout(bool* p_open) // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() //----------------------------------------------------------------------------- -static void ShowDummyObject(const char* prefix, int uid) +static void ShowPlaceholderObject(const char* prefix, int uid) { // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. ImGui::PushID(uid); @@ -4570,13 +4570,13 @@ static void ShowDummyObject(const char* prefix, int uid) ImGui::NextColumn(); if (node_open) { - static float dummy_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; + static float placeholder_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f }; for (int i = 0; i < 8; i++) { ImGui::PushID(i); // Use field index as identifier. if (i < 2) { - ShowDummyObject("Child", 424242); + ShowPlaceholderObject("Child", 424242); } else { @@ -4587,9 +4587,9 @@ static void ShowDummyObject(const char* prefix, int uid) ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); if (i >= 5) - ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + ImGui::InputFloat("##value", &placeholder_members[i], 1.0f); else - ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::DragFloat("##value", &placeholder_members[i], 0.01f); ImGui::NextColumn(); } ImGui::PopID(); @@ -4619,9 +4619,9 @@ static void ShowExampleAppPropertyEditor(bool* p_open) ImGui::Columns(2); ImGui::Separator(); - // Iterate dummy objects with dummy members (all the same data) + // Iterate placeholder objects (all the same data) for (int obj_i = 0; obj_i < 3; obj_i++) - ShowDummyObject("Object", obj_i); + ShowPlaceholderObject("Object", obj_i); ImGui::Columns(1); ImGui::Separator(); @@ -4955,10 +4955,12 @@ static void ShowExampleAppCustomRendering(bool* p_open) struct ItemLine { ImVec2 p0, p1; ItemLine(const ImVec2& _p0, const ImVec2& _p1) { p0 = _p0; p1 = _p1; } }; static ImVector lines; static ImVec2 scrolling(0.0f, 0.0f); - static bool show_grid = true; + static bool opt_enable_grid = true; + static bool opt_enable_context_menu = true; static bool adding_line = false; - ImGui::Checkbox("Show grid", &show_grid); + ImGui::Checkbox("Enable grid", &opt_enable_grid); + ImGui::Checkbox("Enable context menu", &opt_enable_context_menu); ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu."); // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. @@ -5005,17 +5007,18 @@ static void ShowExampleAppCustomRendering(bool* p_open) adding_line = false; } - // Pan (using zero mouse threshold) - if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, 0.0f)) + // Pan (we use a zero mouse threshold when there's no context menu) + // You may decide to make that threshold dynamic based on whether the mouse is hovering something etc. + const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f; + if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan)) { scrolling.x += io.MouseDelta.x; scrolling.y += io.MouseDelta.y; } // Context menu (under default mouse threshold) - // We intentionally use the same button to demonstrate using mouse drag threshold. Some may feel panning should rely on same threshold. ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); - if (drag_delta.x == 0.0f && drag_delta.y == 0.0f) + if (opt_enable_context_menu && ImGui::IsMouseReleased(ImGuiMouseButton_Right) && drag_delta.x == 0.0f && drag_delta.y == 0.0f) ImGui::OpenPopupContextItem("context"); if (ImGui::BeginPopup("context")) { @@ -5029,7 +5032,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Draw grid + all lines in the canvas draw_list->PushClipRect(canvas_p0, canvas_p1, true); - if (show_grid) + if (opt_enable_grid) { const float GRID_STEP = 64.0f; for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP) @@ -5095,7 +5098,7 @@ struct MyDocument void DoForceClose() { Open = false; Dirty = false; } void DoSave() { Dirty = false; } - // Display dummy contents for the Document + // Display placeholder contents for the Document static void DisplayContents(MyDocument* doc) { ImGui::PushID(doc); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e9529e01..890c0c2c 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2307,8 +2307,8 @@ bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas) const int codepoint = src_tmp.GlyphsList[glyph_i]; const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i]; stbtt_aligned_quad q; - float dummy_x = 0.0f, dummy_y = 0.0f; - stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &dummy_x, &dummy_y, &q, 0); + 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); dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance); } } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8e8bfca9..55dc6433 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5205,9 +5205,9 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask); SetCursorScreenPos(backup_pos); - ImVec4 dummy_ref_col; - memcpy(&dummy_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4)); - ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags); + ImVec4 previewing_ref_col; + memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4)); + ColorPicker4("##previewing_picker", &previewing_ref_col.x, picker_flags); PopID(); } PopItemWidth(); @@ -5679,7 +5679,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags // - Selectable() //------------------------------------------------------------------------- -// Tip: pass a non-visible label (e.g. "##dummy") then you can use the space to draw other text or image. +// Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. // With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowItemOverlap are also frequently used flags. // FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. @@ -7121,7 +7121,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, const ImGuiStyle& style = g.Style; const ImGuiID id = TabBarCalcTabID(tab_bar, label); - // If the user called us with *p_open == false, we early out and don't render. We make a dummy call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. + // If the user called us with *p_open == false, we early out and don't render. + // We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); if (p_open && !*p_open) { From db886f395372d9e313758933d96ab63767fa8701 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 4 Aug 2020 12:05:15 +0200 Subject: [PATCH 165/959] Demo: Rework Clipping section. Fix for static analysis. Added bindings in Readme. --- docs/CHANGELOG.txt | 5 ++-- docs/README.md | 4 +-- docs/TODO.txt | 2 ++ imgui.cpp | 4 +-- imgui_demo.cpp | 71 +++++++++++++++++++++++++++++++++++++--------- 5 files changed, 66 insertions(+), 20 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bdc30ccb..ec58fce5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,9 +68,10 @@ Other Changes: by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] -- Demo: Improve "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. +- Demo: Improved "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. Also showcase using InvisibleButton() will multiple mouse buttons flags. -- Demo: Tweak "Child Windows" section. +- Demo: Improved "Layout & Scrolling" -> "Clipping" section. +- Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] diff --git a/docs/README.md b/docs/README.md index a0ca6483..9579ee22 100644 --- a/docs/README.md +++ b/docs/README.md @@ -113,8 +113,8 @@ Officially maintained bindings (in repository): - Frameworks: Emscripten, Allegro5, Marmalade. Third-party bindings (see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings/) page): -- Languages: C, C#/.Net, ChaiScript, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... -- Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. +- Languages: C, C# and: Beef, ChaiScript, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... +- Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. - Note that C bindings ([cimgui](https://github.com/cimgui/cimgui)) are auto-generated, you can use its json/lua output to generate bindings for other languages. Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. diff --git a/docs/TODO.txt b/docs/TODO.txt index 9d9ea950..a96693b3 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -393,6 +393,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - backends: bgfx: https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - backends: mscriptem: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) + - bindings: ways to use clang ast dump to generate bindings or helpers for bindings? (e.g. clang++ -Xclang -ast-dump=json imgui.h) + - optimization: replace vsnprintf with stb_printf? using IMGUI_USE_STB_SPRINTF.(#1038) - optimization: add clipping for multi-component widgets (SliderFloatX, ColorEditX, etc.). one problem is that nav branch can't easily clip parent group when there is a move request. - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) diff --git a/imgui.cpp b/imgui.cpp index 057001ba..ab41ba10 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3373,8 +3373,8 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; - // Cancel moving if clicked over an item which was disabled or inhibited by popups - if (g.HoveredId == 0 && g.HoveredIdDisabled) + // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already) + if (g.HoveredIdDisabled) g.MovingWindow = NULL; } else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e267872f..b04c7db6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2684,23 +2684,66 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Clipping")) { - static ImVec2 size(100, 100), offset(50, 20); - ImGui::TextWrapped( - "On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. " - "Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. " - "The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + static ImVec2 size(100.0f, 100.0f); + static ImVec2 offset(30.0f, 30.0f); ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); - ImGui::TextWrapped("(Click and drag)"); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); - ImGui::InvisibleButton("##empty", size); - if (ImGui::IsItemActive() && ImGui::IsMouseDragging(0)) + ImGui::TextWrapped("(Click and drag to scroll)"); + + for (int n = 0; n < 3; n++) { - offset.x += ImGui::GetIO().MouseDelta.x; - offset.y += ImGui::GetIO().MouseDelta.y; + if (n > 0) + ImGui::SameLine(); + ImGui::PushID(n); + ImGui::BeginGroup(); // Lock X position + + ImGui::InvisibleButton("##empty", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + offset.x += ImGui::GetIO().MouseDelta.x; + offset.y += ImGui::GetIO().MouseDelta.y; + } + const ImVec2 p0 = ImGui::GetItemRectMin(); + const ImVec2 p1 = ImGui::GetItemRectMax(); + const char* text_str = "Line 1 hello\nLine 2 clip me!"; + const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + switch (n) + { + case 0: + HelpMarker( + "Using ImGui::PushClipRect():\n" + "Will alter ImGui hit-testing logic + ImDrawList rendering.\n" + "(use this if you want your clipping rectangle to affect interactions)"); + ImGui::PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + ImGui::PopClipRect(); + break; + case 1: + HelpMarker( + "Using ImDrawList::PushClipRect():\n" + "Will alter ImDrawList rendering only.\n" + "(use this as a shortcut if you are only using ImDrawList calls)"); + draw_list->PushClipRect(p0, p1, true); + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(text_pos, IM_COL32_WHITE, text_str); + draw_list->PopClipRect(); + break; + case 2: + HelpMarker( + "Using ImDrawList::AddText() with a fine ClipRect:\n" + "Will alter only this specific ImDrawList::AddText() rendering.\n" + "(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)"); + ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert. + draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)); + draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect); + break; + } + ImGui::EndGroup(); + ImGui::PopID(); } - ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x + size.x, pos.y + size.y), IM_COL32(90, 90, 120, 255)); - ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x + offset.x, pos.y + offset.y), IM_COL32_WHITE, "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::TreePop(); } } From a24578ec094b51f739dd788b53028c411c55a3eb Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 14:58:44 +0200 Subject: [PATCH 166/959] Examples: Switch most VS projects to enable Edit & Continue by default (may need to upgrade projects to latest toolchain) --- examples/example_allegro5/example_allegro5.vcxproj | 1 + examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj | 1 + examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj | 1 + examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj | 1 + examples/example_glut_opengl2/example_glut_opengl2.vcxproj | 1 + examples/example_sdl_directx11/example_sdl_directx11.vcxproj | 1 + examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj | 3 ++- examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj | 1 + examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj | 1 + .../example_win32_directx10/example_win32_directx10.vcxproj | 1 + .../example_win32_directx11/example_win32_directx11.vcxproj | 1 + examples/example_win32_directx9/example_win32_directx9.vcxproj | 1 + 12 files changed, 13 insertions(+), 1 deletion(-) diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index c86dcb2b..ace88555 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index b265fea0..5cb59b87 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 47d25380..3d670bf5 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index 9e2c9b38..65458eb9 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index 9a239516..ac8f6a76 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled $(GLUT_INCLUDE_DIR);..\..;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj index 804bd500..b32034e5 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -106,6 +106,7 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index 83a6a8a0..8bba2071 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -19,7 +19,7 @@ - {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} + {4168B148-B7DE-4A31-8497-19AFA6B83360} example_sdl_opengl2 8.1 @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj index 54aaa796..c516c999 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj index ac701a2a..8a6eab4c 100644 --- a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj +++ b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj @@ -105,6 +105,7 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + EditAndContinue true diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 5c3aa69f..6182b687 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -100,6 +100,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); + EditAndContinue true diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index bcb71bc4..3e4db23e 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -99,6 +99,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); + EditAndContinue true diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index 25bdd859..cf944ae5 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -100,6 +100,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + EditAndContinue true From 473a01adb0c334dc4c7f6432cc55098a9e6ac2d6 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 17:09:40 +0200 Subject: [PATCH 167/959] Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll limits. (#3379) + Demo: Rename "Layout" to "Layout & Scrolling". --- docs/CHANGELOG.txt | 4 +++ imgui.cpp | 66 ++++++++++++++++++++++++++++------------------ imgui.h | 4 +-- imgui_demo.cpp | 8 +++--- 4 files changed, 49 insertions(+), 33 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ec58fce5..7cc16314 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,10 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll + limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many + side-effects. The behavior is still present in SetScrollHere functions as they are more explicitly + aiming at making widgets visible. May later be moved to a flag. - InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. This is a small but rather important change because lots of multi-button behaviors could previously diff --git a/imgui.cpp b/imgui.cpp index ab41ba10..e6d7f61d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -805,7 +805,7 @@ static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock static void SetCurrentWindow(ImGuiWindow* window); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); -static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list); static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window); @@ -5819,7 +5819,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); // Apply scrolling - window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true); + window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window); window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); // DRAWING @@ -7325,30 +7325,20 @@ void ImGui::EndGroup() // [SECTION] SCROLLING //----------------------------------------------------------------------------- -static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) +static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) { - ImGuiContext& g = *GImGui; ImVec2 scroll = window->Scroll; if (window->ScrollTarget.x < FLT_MAX) { float cr_x = window->ScrollTargetCenterRatio.x; float target_x = window->ScrollTarget.x; - if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x) - target_x = 0.0f; - else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + g.Style.ItemSpacing.x) - target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f; scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x); } if (window->ScrollTarget.y < FLT_MAX) { - // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); float cr_y = window->ScrollTargetCenterRatio.y; float target_y = window->ScrollTarget.y; - if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) - target_y = 0.0f; - if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y) - target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f; scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height); } scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f)); @@ -7380,7 +7370,7 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_ else if (item_rect.Max.y >= window_rect.Max.y) SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f); - ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false); + ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window); delta_scroll = next_scroll - window->Scroll; } @@ -7441,10 +7431,10 @@ void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) window->ScrollTargetCenterRatio.y = 0.0f; } - +// Note that a local position will vary depending on initial scroll value +// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio) { - // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); window->ScrollTargetCenterRatio.x = center_x_ratio; @@ -7452,10 +7442,8 @@ void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio) { - // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); - const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); - local_y -= decoration_up_height; + local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); window->ScrollTargetCenterRatio.y = center_y_ratio; } @@ -7472,15 +7460,34 @@ void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio); } +// Tweak: snap on edges when aiming at an item very close to the edge, +// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +// When we refactor the scrolling API this may be configurable with a flag? +// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. +static float CalcScrollSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio) +{ + if (target <= snap_min + snap_threshold) + return ImLerp(snap_min, target, center_ratio); + if (target >= snap_max - snap_threshold) + return ImLerp(target, snap_max, center_ratio); + return target; +} + // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. void ImGui::SetScrollHereX(float center_x_ratio) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space - float last_item_width = window->DC.LastItemRect.GetWidth(); - target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. - SetScrollFromPosX(target_x, center_x_ratio); + float spacing_x = g.Style.ItemSpacing.x; + float target_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio); + + // Tweak: snap on edges when aiming at an item very close to the edge + const float snap_x_threshold = ImMax(0.0f, window->WindowPadding.x - spacing_x); + const float snap_x_min = window->DC.CursorStartPos.x - window->WindowPadding.x; + const float snap_x_max = window->DC.CursorStartPos.x + window->ContentSize.x + window->WindowPadding.x; + target_x = CalcScrollSnap(target_x, snap_x_min, snap_x_max, snap_x_threshold, center_x_ratio); + + SetScrollFromPosX(window, target_x - window->Pos.x, center_x_ratio); } // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. @@ -7488,9 +7495,16 @@ void ImGui::SetScrollHereY(float center_y_ratio) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space - target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. - SetScrollFromPosY(target_y, center_y_ratio); + float spacing_y = g.Style.ItemSpacing.y; + float target_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); + + // Tweak: snap on edges when aiming at an item very close to the edge + const float snap_y_threshold = ImMax(0.0f, window->WindowPadding.y - spacing_y); + const float snap_y_min = window->DC.CursorStartPos.y - window->WindowPadding.y; + const float snap_y_max = window->DC.CursorStartPos.y + window->ContentSize.y + window->WindowPadding.y; + target_y = CalcScrollSnap(target_y, snap_y_min, snap_y_max, snap_y_threshold, center_y_ratio); + + SetScrollFromPosY(window, target_y - window->Pos.y, center_y_ratio); } //----------------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index 40fa6cc8..c135ada2 100644 --- a/imgui.h +++ b/imgui.h @@ -333,8 +333,8 @@ namespace ImGui // Windows Scrolling IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] - IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X - IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b04c7db6..bc4cd1c2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2490,11 +2490,9 @@ static void ShowDemoWindowLayout() ImGui::Spacing(); HelpMarker( "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" - "Using the \"Scroll To Pos\" button above will make the discontinuity at edges visible: " - "scrolling to the top/bottom/left/right-most item will add an additional WindowPadding to reflect " - "on reaching the edge of the list.\n\nBecause the clipping rectangle of most window hides half " - "worth of WindowPadding on the left/right, using SetScrollFromPosX(+1) will usually result in " - "clipped text whereas the equivalent SetScrollFromPosY(+1) wouldn't."); + "Because the clipping rectangle of most window hides half worth of WindowPadding on the " + "left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the " + "equivalent SetScrollFromPosY(+1) wouldn't."); ImGui::PushID("##HorizontalScrolling"); for (int i = 0; i < 5; i++) { From fc61018b1c42be13e4e5a7f1111435dbba750a25 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 17:10:06 +0200 Subject: [PATCH 168/959] Demo: Renamed "Layout" -> "Layout & Scrolling". Fixed usage of local struct as template class (c++11). --- imgui_demo.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bc4cd1c2..1e5c59b8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1960,7 +1960,7 @@ static void ShowDemoWindowWidgets() static void ShowDemoWindowLayout() { - if (!ImGui::CollapsingHeader("Layout")) + if (!ImGui::CollapsingHeader("Layout & Scrolling")) return; if (ImGui::TreeNode("Child windows")) @@ -4993,8 +4993,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::BeginTabItem("Canvas")) { - struct ItemLine { ImVec2 p0, p1; ItemLine(const ImVec2& _p0, const ImVec2& _p1) { p0 = _p0; p1 = _p1; } }; - static ImVector lines; + static ImVector points; static ImVec2 scrolling(0.0f, 0.0f); static bool opt_enable_grid = true; static bool opt_enable_context_menu = true; @@ -5038,12 +5037,13 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Add first and second point if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { - lines.push_back(ItemLine(mouse_pos_in_canvas, mouse_pos_in_canvas)); + points.push_back(mouse_pos_in_canvas); + points.push_back(mouse_pos_in_canvas); adding_line = true; } if (adding_line) { - lines.back().p1 = mouse_pos_in_canvas; + points.back() = mouse_pos_in_canvas; if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) adding_line = false; } @@ -5064,10 +5064,10 @@ static void ShowExampleAppCustomRendering(bool* p_open) if (ImGui::BeginPopup("context")) { if (adding_line) - lines.pop_back(); + points.resize(points.size() - 2); adding_line = false; - if (ImGui::MenuItem("Remove one", NULL, false, lines.Size > 0)) { lines.pop_back(); } - if (ImGui::MenuItem("Remove all", NULL, false, lines.Size > 0)) { lines.clear(); } + if (ImGui::MenuItem("Remove one", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); } + if (ImGui::MenuItem("Remove all", NULL, false, points.Size > 0)) { points.clear(); } ImGui::EndPopup(); } @@ -5081,8 +5081,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP) draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40)); } - for (int n = 0; n < lines.Size; n++) - draw_list->AddLine(ImVec2(origin.x + lines[n].p0.x, origin.y + lines[n].p0.y), ImVec2(origin.x + lines[n].p1.x, origin.y + lines[n].p1.y), IM_COL32(255, 255, 0, 255), 2.0f); + for (int n = 0; n < points.Size; n += 2) + draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f); draw_list->PopClipRect(); ImGui::EndTabItem(); From 8074b4914834e2892000fc1f359fdb8cf84e88ac Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 19:23:00 +0200 Subject: [PATCH 169/959] Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). (#3187, #3386) # Conflicts: # imgui_widgets.cpp --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui_internal.h | 5 +++-- imgui_widgets.cpp | 10 ++++++---- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7cc16314..c9d14d56 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,8 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) +- Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). + Also fixed related text clipping when used in a column after the first one. (#3187, #3386) - Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many side-effects. The behavior is still present in SetScrollHere functions as they are more explicitly diff --git a/imgui.cpp b/imgui.cpp index e6d7f61d..c6127355 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5898,6 +5898,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize)); window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x; window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y; + window->ParentWorkRect = window->WorkRect; // [LEGACY] Content Region // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. diff --git a/imgui_internal.h b/imgui_internal.h index e0f8ae02..65e6e9e7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1015,7 +1015,7 @@ struct ImGuiColumns float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() - ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns() + ImRect HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns() ImVector Columns; ImDrawListSplitter Splitter; @@ -1612,7 +1612,8 @@ struct IMGUI_API ImGuiWindow ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar) ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect. - ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ImRect WorkRect; // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ImRect ParentWorkRect; // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack? ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 55dc6433..1d4362d0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5704,8 +5704,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ItemSize(size, 0.0f); // Fill horizontal space - const float min_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ContentRegionRect.Min.x : pos.x; - const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ContentRegionRect.Max.x : GetContentRegionMaxAbs().x; + const float min_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Min.x : pos.x; + const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) size.x = ImMax(label_size.x, max_x - min_x); @@ -7665,7 +7665,8 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostInitialClipRect = window->ClipRect; - columns->HostWorkRect = window->WorkRect; + columns->HostBackupParentWorkRect = window->ParentWorkRect; + window->ParentWorkRect = window->WorkRect; // Set state for first column // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect @@ -7845,7 +7846,8 @@ void ImGui::EndColumns() } columns->IsBeingResized = is_being_resized; - window->WorkRect = columns->HostWorkRect; + window->WorkRect = window->ParentWorkRect; + window->ParentWorkRect = columns->HostBackupParentWorkRect; window->DC.CurrentColumns = NULL; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); From b15b25bccd108832aee7b8e75a53072830c353fe Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Aug 2020 16:35:29 +0200 Subject: [PATCH 170/959] TabBar: made a change to that declared ideal width (for auto-resize) won't lag by an extra frame. Vaguely relate to underlying (uncommited) work for #3291 --- imgui_widgets.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1d4362d0..1378613c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6657,9 +6657,9 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->CurrFrameVisible = g.FrameCount; tab_bar->FramePadding = g.Style.FramePadding; - // Layout - ItemSize(ImVec2(tab_bar->OffsetMaxIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); + // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap window->DC.CursorPos.x = tab_bar->BarRect.Min.x; + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + g.Style.ItemSpacing.y; // Draw separator const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); @@ -6685,7 +6685,7 @@ void ImGui::EndTabBar() IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); return; } - if (tab_bar->WantLayout) + if (tab_bar->WantLayout) // Fallback in case no TabItem have been submitted TabBarLayout(tab_bar); // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). @@ -6871,6 +6871,11 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Clear name buffers if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) tab_bar->TabsNames.Buf.resize(0); + + // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) + ImGuiWindow* window = g.CurrentWindow; + window->DC.CursorPos = tab_bar->BarRect.Min; + ItemSize(ImVec2(tab_bar->OffsetMaxIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. From ede8825fb2d28142ce43d944f8f9ce58cadf5054 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Aug 2020 15:24:00 +0200 Subject: [PATCH 171/959] Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. Broken by a06eb833 (#3390) --- docs/CHANGELOG.txt | 1 + examples/example_glfw_vulkan/main.cpp | 1 + examples/example_sdl_vulkan/main.cpp | 1 + 3 files changed, 3 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c9d14d56..76703d74 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -80,6 +80,7 @@ Other Changes: - Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] +- Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. (#3390) [@RoryO] ----------------------------------------------------------------------- diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 80763a01..58d0ab7f 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -513,6 +513,7 @@ int main(int, char**) const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); if (!is_minimized) { + memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); FramePresent(wd); } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 0a2ea9ee..6de7afab 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -513,6 +513,7 @@ int main(int, char**) const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); if (!is_minimized) { + memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); FramePresent(wd); } From 90b152f265250d85fa180efcab01a9951d499f2d Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Aug 2020 16:26:16 +0200 Subject: [PATCH 172/959] ImFontAtlas: Fixed multiple rebuild with same inputs erroneously increased ConfigDataCount. CI: Update Ubuntu 18.04 > 20.04 (motivated by #3369) Fix Freetype warning. --- .github/workflows/build.yml | 2 +- imgui_draw.cpp | 1 + misc/freetype/imgui_freetype.cpp | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b3b910f2..274ca2a6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -180,7 +180,7 @@ jobs: run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' Linux: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v1 with: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 890c0c2c..39209287 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2328,6 +2328,7 @@ void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* f font->ClearOutputData(); font->FontSize = font_config->SizePixels; font->ConfigData = font_config; + font->ConfigDataCount = 0; font->ContainerAtlas = atlas; font->Ascent = ascent; font->Descent = descent; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 1a03be0c..3d62dc4b 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -382,7 +382,7 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns 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 <= src_range[1]; codepoint++) + 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; From 89ac87cd91baa25dfa4bca3796588eef34f3cadf Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 11:30:19 +0200 Subject: [PATCH 173/959] Internals: Added SetLastItemData, rename ImGuiItemHoveredDataBackup to ImGuiLastItemDataBackup. --- imgui.cpp | 15 ++++++++++++--- imgui_internal.h | 7 ++++--- imgui_widgets.cpp | 4 ++-- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c6127355..1e541e11 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3100,6 +3100,15 @@ bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged return false; } +// This is also inlined in ItemAdd() +// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect! +void ImGui::SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags item_flags, const ImRect& item_rect) +{ + window->DC.LastItemId = item_id; + window->DC.LastItemStatusFlags = item_flags; + window->DC.LastItemRect = item_rect; +} + // Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) { @@ -5980,9 +5989,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). // This is useful to allow creating context menus on title bar only, etc. - window->DC.LastItemId = window->MoveId; - window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; - window->DC.LastItemRect = title_bar_rect; + SetLastItemData(window, window->MoveId, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect); + #ifdef IMGUI_ENABLE_TEST_ENGINE if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId); @@ -6959,6 +6967,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) #endif } + // Equivalent to calling SetLastItemData() window->DC.LastItemId = id; window->DC.LastItemRect = bb; window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None; diff --git a/imgui_internal.h b/imgui_internal.h index 65e6e9e7..79a81f99 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -96,7 +96,7 @@ struct ImGuiContext; // Main Dear ImGui context struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box -struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data +struct ImGuiLastItemDataBackup; // Backup and restore IsItemHovered() internal data struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiNavMoveResult; // Result of a gamepad/keyboard directional navigation move query result struct ImGuiNextWindowData; // Storage for SetNextWindow** functions @@ -1664,14 +1664,14 @@ public: }; // Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data. -struct ImGuiItemHoveredDataBackup +struct ImGuiLastItemDataBackup { ImGuiID LastItemId; ImGuiItemStatusFlags LastItemStatusFlags; ImRect LastItemRect; ImRect LastItemDisplayRect; - ImGuiItemHoveredDataBackup() { Backup(); } + ImGuiLastItemDataBackup() { Backup(); } void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; } void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; } }; @@ -1839,6 +1839,7 @@ namespace ImGui IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL); IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id); IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged); + IMGUI_API void SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags status_flags, const ImRect& item_rect); IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1378613c..78115734 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5661,7 +5661,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. ImGuiContext& g = *GImGui; - ImGuiItemHoveredDataBackup last_item_backup; + ImGuiLastItemDataBackup last_item_backup; float button_size = g.FontSize; float button_x = ImMax(window->DC.LastItemRect.Min.x, window->DC.LastItemRect.Max.x - g.Style.FramePadding.x * 2.0f - button_size); float button_y = window->DC.LastItemRect.Min.y; @@ -7410,7 +7410,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, close_button_visible = true; if (close_button_visible) { - ImGuiItemHoveredDataBackup last_item_backup; + ImGuiLastItemDataBackup last_item_backup; const float close_button_sz = g.FontSize; PushStyleVar(ImGuiStyleVar_FramePadding, frame_padding); if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x * 2.0f - close_button_sz, bb.Min.y))) From 209a6a751cbd86c5534df050cd0839a093511a19 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 11:33:30 +0200 Subject: [PATCH 174/959] Revert "Examples: Switch most VS projects to enable Edit & Continue by default (may need to upgrade projects to latest toolchain)" This reverts commit a24578ec094b51f739dd788b53028c411c55a3eb. /ZI not supported on 64-bit on some toolchains, leaving to default is best? --- examples/example_allegro5/example_allegro5.vcxproj | 1 - examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj | 1 - examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj | 1 - examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj | 1 - examples/example_glut_opengl2/example_glut_opengl2.vcxproj | 1 - examples/example_sdl_directx11/example_sdl_directx11.vcxproj | 1 - examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj | 3 +-- examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj | 1 - examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj | 1 - .../example_win32_directx10/example_win32_directx10.vcxproj | 1 - .../example_win32_directx11/example_win32_directx11.vcxproj | 1 - examples/example_win32_directx9/example_win32_directx9.vcxproj | 1 - 12 files changed, 1 insertion(+), 13 deletions(-) diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index ace88555..c86dcb2b 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index 5cb59b87..b265fea0 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 3d670bf5..47d25380 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index 65458eb9..9e2c9b38 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index ac8f6a76..9a239516 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled $(GLUT_INCLUDE_DIR);..\..;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj index b32034e5..804bd500 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -106,7 +106,6 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index 8bba2071..83a6a8a0 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -19,7 +19,7 @@ - {4168B148-B7DE-4A31-8497-19AFA6B83360} + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} example_sdl_opengl2 8.1 @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj index c516c999..54aaa796 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj index 8a6eab4c..ac701a2a 100644 --- a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj +++ b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj @@ -105,7 +105,6 @@ Level4 Disabled ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) - EditAndContinue true diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 6182b687..5c3aa69f 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -100,7 +100,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); - EditAndContinue true diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index 3e4db23e..bcb71bc4 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -99,7 +99,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories); - EditAndContinue true diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index cf944ae5..25bdd859 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -100,7 +100,6 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; - EditAndContinue true From acf043a67589e718b630e27df4ddcefe0693d320 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 11:58:37 +0200 Subject: [PATCH 175/959] Docking: Moved code unjustly in DockNodeTreeFindNodeByPos() out of it and into caller (should have no side-effect ideally). Removed dupe in Begin() from earlier merge. --- imgui.cpp | 39 +++++++++++++++++++-------------------- imgui_internal.h | 4 ++-- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index fbb2bff6..58d515ab 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6056,10 +6056,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; - // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. - window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); - window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; - // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive) @@ -11757,7 +11753,7 @@ namespace ImGui static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child); static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes = false); static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node); - static ImGuiDockNode* DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos); + static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos); static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node); // Settings @@ -14026,13 +14022,13 @@ ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node) return NULL; } -ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos) +ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos) { if (!node->IsVisible) return NULL; ImGuiContext& g = *GImGui; - const float dock_spacing = g.Style.ItemInnerSpacing.x; + const float dock_spacing = g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? ImRect r(node->Pos, node->Pos + node->Size); r.Expand(dock_spacing * 0.5f); bool inside = r.Contains(pos); @@ -14041,20 +14037,11 @@ ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos) if (node->IsLeafNode()) return node; - if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[0], pos)) + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos)) return hovered_node; - if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[1], pos)) + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos)) return hovered_node; - // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) - // In this case we need to fallback into any leaf mode, possibly the central node. - if (node->IsDockSpace() && node->IsRootNode()) - { - if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. - return node->CentralNode; - return DockNodeTreeFindFallbackLeafNode(node); - } - return NULL; } @@ -14876,7 +14863,19 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) ImGuiDockNode* node = NULL; bool allow_null_target_node = false; if (window->DockNodeAsHost) - node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + { + node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + + // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + if (node && node->IsDockSpace() && node->IsRootNode()) + { + if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + node = node->CentralNode; + else + node = DockNodeTreeFindFallbackLeafNode(node); + } + } else if (window->DockNode) // && window->DockIsActive) node = window->DockNode; else @@ -15975,7 +15974,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) { ImGuiDockNode* root_node = DockNodeGetRootNode(node); - if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos)) + if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(root_node, g.IO.MousePos)) if (hovered_node != node) continue; char buf[64] = ""; diff --git a/imgui_internal.h b/imgui_internal.h index 8c7601c8..6f29af1e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1085,8 +1085,8 @@ enum ImGuiDockNodeFlagsPrivate_ ImGuiDockNodeFlags_NoDockingSplitOther = 1 << 18, // [EXPERIMENTAL] Prevent this node from splitting another window/node. ImGuiDockNodeFlags_NoDockingOverMe = 1 << 19, // [EXPERIMENTAL] Prevent another window/node to be docked over this node. ImGuiDockNodeFlags_NoDockingOverOther = 1 << 20, // [EXPERIMENTAL] Prevent this node to be docked over another window/node. - ImGuiDockNodeFlags_NoResizeX = 1 << 21, // [EXPERIMENTAL] - ImGuiDockNodeFlags_NoResizeY = 1 << 22, // [EXPERIMENTAL] + ImGuiDockNodeFlags_NoResizeX = 1 << 21, // [EXPERIMENTAL] + ImGuiDockNodeFlags_NoResizeY = 1 << 22, // [EXPERIMENTAL] ImGuiDockNodeFlags_SharedFlagsInheritMask_ = ~0, ImGuiDockNodeFlags_NoResizeFlagsMask_ = ImGuiDockNodeFlags_NoResize | ImGuiDockNodeFlags_NoResizeX | ImGuiDockNodeFlags_NoResizeY, ImGuiDockNodeFlags_LocalFlagsMask_ = ImGuiDockNodeFlags_NoSplit | ImGuiDockNodeFlags_NoResizeFlagsMask_ | ImGuiDockNodeFlags_AutoHideTabBar | ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_CentralNode | ImGuiDockNodeFlags_NoTabBar | ImGuiDockNodeFlags_HiddenTabBar | ImGuiDockNodeFlags_NoWindowMenuButton | ImGuiDockNodeFlags_NoCloseButton | ImGuiDockNodeFlags_NoDocking, From 85a661d276a27063b39209fd52deab1a793bfbed Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 12:52:33 +0200 Subject: [PATCH 176/959] Docking: Storing HoveredDockNode in context which can be useful for easily detecting e.g. hovering an empty node. (#3398) --- imgui.cpp | 81 +++++++++++++++++++++++------------------------- imgui_internal.h | 2 ++ 2 files changed, 40 insertions(+), 43 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 58d515ab..30f31a72 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11892,6 +11892,16 @@ void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; + // Store hovered dock node. We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut. + g.HoveredDockNode = NULL; + if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow) + { + if (hovered_window->DockNode) + g.HoveredDockNode = hovered_window->DockNode; + else if (hovered_window->DockNodeAsHost) + g.HoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); + } + // Process Docking requests for (int n = 0; n < dc->Requests.Size; n++) if (dc->Requests[n].Type == ImGuiDockRequestType_Dock) @@ -14027,8 +14037,7 @@ ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVe if (!node->IsVisible) return NULL; - ImGuiContext& g = *GImGui; - const float dock_spacing = g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? + const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? ImRect r(node->Pos, node->Pos + node->Size); r.Expand(dock_spacing * 0.5f); bool inside = r.Contains(pos); @@ -14860,26 +14869,19 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { // Select target node - ImGuiDockNode* node = NULL; - bool allow_null_target_node = false; - if (window->DockNodeAsHost) - { - node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); + // (we should not assume that g.HoveredDockNode is != NULL when window is a host dock node: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos) + ImGuiDockNode* node = g.HoveredDockNode; + const bool allow_null_target_node = window->DockNode == NULL && window->DockNodeAsHost == NULL; - // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) - // In this case we need to fallback into any leaf mode, possibly the central node. - if (node && node->IsDockSpace() && node->IsRootNode()) - { - if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. - node = node->CentralNode; - else - node = DockNodeTreeFindFallbackLeafNode(node); - } + // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + if (window->DockNodeAsHost && node && node->IsDockSpace() && node->IsRootNode()) + { + if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + node = node->CentralNode; + else + node = DockNodeTreeFindFallbackLeafNode(node); } - else if (window->DockNode) // && window->DockIsActive) - node = window->DockNode; - else - allow_null_target_node = true; // Dock into a regular window const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); @@ -15824,6 +15826,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ImGui::SameLine(); if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } + ImGui::Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (!root_nodes_only || node->IsRootNode()) @@ -15967,29 +15970,21 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_DOCK // Overlay: Display Docking info - if (show_docking_nodes && g.IO.KeyCtrl) - { - ImGuiDockContext* dc = &g.DockContext; - for (int n = 0; n < dc->Nodes.Data.Size; n++) - if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) - { - ImGuiDockNode* root_node = DockNodeGetRootNode(node); - if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(root_node, g.IO.MousePos)) - if (hovered_node != node) - continue; - char buf[64] = ""; - char* p = buf; - ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); - p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); - p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId); - p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); - p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); - int depth = DockNodeGetDepth(node); - overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255)); - ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth; - overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255)); - overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf); - } + if (show_docking_nodes && g.IO.KeyCtrl && g.HoveredDockNode) + { + char buf[64] = ""; + char* p = buf; + ImGuiDockNode* node = g.HoveredDockNode; + ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); + p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); + int depth = DockNodeGetDepth(node); + overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255)); + ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth; + overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255)); + overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf); } #endif // #ifdef IMGUI_HAS_DOCK diff --git a/imgui_internal.h b/imgui_internal.h index 6f29af1e..e3253fb4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1296,6 +1296,7 @@ struct ImGuiContext ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + ImGuiDockNode* HoveredDockNode; ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; @@ -1515,6 +1516,7 @@ struct ImGuiContext HoveredWindow = NULL; HoveredRootWindow = NULL; HoveredWindowUnderMovingWindow = NULL; + HoveredDockNode = NULL; MovingWindow = NULL; WheelingWindow = NULL; WheelingWindowTimer = 0.0f; From 009276b6cbd20ee697a209370d647945877e7e39 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 15:31:48 +0200 Subject: [PATCH 177/959] Backends: Allegro 5: Fixed horizontal scrolling direction with mouse wheel / touch pads (#3394, #2424, #1463) [@nobody-special666] Amend 7dea158175615dc8939c57a06641bac911e33e8c + Fix vsproj GUID --- docs/CHANGELOG.txt | 4 +++- examples/example_allegro5/example_allegro5.vcxproj | 2 +- examples/imgui_impl_allegro5.cpp | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 76703d74..b30685f5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,7 +49,7 @@ Other Changes: clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) -- Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). +- Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). Also fixed related text clipping when used in a column after the first one. (#3187, #3386) - Scrolling: Avoid SetScroll, SetScrollFromPos functions from snapping on the edge of scroll limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many @@ -80,6 +80,8 @@ Other Changes: - Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. - Backends: OpenGL3: Added support for glad2 loader. (#3330) [@moritz-h] +- Backends: Allegro 5: Fixed horizontal scrolling direction with mouse wheel / touch pads (it seems + like Allegro 5 reports it differently from GLFW and SDL). (#3394, #2424, #1463) [@nobody-special666] - Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. (#3390) [@RoryO] diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index c86dcb2b..f5fadc37 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -19,7 +19,7 @@ - {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} + {73F235B5-7D31-4FC6-8682-DDC5A097B9C1} example_allegro5 8.1 diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 4a467c30..ca2cfae4 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-08-10: Inputs: Fixed horizontal mouse wheel direction. // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-05-11: Inputs: Don't filter character value from ALLEGRO_EVENT_KEY_CHAR before calling AddInputCharacter(). @@ -332,7 +333,7 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) if (ev->mouse.display == g_Display) { io.MouseWheel += ev->mouse.dz; - io.MouseWheelH += ev->mouse.dw; + io.MouseWheelH -= ev->mouse.dw; io.MousePos = ImVec2(ev->mouse.x, ev->mouse.y); } return true; From dbc70f21a90b0d7af93abf178ac6a0c6fa4b406b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 15:53:34 +0200 Subject: [PATCH 178/959] Docking: Fixed docking overlay bits appearing at (0,0), because of 43bd80a4. Most typically noticable when disabling multi-viewport. --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 30f31a72..f03f787a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11684,7 +11684,7 @@ struct ImGuiDockPreviewData float SplitRatio; ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() - ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; } + ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); } }; // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes) From a5ba26806f19bb85a7f146e166aa2f61e99e70a3 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 16:28:46 +0200 Subject: [PATCH 179/959] Make moving window prevent its active id from being stolen (#3392, #3243, #1738) Amend 7b3d379, 615e9ae3 --- imgui.cpp | 9 ++++++--- imgui_internal.h | 1 + imgui_widgets.cpp | 3 ++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f03f787a..9a8c8b3b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2979,6 +2979,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) } g.ActiveId = id; g.ActiveIdAllowOverlap = false; + g.ActiveIdNoClearOnFocusLoss = false; g.ActiveIdWindow = window; g.ActiveIdHasBeenEditedThisFrame = false; if (id) @@ -2996,7 +2997,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) void ImGui::ClearActiveID() { - SetActiveID(0, NULL); + SetActiveID(0, NULL); // g.ActiveId = 0; } void ImGui::SetHoveredID(ImGuiID id) @@ -3401,6 +3402,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) FocusWindow(window); SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; + g.ActiveIdNoClearOnFocusLoss = true; g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; bool can_move_window = true; @@ -6775,8 +6777,9 @@ void ImGui::FocusWindow(ImGuiWindow* window) // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. - if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window && !active_id_window_is_dock_node_host) - ClearActiveID(); + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window) + if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host) + ClearActiveID(); // Passing NULL allow to disable keyboard focus if (!window) diff --git a/imgui_internal.h b/imgui_internal.h index e3253fb4..2dada7af 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1314,6 +1314,7 @@ struct ImGuiContext float ActiveIdTimer; bool ActiveIdIsJustActivated; // Set at the time of activation for one frame bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) + bool ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. bool ActiveIdHasBeenEditedThisFrame; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 374e6b5d..1103167e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7395,8 +7395,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Undock DockContextQueueUndockWindow(&g, docked_window); g.MovingWindow = docked_window; - g.ActiveId = g.MovingWindow->MoveId; + SetActiveID(g.MovingWindow->MoveId, g.MovingWindow); g.ActiveIdClickOffset -= g.MovingWindow->Pos - bb.Min; + g.ActiveIdNoClearOnFocusLoss = true; } } } From 8241cd6284b496bba6a5800502b02f9f68af0324 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 16:28:46 +0200 Subject: [PATCH 180/959] Make moving window prevent its active id from being stolen (#3392, #3243, #1738) Amend 7b3d379, 615e9ae3 # Conflicts: # imgui.cpp # imgui_widgets.cpp --- imgui.cpp | 11 ++++++++--- imgui_internal.h | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1e541e11..c2e3bbef 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2927,6 +2927,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) } g.ActiveId = id; g.ActiveIdAllowOverlap = false; + g.ActiveIdNoClearOnFocusLoss = false; g.ActiveIdWindow = window; g.ActiveIdHasBeenEditedThisFrame = false; if (id) @@ -2944,7 +2945,7 @@ void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) void ImGui::ClearActiveID() { - SetActiveID(0, NULL); + SetActiveID(0, NULL); // g.ActiveId = 0; } void ImGui::SetHoveredID(ImGuiID id) @@ -3301,6 +3302,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) FocusWindow(window); SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; + g.ActiveIdNoClearOnFocusLoss = true; g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; bool can_move_window = true; @@ -6147,9 +6149,12 @@ void ImGui::FocusWindow(ImGuiWindow* window) ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; - // Steal focus on active widgets + // Steal active widgets. Some of the cases it triggers includes: + // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. + // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) - ClearActiveID(); + if (!g.ActiveIdNoClearOnFocusLoss) + ClearActiveID(); // Passing NULL allow to disable keyboard focus if (!window) diff --git a/imgui_internal.h b/imgui_internal.h index 79a81f99..5118d819 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1147,6 +1147,7 @@ struct ImGuiContext float ActiveIdTimer; bool ActiveIdIsJustActivated; // Set at the time of activation for one frame bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) + bool ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. bool ActiveIdHasBeenEditedThisFrame; From a4dd4d60b4afcea8185bca773249bd1ec641d726 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 17:34:14 +0200 Subject: [PATCH 181/959] CI: moved static analysis to a separate project + fix (uninitialized variable, was harmless in this case). --- .github/workflows/build.yml | 35 ---------------------- .github/workflows/static-analysis.yml | 43 +++++++++++++++++++++++++++ docs/README.md | 3 +- imgui_internal.h | 1 + 4 files changed, 46 insertions(+), 36 deletions(-) create mode 100644 .github/workflows/static-analysis.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 274ca2a6..a404f465 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -398,38 +398,3 @@ jobs: source ./emsdk_env.sh popd make -C examples/example_emscripten - - Static-Analysis: - runs-on: ubuntu-18.04 - steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 - - - name: Install Dependencies - env: - PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }} - run: | - if [[ "$PVS_STUDIO_LICENSE" != "" ]]; - then - echo "$PVS_STUDIO_LICENSE" > pvs-studio.lic - wget -q https://files.viva64.com/etc/pubkey.txt - sudo apt-key add pubkey.txt - sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list - sudo apt-get update - sudo apt-get install -y pvs-studio - fi - - - name: PVS-Studio static analysis - run: | - if [[ ! -f pvs-studio.lic ]]; - then - echo "PVS Studio license is missing. No analysis will be performed." - echo "If you have a PVS Studio license please create a project secret named PVS_STUDIO_LICENSE with your license." - echo "You may use a free license. More information at https://www.viva64.com/en/b/0457/" - exit 0 - fi - cd examples/example_null - pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 - pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log - plog-converter -a 'GA:1,2;OP:1' -t errorfile -w pvs-studio.log diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml new file mode 100644 index 00000000..7967d532 --- /dev/null +++ b/.github/workflows/static-analysis.yml @@ -0,0 +1,43 @@ +name: static-analysis + +on: + push: {} + pull_request: {} + schedule: + - cron: '0 9 * * *' + +jobs: + PVS-Studio: + runs-on: ubuntu-18.04 + steps: + - uses: actions/checkout@v1 + with: + fetch-depth: 1 + + - name: Install Dependencies + env: + PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }} + run: | + if [[ "$PVS_STUDIO_LICENSE" != "" ]]; + then + echo "$PVS_STUDIO_LICENSE" > pvs-studio.lic + wget -q https://files.viva64.com/etc/pubkey.txt + sudo apt-key add pubkey.txt + sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list + sudo apt-get update + sudo apt-get install -y pvs-studio + fi + + - name: PVS-Studio static analysis + run: | + if [[ ! -f pvs-studio.lic ]]; + then + echo "PVS Studio license is missing. No analysis will be performed." + echo "If you have a PVS Studio license please create a project secret named PVS_STUDIO_LICENSE with your license." + echo "You may use a free license. More information at https://www.viva64.com/en/b/0457/" + exit 0 + fi + cd examples/example_null + pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 + pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log + plog-converter -a 'GA:1,2;OP:1' -t errorfile -w pvs-studio.log diff --git a/docs/README.md b/docs/README.md index 9579ee22..1259a638 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,7 @@ Dear ImGui ===== -[![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) +[![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) [![Static Analysis Status](https://github.com/ocornut/imgui/workflows/static-analysis/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=static-analysis) + (This library is available under a free and permissive license, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out.) diff --git a/imgui_internal.h b/imgui_internal.h index 5118d819..e923a6af 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1352,6 +1352,7 @@ struct ImGuiContext ActiveIdTimer = 0.0f; ActiveIdIsJustActivated = false; ActiveIdAllowOverlap = false; + ActiveIdNoClearOnFocusLoss = false; ActiveIdHasBeenPressedBefore = false; ActiveIdHasBeenEditedBefore = false; ActiveIdHasBeenEditedThisFrame = false; From 214dd68ec1d62b5a885967a0e66194a8bfbfbbeb Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Aug 2020 22:05:26 +0200 Subject: [PATCH 182/959] Comments, clarifying ClosePopupsOverWindow(). --- docs/README.md | 10 +++++----- imgui.cpp | 24 ++++++++++++++++-------- imgui_internal.h | 8 ++++---- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/docs/README.md b/docs/README.md index 1259a638..58fb208e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -98,7 +98,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas ![screenshot demo](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png) You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: -- [imgui-demo-binaries-20190715.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows binaries, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). +- [imgui-demo-binaries-20200412.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.org/faq)). @@ -126,7 +126,7 @@ Some of the goals for 2020 are: - Work on docking. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch) - Work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) - Work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) -- Work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957)) +- Work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957), in public [tables](https://github.com/ocornut/imgui/tree/tables) branch looking for feedback) - Work on automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) - Make the examples look better, improve styles, improve font support, make the examples hi-DPI and multi-DPI aware. @@ -145,7 +145,7 @@ Custom engine ### Support, Frequently Asked Questions (FAQ) -Most common questions will be answered by the [Frequently Asked Questions (FAQ)](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) page. +See: [Frequently Asked Questions (FAQ)](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) where common questions are answered. See: [Wiki](https://github.com/ocornut/imgui/wiki) for many links, references, articles. @@ -161,7 +161,7 @@ Private support is available for paying business customers (E-mail: _contact @ d We occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. -You may also peak at the [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features in the `docking` branch. Many projects are using this branch and it is kept in sync with master regularly. +Advanced users may want to use the `docking` branch with [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features. This branch is kept in sync with master regularly. **Who uses Dear ImGui?** @@ -220,7 +220,7 @@ Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT li Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). -Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub. +Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Also thank you to everyone posting feedback, questions and patches on GitHub. License ------- diff --git a/imgui.cpp b/imgui.cpp index c2e3bbef..a9aabfdb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6098,7 +6098,7 @@ void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; ImGuiWindow* current_front_window = g.Windows.back(); - if (current_front_window == window || current_front_window->RootWindow == window) + if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better) return; for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window if (g.Windows[i] == window) @@ -7696,13 +7696,14 @@ void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) } } +// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. +// This function closes any popups that are over 'ref_window'. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size == 0) return; - // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. // Don't close our own child popup windows. int popup_count_to_keep = 0; if (ref_window) @@ -7717,13 +7718,20 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) continue; - // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow) - bool popup_or_descendent_is_ref_window = false; - for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++) - if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window) + // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow) + // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3: + // Window -> Popup1 -> Popup2 -> Popup3 + // - Each popups may contain child windows, which is why we compare ->RootWindow! + // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child + bool ref_window_is_descendent_of_popup = false; + for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++) + if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window) if (popup_window->RootWindow == ref_window->RootWindow) - popup_or_descendent_is_ref_window = true; - if (!popup_or_descendent_is_ref_window) + { + ref_window_is_descendent_of_popup = true; + break; + } + if (!ref_window_is_descendent_of_popup) break; } } diff --git a/imgui_internal.h b/imgui_internal.h index e923a6af..e362a04b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1127,10 +1127,10 @@ struct ImGuiContext ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow* int WindowsActiveCount; // Number of unique windows submitted by frame ImGuiWindow* CurrentWindow; // Window being drawn into - ImGuiWindow* HoveredWindow; // Will catch mouse inputs - ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. + ImGuiWindow* HoveredRootWindow; // == HoveredWindow ? HoveredWindow->RootWindow : NULL, merely a shortcut to avoid null test in some situation. ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. - ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow. + ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; float WheelingWindowTimer; @@ -1632,7 +1632,7 @@ struct IMGUI_API ImGuiWindow ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) ImDrawList DrawListInst; ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL. - ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. + ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window == Top-level window. ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. From a9626e1162c3742307553108aff8a443c20bb73c Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Aug 2020 11:51:47 +0200 Subject: [PATCH 183/959] Docking: Made DockBuilderAddNode() automatically call DockBuilderRemoveNode(). (#3399, #2109) --- imgui.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9a8c8b3b..13dfcc42 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14316,10 +14316,15 @@ void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) // - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! // For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. // - Use (id == 0) to let the system allocate a node identifier. +// - Existing node with a same id will be removed. ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) { ImGuiContext* ctx = GImGui; ImGuiDockNode* node = NULL; + + if (id != 0) + DockBuilderRemoveNode(id); + if (flags & ImGuiDockNodeFlags_DockSpace) { DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly); @@ -14327,10 +14332,7 @@ ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) } else { - if (id != 0) - node = DockContextFindNodeByID(ctx, id); - if (!node) - node = DockContextAddNode(ctx, id); + node = DockContextAddNode(ctx, id); node->LocalFlags = flags; } node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame. From 0e5b1ea297f9a0764c59ca29810c6b05c39fe6d2 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Wed, 12 Aug 2020 16:26:42 +0200 Subject: [PATCH 184/959] CI: imscripten fastcomp backend is now deprecated (#3402) Fastcomp backend was introduced here: https://github.com/ocornut/imgui/commit/14b18697e653de80f75af18113033b2086846194 Emscripten changelog: https://emscripten.org/docs/introducing_emscripten/release_notes.html?highlight=2.0.0:%2008/10/2020 Emscripten issue: https://github.com/emscripten-core/emsdk/pull/590 Updated CHANGELOG.txt --- .github/workflows/build.yml | 4 ++-- docs/CHANGELOG.txt | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a404f465..eea8eaa3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -389,8 +389,8 @@ jobs: wget -q https://github.com/emscripten-core/emsdk/archive/master.tar.gz tar -xvf master.tar.gz emsdk-master/emsdk update - emsdk-master/emsdk install latest-fastcomp - emsdk-master/emsdk activate latest-fastcomp + emsdk-master/emsdk install latest + emsdk-master/emsdk activate latest - name: Build example_emscripten run: | diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b30685f5..718cdecd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -83,6 +83,7 @@ Other Changes: - Backends: Allegro 5: Fixed horizontal scrolling direction with mouse wheel / touch pads (it seems like Allegro 5 reports it differently from GLFW and SDL). (#3394, #2424, #1463) [@nobody-special666] - Examples: Vulkan: Fixed GLFW+Vulkan and SDL+Vulkan clear color not being set. (#3390) [@RoryO] +- CI: Emscripten has stopped their support for their fastcomp backend, switching to latest sdk [@Xipiryon] ----------------------------------------------------------------------- From 46d75202b82dba5e32105219d2ea5947648a4ed8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Aug 2020 12:55:42 +0200 Subject: [PATCH 185/959] Tab Bar: Allow calling SetTabItemClosed() after a tab has been submitted (will process next frame). + larger combo height on TabBarTabListPopupButton() --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 1 + imgui_internal.h | 9 +++++---- imgui_widgets.cpp | 21 +++++++++++---------- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 718cdecd..989f8079 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,7 @@ Other Changes: limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many side-effects. The behavior is still present in SetScrollHere functions as they are more explicitly aiming at making widgets visible. May later be moved to a flag. +- Tab Bar: Allow calling SetTabItemClosed() after a tab has been submitted (will process next frame). - InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. This is a small but rather important change because lots of multi-button behaviors could previously diff --git a/docs/TODO.txt b/docs/TODO.txt index a96693b3..c0f01841 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -161,6 +161,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - dock: merge docking branch (#2109) - dock: dock out from a collapsing header? would work nicely but need emitting window to keep submitting the code. + - tabs: while dragging/reordering a tab, close button decoration shouldn't appear on other tabs - tabs: make EndTabBar fail if users doesn't respect BeginTabBar return value, for consistency/future-proofing. - tabs: persistent order/focus in BeginTabBar() api (#261, #351) - tabs: TabItem could honor SetNextItemWidth()? diff --git a/imgui_internal.h b/imgui_internal.h index e362a04b..ce1fef49 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1696,19 +1696,20 @@ enum ImGuiTabItemFlagsPrivate_ ImGuiTabItemFlags_NoCloseButton = 1 << 20 // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) }; -// Storage for one active tab item (sizeof() 26~32 bytes) +// Storage for one active tab item (sizeof() 28~32 bytes) struct ImGuiTabItem { ImGuiID ID; ImGuiTabItemFlags Flags; int LastFrameVisible; int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance - int NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames float Offset; // Position relative to beginning of tab float Width; // Width currently displayed float ContentWidth; // Width of actual contents, stored during BeginTabItem() call + ImS16 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames + bool WantClose; // Marked as closed by SetTabItemClosed() - ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; } + ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; WantClose = false; } }; // Storage for a tab bar (sizeof() 92~96 bytes) @@ -1743,7 +1744,7 @@ struct ImGuiTabBar int GetTabOrder(const ImGuiTabItem* tab) const { return Tabs.index_from_ptr(tab); } const char* GetTabName(const ImGuiTabItem* tab) const { - IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size); + IM_ASSERT(tab->NameOffset != -1 && (int)tab->NameOffset < TabsNames.Buf.Size); return TabsNames.Buf.Data + tab->NameOffset; } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 78115734..64f2f890 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6709,15 +6709,17 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiContext& g = *GImGui; tab_bar->WantLayout = false; - // Garbage collect + // Garbage collect by compacting list int tab_dst_n = 0; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; - if (tab->LastFrameVisible < tab_bar->PrevFrameVisible) + if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose) { - if (tab->ID == tab_bar->SelectedTabId) - tab_bar->SelectedTabId = 0; + // Remove tab + if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; } continue; } if (tab_dst_n != tab_src_n) @@ -7039,7 +7041,7 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) arrow_col.w *= 0.5f; PushStyleColor(ImGuiCol_Text, arrow_col); PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); - bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview); + bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest); PopStyleColor(2); ImGuiTabItem* tab_to_select = NULL; @@ -7167,7 +7169,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab->Flags = flags; // Append name with zero-terminator - tab->NameOffset = tab_bar->TabsNames.size(); + tab->NameOffset = (ImS16)tab_bar->TabsNames.size(); tab_bar->TabsNames.append(label, label + strlen(label) + 1); // If we are not reorderable, always reset offset based on submission order. @@ -7316,9 +7318,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. -// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem(). +// To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). // Tabs closed by the close button will automatically be flagged to avoid this issue. -// FIXME: We should aim to support calling SetTabItemClosed() after the tab submission (for next frame) void ImGui::SetTabItemClosed(const char* label) { ImGuiContext& g = *GImGui; @@ -7326,9 +7327,9 @@ void ImGui::SetTabItemClosed(const char* label) if (is_within_manual_tab_bar) { ImGuiTabBar* tab_bar = g.CurrentTabBar; - IM_ASSERT(tab_bar->WantLayout); // Needs to be called AFTER BeginTabBar() and BEFORE the first call to BeginTabItem() ImGuiID tab_id = TabBarCalcTabID(tab_bar, label); - TabBarRemoveTab(tab_bar, tab_id); + if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + tab->WantClose = true; // Will be processed by next call to TabBarLayout() } } From a252a287bf9ca69b2d749c5f5619b2f9a809d76c Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Sun, 24 May 2020 18:05:09 +0900 Subject: [PATCH 186/959] Drags, Sliders: Logarithmic: WIP experiments with trying to make logarithmic sliders sensible (#3361, #1823, #1316, #642) --- imgui_internal.h | 8 +++- imgui_widgets.cpp | 107 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 107 insertions(+), 8 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ce1fef49..5d24a624 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -348,6 +348,12 @@ IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* #define ImCeil(X) ceilf(X) static inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision static inline double ImPow(double x, double y) { return pow(x, y); } +static inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision +static inline double ImLog(double x) { return log(x); } +static inline float ImAbs(float x) { return fabsf(x); } +static inline double ImAbs(double x) { return fabs(x); } +static inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : ((x > 0.0f) ? 1.0f : 0.0f); } // Sign operator - returns -1, 0 or 1 based on sign of argument +static inline double ImSign(double x) { return (x < 0.0) ? -1.0 : ((x > 0.0) ? 1.0 : 0.0); } #endif // - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double // (Exceptionally using templates here but we could also redefine them for those types) @@ -1987,7 +1993,7 @@ namespace ImGui // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags); template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 64f2f890..974c2f67 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2374,15 +2374,57 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // - VSliderInt() //------------------------------------------------------------------------- +// Convert a value v in the output space of a slider into a parametric position on the slider itself template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon) { if (v_min == v_max) return 0.0f; - const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (power == 0.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); - if (is_power) + if (is_logarithmic) + { + bool flipped = v_max < v_min; + + if (flipped) // Handle the case where the range is backwards + ImSwap(v_min, v_max); + + // Fudge min/max to avoid getting close to log(0) + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_min == 0.0f) && (v_max < 0.0f)) + v_min_fudged = -logarithmic_zero_epsilon; + else if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float result; + + if (v_clamped <= v_min_fudged) + result = 0.0f; // Workaround for values that are in-range but below our fudge + else if (v_clamped >= v_max_fudged) + result = 1.0f; // Workaround for values that are in-range but above our fudge + else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions + { + float zero_point = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + if (v == 0.0f) + result = zero_point; // Special case for exactly zero + else if (v < 0.0f) + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point; + else + result = zero_point + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point)); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); + else + result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged)); + + return flipped ? (1.0f - result) : result; + } + else if (is_power) { if (v_clamped < 0.0f) { @@ -2409,7 +2451,8 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_power = (power != 1.0f) && is_decimal; + const bool is_logarithmic = (power == 0.0f) && is_decimal; + const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; @@ -2437,6 +2480,14 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; } + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + } + // Process interacting with the slider bool value_changed = false; if (g.ActiveId == id) @@ -2468,7 +2519,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if ((decimal_precision > 0) || is_power) { @@ -2496,7 +2547,49 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { TYPE v_new; - if (is_power) + if (is_logarithmic) + { + // We special-case the extents because otherwise our fudging can lead to "mathematically correct" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value + if (clicked_t <= 0.0f) + v_new = v_min; + else if (clicked_t >= 1.0f) + v_new = v_max; + else + { + bool flipped = v_max < v_min; + + // Fudge min/max to avoid getting silly results close to zero + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_min == 0.0f) && (v_max < 0.0f)) + v_min_fudged = -logarithmic_zero_epsilon; + else if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + if (flipped) + ImSwap(v_min_fudged, v_max_fudged); + + float clicked_t_with_flip = flipped ? (1.0f - clicked_t) : clicked_t; + + if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts + { + float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + if (clicked_t_with_flip == zero_point) + v_new = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) + else if (clicked_t_with_flip < zero_point) + v_new = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (clicked_t_with_flip / zero_point)))); + else + v_new = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((clicked_t_with_flip - zero_point) / (1.0f - zero_point)))); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + v_new = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - clicked_t_with_flip))); + else + v_new = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)clicked_t_with_flip)); + } + } + else if (is_power) { // Account for power curve scale on both sides of the zero if (clicked_t < linear_zero_pos) @@ -2558,7 +2651,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); From 9f98b4e7f2479e69108952476d8146817385ee72 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Tue, 2 Jun 2020 15:36:20 +0900 Subject: [PATCH 187/959] Drags, Sliders: Logarithmic: Added logarithmic mode support to drag widgets, extended API to add flags to drag/sliders (#3361, #1823, #1316, #642) --- imgui.h | 82 ++++++--- imgui_internal.h | 32 ++-- imgui_widgets.cpp | 451 +++++++++++++++++++++++++++++++--------------- 3 files changed, 379 insertions(+), 186 deletions(-) diff --git a/imgui.h b/imgui.h index c135ada2..a030ebdb 100644 --- a/imgui.h +++ b/imgui.h @@ -168,6 +168,7 @@ typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: f typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() +typedef int ImGuiDragSliderFlags; // -> enum ImGuiDragSliderFlags_ // Flags: for SliderFloat()/DragFloat()/etc // Other types #ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx'] @@ -465,36 +466,57 @@ namespace ImGui // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, float power = 1.0f); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f); + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + + // [Obsolete] + // Old drag functions that take a power term instead of flags + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg"); - IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); - IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d"); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, float power = 1.0f); + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); + + // [Obsolete] + // Old slider functions that take a power term instead of flags + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); // Widgets: Input with Keyboard // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. @@ -1282,6 +1304,14 @@ enum ImGuiColorEditFlags_ #endif }; +// Flags for configuring drag/slider widgets +enum ImGuiDragSliderFlags_ +{ + ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert + ImGuiDragSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? + ImGuiDragSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) +}; + // Identify a mouse button. // Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. enum ImGuiMouseButton_ diff --git a/imgui_internal.h b/imgui_internal.h index 5d24a624..4f5d26c7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -114,7 +114,6 @@ struct ImGuiWindowSettings; // Storage for a window .ini settings (we ke typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: BeginColumns() -typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() @@ -123,7 +122,6 @@ typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // F typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx() -typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior() typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() @@ -633,18 +631,6 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; -enum ImGuiSliderFlags_ -{ - ImGuiSliderFlags_None = 0, - ImGuiSliderFlags_Vertical = 1 << 0 -}; - -enum ImGuiDragFlags_ -{ - ImGuiDragFlags_None = 0, - ImGuiDragFlags_Vertical = 1 << 0 -}; - // Extend ImGuiSelectableFlags_ enum ImGuiSelectableFlagsPrivate_ { @@ -1981,19 +1967,27 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags); - IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags); + IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb); IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f); IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging IMGUI_API void TreePushOverrideID(ImGuiID id); + // Internal implementations for some of the exposed functions (use the non-internal versions instead) + IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " - template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags); - template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragSliderFlags flags); + template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 974c2f67..8f94426b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1997,13 +1997,14 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiContext& g = *GImGui; - const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); - const bool is_power = (power != 1.0f && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); + const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; + const bool is_power = (power != 1.0f && !is_logarithmic && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); const bool is_locked = (v_min > v_max); if (is_locked) return false; @@ -2034,6 +2035,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (axis == ImGuiAxis_Y) adjust_delta = -adjust_delta; + // For logarithmic use our range is effectively 0..1 so scale the delta into that range + if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0 + adjust_delta /= (float)(v_max - v_min); + // Clear current value on activation // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. bool is_just_activated = g.ActiveIdIsJustActivated; @@ -2056,7 +2061,21 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_cur = *v; FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; - if (is_power) + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + if (is_logarithmic) + { + // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. + const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; + logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + + // Convert to parametric space, apply delta, convert back + // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + float v_new_parametric = v_old_parametric + g.DragCurrentAccum; + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + v_old_ref_for_accum_remainder = v_old_parametric; + } + else if (is_power) { // Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); @@ -2074,7 +2093,14 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false; - if (is_power) + if (is_logarithmic) + { + // Convert to parametric space, apply delta, convert back + // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); + } + else if (is_power) { FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder); @@ -2104,8 +2130,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { + IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + ImGuiContext& g = *GImGui; if (g.ActiveId == id) { @@ -2137,9 +2165,8 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v return false; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +// Internal implementation - see below for entry points +bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2198,7 +2225,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); // Drag behavior - const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, power, ImGuiDragFlags_None); + const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, power, flags); if (value_changed) MarkItemEdited(id); @@ -2214,7 +2241,21 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, return value_changed; } -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +// Obsolete version with power parameter +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, (ImGuiDragSliderFlags)0); +} + +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, 1.0f, flags); +} + +// Internal implementation - see below for entry points +bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2231,7 +2272,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, power); + value_changed |= DragScalarInternal("", data_type, p_data, v_speed, p_min, p_max, format, power, flags); PopID(); PopItemWidth(); p_data = (void*)((char*)p_data + type_size); @@ -2249,27 +2290,63 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data return value_changed; } +// Obsolete version with power parameter +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); +} + +// Internal implementation +bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2283,14 +2360,14 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu float min = (v_min >= v_max) ? -FLT_MAX : v_min; float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power); + bool value_changed = DragScalarInternal("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); max = (v_min >= v_max) ? FLT_MAX : v_max; if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power); + value_changed |= DragScalarInternal("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2300,28 +2377,39 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu return value_changed; } +// Obsolete version with power parameter +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) +{ + return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) +{ + return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, 1.0f, flags); +} + // NB: v_speed is float to allow adjusting the drag speed with more precision -bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format); + return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format); + return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format); + return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format) +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format); + return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max) +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2335,14 +2423,14 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ int min = (v_min >= v_max) ? INT_MIN : v_min; int max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format); + bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); max = (v_min >= v_max) ? INT_MAX : v_max; if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format); + value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2374,14 +2462,14 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // - VSliderInt() //------------------------------------------------------------------------- -// Convert a value v in the output space of a slider into a parametric position on the slider itself +// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) { if (v_min == v_max) return 0.0f; - const bool is_logarithmic = (power == 0.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) @@ -2442,16 +2530,114 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); } +// Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) +template +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) +{ + if (v_min == v_max) + return (TYPE)0.0f; + + const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); + + TYPE result; + if (is_logarithmic) + { + // We special-case the extents because otherwise our fudging can lead to "mathematically correct" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value + if (t <= 0.0f) + result = v_min; + else if (t >= 1.0f) + result = v_max; + else + { + bool flipped = v_max < v_min; // Check if range is "backwards" + + // Fudge min/max to avoid getting silly results close to zero + FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; + FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; + + if (flipped) + ImSwap(v_min_fudged, v_max_fudged); + + // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) + if ((v_max == 0.0f) && (v_min < 0.0f)) + v_max_fudged = -logarithmic_zero_epsilon; + + float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range + + if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts + { + float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + if (t_with_flip == zero_point) + result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) + else if (t_with_flip < zero_point) + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point)))); + else + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point) / (1.0f - zero_point)))); + } + else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider + result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); + else + result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip)); + } + } + else if (is_power) + { + // Account for power curve scale on both sides of the zero + if (t < linear_zero_pos) + { + // Negative: rescale to the negative range before powering + float a = 1.0f - (t / linear_zero_pos); + a = ImPow(a, power); + result = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); + } + else + { + // Positive: rescale to the positive range before powering + float a; + if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) + a = (t - linear_zero_pos) / (1.0f - linear_zero_pos); + else + a = t; + a = ImPow(a, power); + result = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); + } + } + else + { + // Linear slider + if (is_decimal) + { + result = ImLerp(v_min, v_max, t); + } + else + { + // For integer values we want the clicking position to match the grab box so we round above + // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + FLOATTYPE v_new_off_f = (v_max - v_min) * t; + TYPE v_new_off_floor = (TYPE)(v_new_off_f); + TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5); + if (v_new_off_floor < v_new_off_round) + result = v_min + v_new_off_round; + else + result = v_min + v_new_off_floor; + } + } + + return result; +} + // FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template -bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (power == 0.0f) && is_decimal; + const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; @@ -2519,7 +2705,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if ((decimal_precision > 0) || is_power) { @@ -2546,91 +2732,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new; - if (is_logarithmic) - { - // We special-case the extents because otherwise our fudging can lead to "mathematically correct" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value - if (clicked_t <= 0.0f) - v_new = v_min; - else if (clicked_t >= 1.0f) - v_new = v_max; - else - { - bool flipped = v_max < v_min; - - // Fudge min/max to avoid getting silly results close to zero - FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min; - FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max; - - // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon) - if ((v_min == 0.0f) && (v_max < 0.0f)) - v_min_fudged = -logarithmic_zero_epsilon; - else if ((v_max == 0.0f) && (v_min < 0.0f)) - v_max_fudged = -logarithmic_zero_epsilon; - - if (flipped) - ImSwap(v_min_fudged, v_max_fudged); - - float clicked_t_with_flip = flipped ? (1.0f - clicked_t) : clicked_t; - - if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts - { - float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space - if (clicked_t_with_flip == zero_point) - v_new = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) - else if (clicked_t_with_flip < zero_point) - v_new = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (clicked_t_with_flip / zero_point)))); - else - v_new = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((clicked_t_with_flip - zero_point) / (1.0f - zero_point)))); - } - else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider - v_new = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - clicked_t_with_flip))); - else - v_new = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)clicked_t_with_flip)); - } - } - else if (is_power) - { - // Account for power curve scale on both sides of the zero - if (clicked_t < linear_zero_pos) - { - // Negative: rescale to the negative range before powering - float a = 1.0f - (clicked_t / linear_zero_pos); - a = ImPow(a, power); - v_new = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); - } - else - { - // Positive: rescale to the positive range before powering - float a; - if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) - a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); - else - a = clicked_t; - a = ImPow(a, power); - v_new = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); - } - } - else - { - // Linear slider - if (is_decimal) - { - v_new = ImLerp(v_min, v_max, clicked_t); - } - else - { - // For integer values we want the clicking position to match the grab box so we round above - // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. - FLOATTYPE v_new_off_f = (v_max - v_min) * clicked_t; - TYPE v_new_off_floor = (TYPE)(v_new_off_f); - TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5); - if (v_new_off_floor < v_new_off_round) - v_new = v_min + v_new_off_round; - else - v_new = v_min + v_new_off_floor; - } - } + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); // Round to user desired precision based on format string v_new = RoundScalarWithFormatT(format, data_type, v_new); @@ -2651,7 +2753,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); @@ -2667,8 +2769,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // For 32-bit and larger types, slider bounds are limited to half the natural type range. // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. -bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) { + IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) return false; @@ -2703,9 +2807,8 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type return false; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +// Internal implementation +bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2762,7 +2865,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, ImGuiSliderFlags_None, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -2782,8 +2885,20 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat return value_changed; } -// Add multiple sliders on 1 line for compact edition of multiple components -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +{ + return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); +} + +bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2800,7 +2915,7 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power); + value_changed |= SliderScalarInternal("", data_type, v, v_min, v_max, format, power, flags); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); @@ -2818,57 +2933,94 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i return value_changed; } +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) +{ + return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); +} + +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } -bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format) +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiDragSliderFlags flags) { if (format == NULL) format = "%.0f deg"; float v_deg = (*v_rad) * 360.0f / (2 * IM_PI); - bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags); *v_rad = v_deg * (2 * IM_PI) / 360.0f; return value_changed; } -bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format) +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format); + return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format) +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format); + return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format) +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format); + return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format) +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format); + return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); } -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +// Internal implementation +bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2908,7 +3060,7 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, ImGuiSliderFlags_Vertical, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiDragSliderFlags_Vertical, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -2927,14 +3079,31 @@ bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType d return value_changed; } +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +{ + return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, 1.0f, flags); +} + +// Obsolete version with power parameter +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +{ + return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +{ + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); +} + +// Obsolete version with power parameter bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) { return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } -bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format) +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) { - return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format); + return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } //------------------------------------------------------------------------- From 152dae9e2aeab833b753541a974cecbb9a0eb2b9 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 14:52:26 +0200 Subject: [PATCH 188/959] Drags, Sliders: Logarithmic: Split back flags into drag/slider flags. Moved to an obsolete section. (#3361, #1823, #1316, #642) --- imgui.h | 113 ++++++++++---------- imgui_internal.h | 24 ++--- imgui_widgets.cpp | 261 +++++++++++++++++++++++----------------------- 3 files changed, 200 insertions(+), 198 deletions(-) diff --git a/imgui.h b/imgui.h index a030ebdb..3ee9074b 100644 --- a/imgui.h +++ b/imgui.h @@ -157,6 +157,7 @@ typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: f typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() +typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragFloat(), DragInt() etc. typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. @@ -164,11 +165,11 @@ typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: f typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super) typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderFloat(), SliderInt() etc. typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() -typedef int ImGuiDragSliderFlags; // -> enum ImGuiDragSliderFlags_ // Flags: for SliderFloat()/DragFloat()/etc // Other types #ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx'] @@ -466,57 +467,36 @@ namespace ImGui // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - - // [Obsolete] - // Old drag functions that take a power term instead of flags - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiDragSliderFlags flags = 0); - - // [Obsolete] - // Old slider functions that take a power term instead of flags - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0); // Widgets: Input with Keyboard // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. @@ -1304,12 +1284,22 @@ enum ImGuiColorEditFlags_ #endif }; -// Flags for configuring drag/slider widgets -enum ImGuiDragSliderFlags_ +// Flags for DragFloat(), DragInt() etc. +enum ImGuiDragFlags_ +{ + ImGuiDragFlags_None = 0, + ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert + ImGuiDragFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? + ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) +}; + +// Flags for SliderFloat(), SliderInt() etc. +enum ImGuiSliderFlags_ { - ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert - ImGuiDragSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? - ImGuiDragSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_None = 0, + ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert + ImGuiSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? + ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) }; // Identify a mouse button. @@ -1715,6 +1705,23 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { + // OBSOLETED in 1.78 (from July 2020) + // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); + IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); + IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); // OBSOLETED in 1.77 (from June 2020) static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupContextItem(str_id, mb); } // Passing a mouse button to ImGuiPopupFlags is legal static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } diff --git a/imgui_internal.h b/imgui_internal.h index 4f5d26c7..9f4573f4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1967,27 +1967,27 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags); - IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags); + IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f); IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging IMGUI_API void TreePushOverrideID(ImGuiID id); // Internal implementations for some of the exposed functions (use the non-internal versions instead) - IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); - IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragSliderFlags flags = 0); + IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); + IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); + IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); + IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); + IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " - template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragSliderFlags flags); - template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags); + template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8f94426b..16f095dd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1997,13 +1997,13 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiContext& g = *GImGui; - const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; + const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; const bool is_power = (power != 1.0f && !is_logarithmic && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); const bool is_locked = (v_min > v_max); if (is_locked) @@ -2130,9 +2130,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT(((flags == 0) || (flags >= ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragFlags flags - has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2166,7 +2166,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } // Internal implementation - see below for entry points -bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2241,21 +2241,15 @@ bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* return value_changed; } -// Obsolete version with power parameter -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) -{ - return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, (ImGuiDragSliderFlags)0); -} - // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, 1.0f, flags); } // Internal implementation - see below for entry points -bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2290,63 +2284,33 @@ bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void return value_changed; } -// Obsolete version with power parameter -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) -{ - return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); -} - -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } // Internal implementation -bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragSliderFlags flags) +bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2377,39 +2341,33 @@ bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, flo return value_changed; } -// Obsolete version with power parameter -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) -{ - return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); -} - -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, 1.0f, flags); } // NB: v_speed is float to allow adjusting the drag speed with more precision -bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragSliderFlags flags) +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2441,6 +2399,46 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ return value_changed; } +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// Obsolete versions with power parameter +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, ImGuiDragFlags_None); +} + +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) +{ + return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); +} + +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) +{ + return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) +{ + return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); +} + +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //------------------------------------------------------------------------- // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. //------------------------------------------------------------------------- @@ -2464,12 +2462,12 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) @@ -2532,13 +2530,13 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiDragSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); TYPE result; @@ -2630,14 +2628,14 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m // FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template -bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiAxis axis = (flags & ImGuiDragSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (flags & ImGuiDragSliderFlags_Logarithmic) && is_decimal; + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal; const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; @@ -2769,9 +2767,9 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // For 32-bit and larger types, slider bounds are limited to half the natural type range. // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. -bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiDragSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragSliderFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT(((flags == 0) || (flags >= ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiSliderFlags flags - has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) @@ -2808,7 +2806,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type } // Internal implementation -bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2887,18 +2885,12 @@ bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, voi // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) -{ - return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); -} - -bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2934,62 +2926,32 @@ bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, vo } // Add multiple sliders on 1 line for compact edition of multiple components -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) -{ - return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); -} - -bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) -{ - return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); -} - -bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags) { if (format == NULL) format = "%.0f deg"; @@ -2999,28 +2961,28 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl return value_changed; } -bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags); } -bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); } // Internal implementation -bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragSliderFlags flags) +bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3060,7 +3022,7 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiDragSliderFlags_Vertical, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiSliderFlags_Vertical, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -3079,33 +3041,66 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa return value_changed; } -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, 1.0f, flags); } -// Obsolete version with power parameter -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { - return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); } -bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { - return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); + return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); } -// Obsolete version with power parameter -bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +// Obsolete versions with power parameter +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) { - return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); + return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); } -bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiDragSliderFlags flags) +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) { - return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags); + return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); +} + +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) +{ + return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) +{ + return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); +} + +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) +{ + return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) +{ + return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); +} + +#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS + //------------------------------------------------------------------------- // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. //------------------------------------------------------------------------- From 43c099f31ebe89e94d4e54223f3a2d0dc84f8bce Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 18:00:50 +0200 Subject: [PATCH 189/959] Drags, Sliders: Logarithmic: Moved flags to internals, allowing 1.0f to pass by. (#3361, #1823, #1316, #642) --- imgui.h | 10 ++++----- imgui_demo.cpp | 54 +++++++++++++++++++++++------------------------ imgui_internal.h | 12 +++++++++++ imgui_widgets.cpp | 4 ++-- 4 files changed, 45 insertions(+), 35 deletions(-) diff --git a/imgui.h b/imgui.h index 3ee9074b..dc62afc0 100644 --- a/imgui.h +++ b/imgui.h @@ -1288,18 +1288,16 @@ enum ImGuiColorEditFlags_ enum ImGuiDragFlags_ { ImGuiDragFlags_None = 0, - ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert - ImGuiDragFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? - ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) }; // Flags for SliderFloat(), SliderInt() etc. enum ImGuiSliderFlags_ { ImGuiSliderFlags_None = 0, - ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm = 8, // We treat anything < this as being potentially a (float) power term from the previous API that has got miscast to this enum, and trigger an assert - ImGuiSliderFlags_Vertical = 1 << 3, // Should this widget be orientated vertically? - ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1e5c59b8..587964f6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -629,7 +629,7 @@ static void ShowDemoWindowWidgets() static float f1 = 0.123f, f2 = 0.0f; ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); - ImGui::SliderFloat("slider float (curve)", &f2, -10.0f, 10.0f, "%.4f", 2.0f); + ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); static float angle = 0.0f; ImGui::SliderAngle("slider angle", &angle); @@ -1557,34 +1557,34 @@ static void ShowDemoWindowWidgets() ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms"); ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL); - ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", 1.0f); - ImGui::DragScalar("drag float ^2", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", 2.0f); ImGui::SameLine(); HelpMarker("You can use the 'power' parameter to increase tweaking precision on one side of the range."); - ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams", 1.0f); - ImGui::DragScalar("drag double ^2", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", 2.0f); + ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f"); + ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiDragFlags_Logarithmic); + ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); + ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiDragFlags_Logarithmic); ImGui::Text("Sliders"); - ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); - ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u"); - ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d"); - ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u"); - ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d"); - ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d"); - ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d"); - ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); - ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); - ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); - ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%I64d"); - ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%I64d"); - ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%I64d"); - ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%I64u ms"); - ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms"); - ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms"); - ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); - ImGui::SliderScalar("slider float low^2", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", 2.0f); - ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); - ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams", 1.0f); - ImGui::SliderScalar("slider double low^2",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", 2.0f); - ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams", 1.0f); + ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); + ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u"); + ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d"); + ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u"); + ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d"); + ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d"); + ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d"); + ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u"); + ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u"); + ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u"); + ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%I64d"); + ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%I64d"); + ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%I64d"); + ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%I64u ms"); + ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms"); + ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms"); + ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); + ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); + ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); + ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); static bool inputs_step = true; ImGui::Text("Inputs"); diff --git a/imgui_internal.h b/imgui_internal.h index 9f4573f4..c2d58a18 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -631,6 +631,18 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; +// Extend ImGuiDragFlags_ +enum ImGuiDragFlagsPrivate_ +{ + ImGuiDragFlags_Vertical = 1 << 20 // Should this widget be orientated vertically? +}; + +// Extend ImGuiSliderFlags_ +enum ImGuiSliderFlagsPrivate_ +{ + ImGuiSliderFlags_Vertical = 1 << 20 // Should this slider be orientated vertically? +}; + // Extend ImGuiSelectableFlags_ enum ImGuiSelectableFlagsPrivate_ { diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 16f095dd..6de8ce12 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2132,7 +2132,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiDragFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiDragFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2769,7 +2769,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { - IM_ASSERT(((flags == 0) || (flags >= ImGuiSliderFlags__AnythingBelowThisMightBeAPowerTerm)) && "Invalid ImGuiSliderFlags flags - has a power term been mistakenly cast to flags?"); + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has a power term been mistakenly cast to flags?"); ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) From 7607aea018a603fac69aa2ce373eacce757dcb03 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jul 2020 19:33:03 +0200 Subject: [PATCH 190/959] Drags, Sliders: Removed power features. Old entry points will pass-through if power=1.0f, otherwise assert + safe fallback. Remove 3 redirection functions (#3361, #1823, #1316, #642) --- docs/CHANGELOG.txt | 32 +++++ imgui.cpp | 8 ++ imgui.h | 27 ++-- imgui_internal.h | 19 +-- imgui_widgets.cpp | 311 +++++++++++++-------------------------------- 5 files changed, 148 insertions(+), 249 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 989f8079..5348ad15 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,32 @@ HOW TO UPDATE? VERSION 1.78 WIP (In Progress) ----------------------------------------------------------------------- +Breaking Changes: + +- Obsoleted use of the trailing 'float power=1.0f' parameter for those functions: [@Shironekoben, @ocornut] + - DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN() + - SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN() + - VSliderFloat(), VSliderScalar() + Replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). + The type of those flags are ImGuiDragFlags and ImGuiSliderFlags (underlying int storage). + Worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. + In short, when calling those functions: + - If you omitted the 'power' parameter (likely!), you are not affected. + - If you set the 'power' parameter to 1.0f (same as previous default value): + - Your compiler may warn on float>int conversion. + - Everything else will work. + - You can replace the 1.0f value with 0 to fix the warning, and be technically correct. + - If you set the 'power' parameter to >1.0f (to enable non-linear editing): + - Your compiler may warn on float>int conversion. + - Code will assert at runtime for IM_ASSERT(power == 1.0f) with the following assert description: + "Call Drag function with ImGuiDragFlags_Logarithmic instead of using the old 'float power' function!". + - In case asserts are disabled, the code will not crash and enable the _Logarithmic flag. + - You can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic + to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + See https://github.com/ocornut/imgui/issues/3361 for all details. + Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). + For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. + Other Changes: - Nav: Fixed clicking on void (behind any windows) from not clearing the focused window. @@ -42,6 +68,12 @@ Other Changes: flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. +- Drag, Slider: Added ImGuiDragFlags and ImGuiSliderFlags parameters. + For float functions they replace the old trailing 'float power=1.0' parameter. + (See #3361 and the "Breaking Changes" block above for all details). +- Drag, Slider: Added ImGuiDragFlags_Logarithmic/ImGuiSliderFlags_Logarithmic flags to + enable logarithmic editing (generally more precision around zero), as a replacement to the old + 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.cpp b/imgui.cpp index a9aabfdb..197ce1f9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,14 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). + replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). + worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: + - if you omitted the 'power' parameter (likely!), you are not affected. + - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct. + - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic flag to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + see https://github.com/ocornut/imgui/issues/3361 for all details. + kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. diff --git a/imgui.h b/imgui.h index dc62afc0..59eb6d04 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.78 WIP" -#define IMGUI_VERSION_NUM 17703 +#define IMGUI_VERSION_NUM 17704 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -467,6 +467,8 @@ namespace ImGui // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiDragFlags flags=0' argument. + // If you get a warning converting a float to ImGuiDragFlags, read https://github.com/ocornut/imgui/issues/3361 IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); // If v_min >= v_max we have no bound IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); @@ -483,6 +485,8 @@ namespace ImGui // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); @@ -1703,23 +1707,20 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { - // OBSOLETED in 1.78 (from July 2020) + // OBSOLETED in 1.78 (from August 2020) // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power); IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power); + static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } + static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power); - IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power); + static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } + static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } + static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } + static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.77 (from June 2020) static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupContextItem(str_id, mb); } // Passing a mouse button to ImGuiPopupFlags is legal static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } diff --git a/imgui_internal.h b/imgui_internal.h index c2d58a18..95ce67c0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1979,27 +1979,20 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags); - IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags); + IMGUI_API bool SliderBehavior(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); IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f); IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging IMGUI_API void TreePushOverrideID(ImGuiID id); - // Internal implementations for some of the exposed functions (use the non-internal versions instead) - IMGUI_API bool DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); - IMGUI_API bool DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); - IMGUI_API bool DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format = NULL, const char* format_max = NULL, float power = 1.0f, ImGuiDragFlags flags = 0); - IMGUI_API bool SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); - IMGUI_API bool SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); - IMGUI_API bool VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, float power = 1.0f, ImGuiSliderFlags flags = 0); // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " - template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags); - template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiDragFlags flags); + template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6de8ce12..65021bba 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1997,14 +1997,13 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiDragFlags flags) { ImGuiContext& g = *GImGui; const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; - const bool is_power = (power != 1.0f && !is_logarithmic && is_decimal && is_clamped && (v_max - v_min < FLT_MAX)); const bool is_locked = (v_min > v_max); if (is_locked) return false; @@ -2043,8 +2042,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. bool is_just_activated = g.ActiveIdIsJustActivated; bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); - bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0)); - if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power) + if (is_just_activated || is_already_past_limits_and_pushing_outward) { g.DragCurrentAccum = 0.0f; g.DragCurrentAccumDirty = false; @@ -2069,20 +2067,11 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, flags); v_old_ref_for_accum_remainder = v_old_parametric; } - else if (is_power) - { - // Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range - FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); - FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min)); - v_cur = v_min + (SIGNEDTYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min); - v_old_ref_for_accum_remainder = v_old_norm_curved; - } else { v_cur += (SIGNEDTYPE)g.DragCurrentAccum; @@ -2096,15 +2085,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - // We pass 0.0f as linear_zero_pos because we know we are never in power mode here and so don't need it - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, power, /*linear_zero_pos*/ 0.0f, logarithmic_zero_epsilon, flags); + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } - else if (is_power) - { - FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); - g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder); - } else { g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v); @@ -2130,9 +2113,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { - IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has a power term been mistakenly cast to flags?"); + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiDragFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2149,32 +2133,30 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v switch (data_type) { - case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } - case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } - case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } - case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } - case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, power, flags); - case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, power, flags); - case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, power, flags); - case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, power, flags); - case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, power, flags); - case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, power, flags); + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, flags); + case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, flags); + case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, flags); + case ImGuiDataType_U64: return DragBehaviorT(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, flags); + case ImGuiDataType_Float: return DragBehaviorT(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, flags); + case ImGuiDataType_Double: return DragBehaviorT(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, flags); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); return false; } -// Internal implementation - see below for entry points -bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. +// Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - if (power != 1.0f) - IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds - ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); @@ -2225,7 +2207,7 @@ bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); // Drag behavior - const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, power, flags); + const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags); if (value_changed) MarkItemEdited(id); @@ -2241,15 +2223,7 @@ bool ImGui::DragScalarInternal(const char* label, ImGuiDataType data_type, void* return value_changed; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) -{ - return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, 1.0f, flags); -} - -// Internal implementation - see below for entry points -bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags) +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2266,7 +2240,7 @@ bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= DragScalarInternal("", data_type, p_data, v_speed, p_min, p_max, format, power, flags); + value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags); PopID(); PopItemWidth(); p_data = (void*)((char*)p_data + type_size); @@ -2284,11 +2258,6 @@ bool ImGui::DragScalarNInternal(const char* label, ImGuiDataType data_type, void return value_changed; } -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) -{ - return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, 1.0f, flags); -} - bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); @@ -2309,8 +2278,7 @@ bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } -// Internal implementation -bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power, ImGuiDragFlags flags) +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2324,14 +2292,14 @@ bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, flo float min = (v_min >= v_max) ? -FLT_MAX : v_min; float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - bool value_changed = DragScalarInternal("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, power, flags); + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); max = (v_min >= v_max) ? FLT_MAX : v_max; if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - value_changed |= DragScalarInternal("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, power, flags); + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2341,11 +2309,6 @@ bool ImGui::DragFloatRange2Internal(const char* label, float* v_current_min, flo return value_changed; } -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) -{ - return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, 1.0f, flags); -} - // NB: v_speed is float to allow adjusting the drag speed with more precision bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) { @@ -2401,40 +2364,29 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -// Obsolete versions with power parameter +// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - return DragScalarInternal(label, data_type, p_data, v_speed, p_min, p_max, format, power, ImGuiDragFlags_None); + ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds + drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + } + return DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, drag_flags); } bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - return DragScalarNInternal(label, data_type, p_data, components, v_speed, p_min, p_max, format, power); -} - -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) -{ - return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); -} - -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) -{ - return DragFloatRange2Internal(label, v_current_min, v_current_max, v_speed, v_min, v_max, format, format_max, power); + ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds + drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + } + return DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, drag_flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -2462,13 +2414,12 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); - const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) { @@ -2510,19 +2461,6 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return flipped ? (1.0f - result) : result; } - else if (is_power) - { - if (v_clamped < 0.0f) - { - const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min)); - return (1.0f - ImPow(f, 1.0f / power)) * linear_zero_pos; - } - else - { - const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min))); - return linear_zero_pos + ImPow(f, 1.0f / power) * (1.0f - linear_zero_pos); - } - } // Linear slider return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); @@ -2530,14 +2468,13 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float power, float linear_zero_pos, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); - const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) && (!is_logarithmic); TYPE result; if (is_logarithmic) @@ -2580,28 +2517,6 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip)); } } - else if (is_power) - { - // Account for power curve scale on both sides of the zero - if (t < linear_zero_pos) - { - // Negative: rescale to the negative range before powering - float a = 1.0f - (t / linear_zero_pos); - a = ImPow(a, power); - result = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); - } - else - { - // Positive: rescale to the positive range before powering - float a; - if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) - a = (t - linear_zero_pos) / (1.0f - linear_zero_pos); - else - a = t; - a = ImPow(a, power); - result = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); - } - } else { // Linear slider @@ -2628,7 +2543,7 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m // FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template -bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; @@ -2636,7 +2551,6 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal; - const bool is_power = (power != 1.0f) && is_decimal && (!is_logarithmic); const float grab_padding = 2.0f; const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; @@ -2649,21 +2563,6 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f; const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; - // For power curve sliders that cross over sign boundary we want the curve to be symmetric around 0.0f - float linear_zero_pos; // 0.0->1.0f - if (is_power && v_min * v_max < 0.0f) - { - // Different sign - const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f / power); - const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f / power); - linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0)); - } - else - { - // Same sign - linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; - } - float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true if (is_logarithmic) { @@ -2703,9 +2602,9 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; - if ((decimal_precision > 0) || is_power) + if (decimal_precision > 0) { delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds if (IsNavInputDown(ImGuiNavInput_TweakSlow)) @@ -2730,7 +2629,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, flags); // Round to user desired precision based on format string v_new = RoundScalarWithFormatT(format, data_type, v_new); @@ -2751,7 +2650,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, power, linear_zero_pos, logarithmic_zero_epsilon, flags); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); @@ -2767,9 +2666,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ // For 32-bit and larger types, slider bounds are limited to half the natural type range. // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. -bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) +bool ImGui::SliderBehavior(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) { - IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has a power term been mistakenly cast to flags?"); + // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) @@ -2777,36 +2677,37 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type switch (data_type) { - case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } - case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } - case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } - case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; } case ImGuiDataType_S32: IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, flags, out_grab_bb); case ImGuiDataType_U32: IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, flags, out_grab_bb); case ImGuiDataType_S64: IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, flags, out_grab_bb); case ImGuiDataType_U64: IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2); - return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, flags, out_grab_bb); case ImGuiDataType_Float: IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f); - return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, flags, out_grab_bb); case ImGuiDataType_Double: IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f); - return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, power, flags, out_grab_bb); + return SliderBehaviorT(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, flags, out_grab_bb); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); return false; } -// Internal implementation -bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) +// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. +// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. +bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2863,7 +2764,7 @@ bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, voi // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -2883,14 +2784,8 @@ bool ImGui::SliderScalarInternal(const char* label, ImGuiDataType data_type, voi return value_changed; } -// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required. -// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) -{ - return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, 1.0f, flags); -} - -bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags) +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2907,7 +2802,7 @@ bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, vo PushID(i); if (i > 0) SameLine(0, g.Style.ItemInnerSpacing.x); - value_changed |= SliderScalarInternal("", data_type, v, v_min, v_max, format, power, flags); + value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); @@ -2925,12 +2820,6 @@ bool ImGui::SliderScalarNInternal(const char* label, ImGuiDataType data_type, vo return value_changed; } -// Add multiple sliders on 1 line for compact edition of multiple components -bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags) -{ - return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, 1.0f, flags); -} - bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); @@ -2981,8 +2870,7 @@ bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags); } -// Internal implementation -bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags) +bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -3022,7 +2910,7 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa // Slider behavior ImRect grab_bb; - const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, flags | ImGuiSliderFlags_Vertical, &grab_bb); + const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb); if (value_changed) MarkItemEdited(id); @@ -3041,11 +2929,6 @@ bool ImGui::VSliderScalarInternal(const char* label, const ImVec2& size, ImGuiDa return value_changed; } -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) -{ - return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, 1.0f, flags); -} - bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags); @@ -3058,45 +2941,27 @@ bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -// Obsolete versions with power parameter +// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) { - return SliderScalarInternal(label, data_type, p_data, p_min, p_max, format, power); + ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + slider_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return SliderScalar(label, data_type, p_data, p_min, p_max, format, slider_flags); } bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) { - return SliderScalarNInternal(label, data_type, v, components, v_min, v_max, format, power); -} - -bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) -{ - return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); -} - -bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) -{ - return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); -} - -bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power) -{ - return VSliderScalarInternal(label, size, data_type, p_data, p_min, p_max, format, power); -} - -bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) -{ - return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); + ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + if (power != 1.0f) + { + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); + slider_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths + } + return SliderScalarN(label, data_type, v, components, v_min, v_max, format, slider_flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS From 170d02bd99f0d3d5d01e3b5ace51160c5c0f7cc1 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 17:39:22 +0200 Subject: [PATCH 191/959] Drags, Sliders: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force clamping value when using CTRL+Click to type in a value manually. (#1829, #3209) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 8 +++++-- imgui_demo.cpp | 39 +++++++++++++++++++++++++++---- imgui_widgets.cpp | 57 ++++++++++++++++++++++------------------------ 4 files changed, 70 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5348ad15..ebdfb898 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -74,6 +74,8 @@ Other Changes: - Drag, Slider: Added ImGuiDragFlags_Logarithmic/ImGuiSliderFlags_Logarithmic flags to enable logarithmic editing (generally more precision around zero), as a replacement to the old 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] +- Drag, Slider: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force + clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.h b/imgui.h index 59eb6d04..1bf0f4a5 100644 --- a/imgui.h +++ b/imgui.h @@ -464,6 +464,7 @@ namespace ImGui // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. @@ -485,6 +486,7 @@ namespace ImGui // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. + // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. @@ -1293,7 +1295,8 @@ enum ImGuiDragFlags_ { ImGuiDragFlags_None = 0, ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. - ImGuiDragFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiDragFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) }; // Flags for SliderFloat(), SliderInt() etc. @@ -1301,7 +1304,8 @@ enum ImGuiSliderFlags_ { ImGuiSliderFlags_None = 0, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. - ImGuiSliderFlags_Logarithmic = 1 << 4 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiSliderFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 587964f6..62a7d1fe 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1488,6 +1488,38 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } + if (ImGui::TreeNode("Drag/Slider Flags")) + { + // Demonstrate using advanced flags for DragXXX functions + static ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + ImGui::CheckboxFlags("ImGuiDragFlags_ClampOnInput", (unsigned int*)&drag_flags, ImGuiDragFlags_ClampOnInput); + ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); + ImGui::CheckboxFlags("ImGuiDragFlags_Logarithmic", (unsigned int*)&drag_flags, ImGuiDragFlags_Logarithmic); + ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + + static float drag_f = 0.5f; + static int drag_i = 50; + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%f", drag_flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%f", drag_flags); + ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", drag_flags); + + // Demonstrate using advanced flags for SliderXXX functions + static ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_ClampOnInput); + ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&slider_flags, ImGuiSliderFlags_Logarithmic); + ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + + static float slider_f = 0.5f; + static int slider_i = 50; + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, NULL, slider_flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, NULL, slider_flags); + + ImGui::TreePop(); + } + if (ImGui::TreeNode("Range Widgets")) { static float begin = 10, end = 90; @@ -3853,10 +3885,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "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; - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale only this window - ImGui::SetWindowFontScale(IM_MAX(window_scale, MIN_SCALE)); - if (ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f")) // Scale everything - io.FontGlobalScale = IM_MAX(io.FontGlobalScale, MIN_SCALE); + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput)) // Scale only this window + ImGui::SetWindowFontScale(window_scale); + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput); // Scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 65021bba..7b3bb996 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1910,10 +1910,11 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b } template -static bool ClampBehaviorT(T* v, T v_min, T v_max) +static bool ClampBehaviorT(T* v, const T* v_min, const T* v_max) { - if (*v < v_min) { *v = v_min; return true; } - if (*v > v_max) { *v = v_max; return true; } + // Clamp, both sides are optional + if (v_min && *v < *v_min) { *v = *v_min; return true; } + if (v_max && *v > *v_max) { *v = *v_max; return true; } return false; } @@ -1921,16 +1922,16 @@ bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_m { switch (data_type) { - case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, *(const ImS8* )p_min, *(const ImS8* )p_max); - case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, *(const ImU8* )p_min, *(const ImU8* )p_max); - case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, *(const ImS16* )p_min, *(const ImS16* )p_max); - case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, *(const ImU16* )p_min, *(const ImU16* )p_max); - case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, *(const ImS32* )p_min, *(const ImS32* )p_max); - case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, *(const ImU32* )p_min, *(const ImU32* )p_max); - case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, *(const ImS64* )p_min, *(const ImS64* )p_max); - case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, *(const ImU64* )p_min, *(const ImU64* )p_max); - case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, *(const float* )p_min, *(const float* )p_max); - case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, *(const double*)p_min, *(const double*)p_max); + case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); + case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); + case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); + case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); + case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); + case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); + case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); + case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); + case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, (const float* )p_min, (const float* )p_max); + case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, (const double*)p_min, (const double*)p_max); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); @@ -2197,9 +2198,12 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, } } - // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); + { + // Only clamp CTRL+Click input when ImGuiDragFlags_ClampInput is set + const bool is_clamp_input = (flags & ImGuiDragFlags_ClampOnInput) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + } // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -2753,9 +2757,12 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat } } - // Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that.. if (temp_input_is_active) - return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max); + { + // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + } // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -3081,20 +3088,10 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* return value_changed; } -// Note that Drag/Slider functions are currently NOT forwarding the min/max values clamping values! +// Note that Drag/Slider functions are only forwarding the min/max values clamping values if the +// ImGuiDragFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. -// In the future we should add flags to Slider/Drag to specify how to enforce min/max values with CTRL+Click. -// See GitHub issues #1829 and #3209 -// In the meanwhile, you can easily "wrap" those functions to enforce clamping, using wrapper functions, e.g. -// bool SliderFloatClamp(const char* label, float* v, float v_min, float v_max) -// { -// float v_backup = *v; -// if (!SliderFloat(label, v, v_min, v_max)) -// return false; -// *v = ImClamp(*v, v_min, v_max); -// return v_backup != *v; -// } bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) { ImGuiContext& g = *GImGui; @@ -3117,7 +3114,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG // Apply new value (or operations) then clamp DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL); - if (p_clamp_min && p_clamp_max) + if (p_clamp_min || p_clamp_max) DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); // Only mark as edited if new value is different From 8018623c5b478e050fbfd8df1882ca94cccaeaec Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 23 Jul 2020 23:01:10 +0200 Subject: [PATCH 192/959] Drags, Sliders: Added ImGuiDragFlags_NoRoundToFormat / ImGuiSliderFlags_NoRoundToFormat flags (#642) --- docs/CHANGELOG.txt | 2 ++ imgui.h | 6 ++++-- imgui_demo.cpp | 18 ++++++++++++------ imgui_widgets.cpp | 6 ++++-- 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ebdfb898..2936c201 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,6 +76,8 @@ Other Changes: 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] - Drag, Slider: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). +- Drag, Slider: Added ImGuiDragFlags_NoRoundToFormat/ImGuiSliderFlags_NoRoundToFormat flags + to disable rounding underlying value to match precision of the display format string. (#642) - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.h b/imgui.h index 1bf0f4a5..feaeb811 100644 --- a/imgui.h +++ b/imgui.h @@ -1296,7 +1296,8 @@ enum ImGuiDragFlags_ ImGuiDragFlags_None = 0, ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiDragFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) + ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) + ImGuiDragFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) }; // Flags for SliderFloat(), SliderInt() etc. @@ -1305,7 +1306,8 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_None = 0, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiSliderFlags_Logarithmic = 1 << 5 // Should this widget be logarithmic? (linear otherwise) + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) + ImGuiSliderFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 62a7d1fe..1f737cc5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1496,13 +1496,16 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); ImGui::CheckboxFlags("ImGuiDragFlags_Logarithmic", (unsigned int*)&drag_flags, ImGuiDragFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + ImGui::CheckboxFlags("ImGuiDragFlags_NoRoundToFormat", (unsigned int*)&drag_flags, ImGuiDragFlags_NoRoundToFormat); + ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); static float drag_f = 0.5f; static int drag_i = 50; - ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%f", drag_flags); - ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%f", drag_flags); + ImGui::Text("Underlying float value: %f", drag_f); + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", drag_flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", drag_flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", drag_flags); ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", drag_flags); // Demonstrate using advanced flags for SliderXXX functions @@ -1511,11 +1514,14 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&slider_flags, ImGuiSliderFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoRoundToFormat); + ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); static float slider_f = 0.5f; static int slider_i = 50; - ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, NULL, slider_flags); - ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, NULL, slider_flags); + ImGui::Text("Underlying float value: %f", slider_f); + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", slider_flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", slider_flags); ImGui::TreePop(); } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 7b3bb996..239c125d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2079,7 +2079,8 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const } // Round to user desired precision based on format string - v_cur = RoundScalarWithFormatT(format, data_type, v_cur); + if (!(flags & ImGuiDragFlags_NoRoundToFormat)) + v_cur = RoundScalarWithFormatT(format, data_type, v_cur); // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false; @@ -2636,7 +2637,8 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, flags); // Round to user desired precision based on format string - v_new = RoundScalarWithFormatT(format, data_type, v_new); + if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); // Apply result if (*v != v_new) From f75b29e7be08b7abeb2df295a087cb79cff0252d Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 24 Jul 2020 13:41:14 +0200 Subject: [PATCH 193/959] Drags, Sliders: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning widget into a text input with CTRL+Click or Nav Enter. --- docs/CHANGELOG.txt | 2 ++ imgui.h | 10 ++++++---- imgui_demo.cpp | 4 ++++ imgui_widgets.cpp | 14 ++++++++------ 4 files changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2936c201..23959298 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -78,6 +78,8 @@ Other Changes: clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). - Drag, Slider: Added ImGuiDragFlags_NoRoundToFormat/ImGuiSliderFlags_NoRoundToFormat flags to disable rounding underlying value to match precision of the display format string. (#642) +- Drag, Slider: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning + widget into a text input with CTRL+Click or Nav Enter. - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/imgui.h b/imgui.h index feaeb811..d5eb1476 100644 --- a/imgui.h +++ b/imgui.h @@ -1296,8 +1296,9 @@ enum ImGuiDragFlags_ ImGuiDragFlags_None = 0, ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) - ImGuiDragFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiDragFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiDragFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiDragFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget }; // Flags for SliderFloat(), SliderInt() etc. @@ -1306,8 +1307,9 @@ enum ImGuiSliderFlags_ ImGuiSliderFlags_None = 0, ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise) - ImGuiSliderFlags_NoRoundToFormat = 1 << 6 // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. + ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) + ImGuiSliderFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 1f737cc5..6771367c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1498,6 +1498,8 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); ImGui::CheckboxFlags("ImGuiDragFlags_NoRoundToFormat", (unsigned int*)&drag_flags, ImGuiDragFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); + ImGui::CheckboxFlags("ImGuiDragFlags_NoInput", (unsigned int*)&drag_flags, ImGuiDragFlags_NoInput); + ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); static float drag_f = 0.5f; static int drag_i = 50; @@ -1516,6 +1518,8 @@ static void ShowDemoWindowWidgets() ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoInput); + ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); static float slider_f = 0.5f; static int slider_i = 50; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 239c125d..fddb2cb1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2179,10 +2179,11 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Tabbing or CTRL-clicking on Drag turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - bool temp_input_is_active = TempInputIsActive(id); + const bool temp_input_allowed = (flags & ImGuiDragFlags_NoInput) == 0; + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - const bool focus_requested = FocusableItemRegister(window, id); + const bool focus_requested = temp_input_allowed && FocusableItemRegister(window, id); const bool clicked = (hovered && g.IO.MouseClicked[0]); const bool double_clicked = (hovered && g.IO.MouseDoubleClicked[0]); if (focus_requested || clicked || double_clicked || g.NavActivateId == id || g.NavInputId == id) @@ -2191,7 +2192,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, SetFocusID(id, window); FocusWindow(window); g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); - if (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id) + if (temp_input_allowed && (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id)) { temp_input_is_active = true; FocusableItemUnregister(window); @@ -2740,10 +2741,11 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat // Tabbing or CTRL-clicking on Slider turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - bool temp_input_is_active = TempInputIsActive(id); + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; + bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { - const bool focus_requested = FocusableItemRegister(window, id); + const bool focus_requested = temp_input_allowed && FocusableItemRegister(window, id); const bool clicked = (hovered && g.IO.MouseClicked[0]); if (focus_requested || clicked || g.NavActivateId == id || g.NavInputId == id) { @@ -2751,7 +2753,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat SetFocusID(id, window); FocusWindow(window); g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); - if (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id) + if (temp_input_allowed && (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id)) { temp_input_is_active = true; FocusableItemUnregister(window); From fa279a6aa047b6ab01bca55424b44b4046ca1e20 Mon Sep 17 00:00:00 2001 From: Ben Carter Date: Sun, 26 Jul 2020 11:42:06 +0900 Subject: [PATCH 194/959] Drags, Sliders: Added deadzone to make selecting 0.0 on linear sliders easier, slider navigation delta accumulation. (#3361, #1823, #1316, #642) --- imgui.cpp | 1 + imgui.h | 1 + imgui_demo.cpp | 1 + imgui_internal.h | 8 +++-- imgui_widgets.cpp | 74 ++++++++++++++++++++++++++++++++++++----------- 5 files changed, 66 insertions(+), 19 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 197ce1f9..ad676996 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -933,6 +933,7 @@ ImGuiStyle::ImGuiStyle() ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. TabMinWidthForUnselectedCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. diff --git a/imgui.h b/imgui.h index d5eb1476..6fca6f2b 100644 --- a/imgui.h +++ b/imgui.h @@ -1473,6 +1473,7 @@ struct ImGuiStyle float ScrollbarRounding; // Radius of grab corners for scrollbar. float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. float TabMinWidthForUnselectedCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6771367c..22301ed7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3784,6 +3784,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) 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"); + ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f"); ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f"); ImGui::Text("Alignment"); ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); diff --git a/imgui_internal.h b/imgui_internal.h index 95ce67c0..8f7ab0ff 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1280,6 +1280,8 @@ struct ImGuiContext float ColorEditLastSat; // Backup of last Saturation associated to LastColor[3], so we can restore Saturation in lossy RGB<>HSV round trips float ColorEditLastColor[3]; ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker. + float SliderCurrentAccum; // Accumulated slider delta when using navigation controls. + bool SliderCurrentAccumDirty; // Has the accumulated slider delta changed since last time we tried to apply it? bool DragCurrentAccumDirty; float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio @@ -1433,6 +1435,8 @@ struct ImGuiContext ColorEditOptions = ImGuiColorEditFlags__OptionsDefault; ColorEditLastHue = ColorEditLastSat = 0.0f; ColorEditLastColor[0] = ColorEditLastColor[1] = ColorEditLastColor[2] = FLT_MAX; + SliderCurrentAccum = 0.0f; + SliderCurrentAccumDirty = false; DragCurrentAccumDirty = false; DragCurrentAccum = 0.0f; DragSpeedDefaultRatio = 1.0f / 100.0f; @@ -1991,8 +1995,8 @@ namespace ImGui // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiDragFlags flags); template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags); + template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); + template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fddb2cb1..64e3bfca 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2061,6 +2061,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + const float zero_deadzone_size = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. @@ -2068,9 +2069,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, flags); + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); v_old_ref_for_accum_remainder = v_old_parametric; } else @@ -2087,7 +2088,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, flags); + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } else @@ -2420,7 +2421,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; @@ -2456,9 +2457,9 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m if (v == 0.0f) result = zero_point; // Special case for exactly zero else if (v < 0.0f) - result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point; + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * (zero_point - zero_deadzone_size); else - result = zero_point + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point)); + result = zero_point + zero_deadzone_size + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - (zero_point + zero_deadzone_size))); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); @@ -2474,7 +2475,7 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, ImGuiSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; @@ -2510,12 +2511,12 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts { float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space - if (t_with_flip == zero_point) + if ((t_with_flip >= (zero_point - zero_deadzone_size)) && (t_with_flip <= (zero_point + zero_deadzone_size))) result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) else if (t_with_flip < zero_point) - result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point)))); + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / (zero_point - zero_deadzone_size))))); else - result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point) / (1.0f - zero_point)))); + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - (zero_point + zero_deadzone_size)) / (1.0f - (zero_point + zero_deadzone_size))))); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); @@ -2567,14 +2568,16 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ grab_sz = ImMin(grab_sz, slider_sz); const float slider_usable_sz = slider_sz - grab_sz; const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f; - const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; + const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true + float zero_deadzone_size = 0.0f; // Only valid when is_logarithmic is true if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); + zero_deadzone_size = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); } // Process interacting with the slider @@ -2602,13 +2605,15 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ { const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y; - if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + + if (g.ActiveIdIsJustActivated) { - ClearActiveID(); + g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation + g.SliderCurrentAccumDirty = false; } - else if (delta != 0.0f) + + if (delta != 0.0f) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if (decimal_precision > 0) { @@ -2625,17 +2630,52 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } if (IsNavInputDown(ImGuiNavInput_TweakFast)) delta *= 10.0f; + + g.SliderCurrentAccum += delta; + g.SliderCurrentAccumDirty = true; + + delta = g.SliderCurrentAccum; + } + + if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) + { + ClearActiveID(); + } + else if (g.SliderCurrentAccumDirty) + { + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + set_new_value = true; if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits + { set_new_value = false; + g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate + } else + { + float old_clicked_t = clicked_t; + clicked_t = ImSaturate(clicked_t + delta); + + // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) + v_new = RoundScalarWithFormatT(format, data_type, v_new); + float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + + if (delta > 0) + g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); + else + g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta); + } + + g.SliderCurrentAccumDirty = false; } } if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); // Round to user desired precision based on format string if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) @@ -2657,7 +2697,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, flags); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); From fb0f2ebd41b305d0b6f3a4910b30129c1481520b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 Jul 2020 15:15:09 +0200 Subject: [PATCH 195/959] Drags, Sliders: Tweaks. --- docs/CHANGELOG.txt | 4 ++- docs/TODO.txt | 2 +- imgui.cpp | 1 + imgui_widgets.cpp | 81 ++++++++++++++++++++++++---------------------- 4 files changed, 47 insertions(+), 41 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 23959298..9cf625c5 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,7 +59,7 @@ Breaking Changes: to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. See https://github.com/ocornut/imgui/issues/3361 for all details. Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). - For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. + For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. Other Changes: @@ -80,6 +80,8 @@ Other Changes: to disable rounding underlying value to match precision of the display format string. (#642) - Drag, Slider: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning widget into a text input with CTRL+Click or Nav Enter. +- Nav, Slider: Fix using keyboard/gamepad controls with certain logarithmic sliders where + pushing a direction near zero values would be cancelled out. [@Shironekoben] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more diff --git a/docs/TODO.txt b/docs/TODO.txt index c0f01841..1f6f8b94 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -181,7 +181,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - slider: step option (#1183) - slider style: fill % of the bar instead of positioning a drag. - knob: rotating knob widget (#942) - - drag float: power/logarithmic slider and drags are weird. (#1316) + - drag float: support for reversed drags (min > max) (removed is_locked, also see fdc526e) - drag float: up/down axis - drag float: power != 0.0f with current value being outside the range keeps the value stuck. - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) diff --git a/imgui.cpp b/imgui.cpp index ad676996..e29dc6ce 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -973,6 +973,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); + LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor); TabRounding = ImFloor(TabRounding * scale_factor); if (TabMinWidthForUnselectedCloseButton != FLT_MAX) TabMinWidthForUnselectedCloseButton = ImFloor(TabMinWidthForUnselectedCloseButton * scale_factor); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 64e3bfca..d42f4b20 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2060,8 +2060,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_cur = *v; FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; + IM_ASSERT(ImGuiDragFlags_Logarithmic == ImGuiSliderFlags_Logarithmic); + float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true - const float zero_deadzone_size = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) + const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. @@ -2069,9 +2071,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); v_old_ref_for_accum_remainder = v_old_parametric; } else @@ -2088,7 +2090,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } else @@ -2421,7 +2423,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) +float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) { if (v_min == v_max) return 0.0f; @@ -2453,13 +2455,15 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m result = 1.0f; // Workaround for values that are in-range but above our fudge else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions { - float zero_point = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + float zero_point_center = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine) + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; if (v == 0.0f) - result = zero_point; // Special case for exactly zero + result = zero_point_center; // Special case for exactly zero else if (v < 0.0f) - result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * (zero_point - zero_deadzone_size); + result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L; else - result = zero_point + zero_deadzone_size + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - (zero_point + zero_deadzone_size))); + result = zero_point_snap_R + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point_snap_R)); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged)); @@ -2475,7 +2479,7 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m // Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags) +TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) { if (v_min == v_max) return (TYPE)0.0f; @@ -2510,13 +2514,15 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts { - float zero_point = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space - if ((t_with_flip >= (zero_point - zero_deadzone_size)) && (t_with_flip <= (zero_point + zero_deadzone_size))) + float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space + float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize; + float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize; + if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R) result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise) - else if (t_with_flip < zero_point) - result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / (zero_point - zero_deadzone_size))))); + else if (t_with_flip < zero_point_center) + result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L)))); else - result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - (zero_point + zero_deadzone_size)) / (1.0f - (zero_point + zero_deadzone_size))))); + result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point_snap_R) / (1.0f - zero_point_snap_R)))); } else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip))); @@ -2548,7 +2554,7 @@ TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_m return result; } -// FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. +// FIXME: Move more of the code into SliderBehavior() template bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb) { @@ -2568,16 +2574,16 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ grab_sz = ImMin(grab_sz, slider_sz); const float slider_usable_sz = slider_sz - grab_sz; const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f; - const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; + const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f; float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true - float zero_deadzone_size = 0.0f; // Only valid when is_logarithmic is true + float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true if (is_logarithmic) { // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 1; logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); - zero_deadzone_size = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); + zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f); } // Process interacting with the slider @@ -2603,49 +2609,46 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { - const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); - float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y; - if (g.ActiveIdIsJustActivated) { g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation g.SliderCurrentAccumDirty = false; } - if (delta != 0.0f) + const ImVec2 input_delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); + float input_delta = (axis == ImGuiAxis_X) ? input_delta2.x : -input_delta2.y; + if (input_delta != 0.0f) { const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if (decimal_precision > 0) { - delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds + input_delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds if (IsNavInputDown(ImGuiNavInput_TweakSlow)) - delta /= 10.0f; + input_delta /= 10.0f; } else { if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow)) - delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps + input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps else - delta /= 100.0f; + input_delta /= 100.0f; } if (IsNavInputDown(ImGuiNavInput_TweakFast)) - delta *= 10.0f; + input_delta *= 10.0f; - g.SliderCurrentAccum += delta; + g.SliderCurrentAccum += input_delta; g.SliderCurrentAccumDirty = true; - - delta = g.SliderCurrentAccum; } - + + float delta = g.SliderCurrentAccum; if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) { ClearActiveID(); } else if (g.SliderCurrentAccumDirty) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); - set_new_value = true; if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits { set_new_value = false; @@ -2653,15 +2656,15 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else { + set_new_value = true; float old_clicked_t = clicked_t; - clicked_t = ImSaturate(clicked_t + delta); // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) v_new = RoundScalarWithFormatT(format, data_type, v_new); - float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); if (delta > 0) g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); @@ -2675,7 +2678,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); // Round to user desired precision based on format string if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) @@ -2697,7 +2700,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_size, flags); + float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); From 7f8f0096d81d26b942fb40128ae8c1a28597d90d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 Jul 2020 15:34:14 +0200 Subject: [PATCH 196/959] Internals: Renamed SliderCalcRatioFromValueT() -> ScaleRatioFromValueT(), SliderCalcValueFromRatioT() -> ScaleValueFromRatioT(). Replaced drag/slider flags with a single bool is_logarithmic in those functions. --- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 34 ++++++++++++++++------------------ 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 8f7ab0ff..def3c4fb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1993,10 +1993,10 @@ namespace ImGui // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " + template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiDragFlags flags); template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); - template IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); - template IMGUI_API T SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, float logarithmic_zero_epsilon, float zero_deadzone_size, ImGuiSliderFlags flags); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); // Data type helpers diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d42f4b20..b6229890 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2060,8 +2060,6 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_cur = *v; FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; - IM_ASSERT(ImGuiDragFlags_Logarithmic == ImGuiSliderFlags_Logarithmic); - float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense) if (is_logarithmic) @@ -2071,9 +2069,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - float v_old_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float v_old_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = SliderCalcValueFromRatioT(data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + v_cur = ScaleValueFromRatioT(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); v_old_ref_for_accum_remainder = v_old_parametric; } else @@ -2090,7 +2088,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - float v_new_parametric = SliderCalcRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float v_new_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } else @@ -2403,6 +2401,8 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data //------------------------------------------------------------------------- // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. //------------------------------------------------------------------------- +// - ScaleRatioFromValueT<> [Internal] +// - ScaleValueFromRatioT<> [Internal] // - SliderBehaviorT<>() [Internal] // - SliderBehavior() [Internal] // - SliderScalar() @@ -2421,14 +2421,14 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data // - VSliderInt() //------------------------------------------------------------------------- -// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of SliderCalcValueFromRatioT) +// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) template -float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) +float ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) { if (v_min == v_max) return 0.0f; + IM_UNUSED(data_type); - const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_logarithmic) { @@ -2477,15 +2477,13 @@ float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_m return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); } -// Convert a parametric position on a slider into a value v in the output space (the logical opposite of SliderCalcRatioFromValueT) +// Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT) template -TYPE ImGui::SliderCalcValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, float logarithmic_zero_epsilon, float zero_deadzone_halfsize, ImGuiSliderFlags flags) +TYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) { if (v_min == v_max) return (TYPE)0.0f; - const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); - const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); TYPE result; if (is_logarithmic) @@ -2647,8 +2645,8 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (g.SliderCurrentAccumDirty) { - clicked_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); - + clicked_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits { set_new_value = false; @@ -2661,10 +2659,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ clicked_t = ImSaturate(clicked_t + delta); // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) v_new = RoundScalarWithFormatT(format, data_type, v_new); - float new_clicked_t = SliderCalcRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float new_clicked_t = ScaleRatioFromValueT(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (delta > 0) g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); @@ -2678,7 +2676,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new = SliderCalcValueFromRatioT(data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); // Round to user desired precision based on format string if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) @@ -2700,7 +2698,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = SliderCalcRatioFromValueT(data_type, *v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize, flags); + float grab_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); From f32663b33c62187fa12be591f668896e3be5b33e Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 Jul 2020 16:23:38 +0200 Subject: [PATCH 197/959] Drags, Sliders: Removed locking behavior with min > max (added in 1.73) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui_demo.cpp | 2 +- imgui_internal.h | 6 ++++-- imgui_widgets.cpp | 41 ++++++++++++++++++++--------------------- 5 files changed, 28 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9cf625c5..dfe76747 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -60,6 +60,8 @@ Breaking Changes: See https://github.com/ocornut/imgui/issues/3361 for all details. Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. +- DragInt, DragFloat, DragScalar: Obsoleted use of v_min > v_max to lock edits (introduced in 1.73, this was not + demoed nor documented much, will be replaced a more generic ReadOnly feature). Other Changes: diff --git a/imgui.cpp b/imgui.cpp index e29dc6ce..c78ed393 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -380,6 +380,7 @@ CODE - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic flag to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. see https://github.com/ocornut/imgui/issues/3361 for all details. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. + - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiDragFlags_ReadOnly internal flag in the meantime. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 22301ed7..5578601f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1534,7 +1534,7 @@ static void ShowDemoWindowWidgets() { static float begin = 10, end = 90; static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiDragFlags_ClampOnInput); ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); ImGui::TreePop(); diff --git a/imgui_internal.h b/imgui_internal.h index def3c4fb..6d1c1cb6 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -634,13 +634,15 @@ enum ImGuiButtonFlagsPrivate_ // Extend ImGuiDragFlags_ enum ImGuiDragFlagsPrivate_ { - ImGuiDragFlags_Vertical = 1 << 20 // Should this widget be orientated vertically? + ImGuiDragFlags_Vertical = 1 << 20, // Should this widget be orientated vertically? + ImGuiDragFlags_ReadOnly = 1 << 21 }; // Extend ImGuiSliderFlags_ enum ImGuiSliderFlagsPrivate_ { - ImGuiSliderFlags_Vertical = 1 << 20 // Should this slider be orientated vertically? + ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically? + ImGuiSliderFlags_ReadOnly = 1 << 21 }; // Extend ImGuiSelectableFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b6229890..52075823 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2005,9 +2005,6 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; - const bool is_locked = (v_min > v_max); - if (is_locked) - return false; // Default tweak speed if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX)) @@ -2131,7 +2128,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } if (g.ActiveId != id) return false; - if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiDragFlags_ReadOnly)) return false; switch (data_type) @@ -2285,6 +2282,7 @@ bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } +// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); @@ -2296,17 +2294,17 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); - float min = (v_min >= v_max) ? -FLT_MAX : v_min; - float max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min, &max, format, flags); + float min_min = (v_min >= v_max) ? -FLT_MAX : v_min; + float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); - max = (v_min >= v_max) ? FLT_MAX : v_max; - if (min == max) { min = FLT_MAX; max = -FLT_MAX; } // Lock edit - value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &min, &max, format_max ? format_max : format, flags); + float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + float max_max = (v_min >= v_max) ? FLT_MAX : v_max; + ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2337,6 +2335,7 @@ bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } +// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragFlags flags) { ImGuiWindow* window = GetCurrentWindow(); @@ -2348,17 +2347,17 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); - int min = (v_min >= v_max) ? INT_MIN : v_min; - int max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - bool value_changed = DragInt("##min", v_current_min, v_speed, min, max, format, flags); + int min_min = (v_min >= v_max) ? INT_MIN : v_min; + int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); + ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); - min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); - max = (v_min >= v_max) ? INT_MAX : v_max; - if (min == max) { min = INT_MAX; max = INT_MIN; } // Lock edit - value_changed |= DragInt("##max", v_current_max, v_speed, min, max, format_max ? format_max : format, flags); + int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); + int max_max = (v_min >= v_max) ? INT_MAX : v_max; + ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2720,7 +2719,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flag! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; - if (g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) + if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) return false; switch (data_type) From d3fcc37e9eb76f1c82ccfd44f177e559234a553b Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Aug 2020 12:27:40 +0200 Subject: [PATCH 198/959] Update Emscripten readme about local XHR requests (#3412) --- examples/example_emscripten/README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten/README.md index dcb7c1a7..597ffaf7 100644 --- a/examples/example_emscripten/README.md +++ b/examples/example_emscripten/README.md @@ -7,6 +7,13 @@ - Then build using `make` while in the `example_emscripten/` directory. -- Note that Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: +- For local testing, you may need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
+_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ +
Easy local webserver: _"For example, Python has one built in, `python -m http.server` in Python 3 or `python -m SimpleHTTPServer` in Python 2. After doing that, you can visit http://localhost:8000/."_ + +Obsolete features: + +- Emscripten 2.0 (August 2020) obsoleted the fastcomp back-end, only llvm is supported. +- Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: `#EMS += -s BINARYEN_TRAP_MODE=clamp` From 14539b3ed2c0bb207967a7c9a8730c8662ccd521 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 18 Aug 2020 12:34:19 +0200 Subject: [PATCH 199/959] Update Emscripten readme about emrun (#3412) --- examples/example_emscripten/README.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten/README.md index 597ffaf7..42bab014 100644 --- a/examples/example_emscripten/README.md +++ b/examples/example_emscripten/README.md @@ -1,19 +1,20 @@ -# How to Build +## How to Build - You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions - +- You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. - Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools. - - Then build using `make` while in the `example_emscripten/` directory. -- For local testing, you may need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
+## How to Run + +To run on a local machine: +- Generally you may need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ -
Easy local webserver: _"For example, Python has one built in, `python -m http.server` in Python 3 or `python -m SimpleHTTPServer` in Python 2. After doing that, you can visit http://localhost:8000/."_ +- Emscripten SDK has a handy `emrun` command: `emrun example_emscripten.html` which will spawn a temporary local webserver. See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. +- Otherwise you may use Python builtin webserver: `python -m http.server` in Python 3 or `python -m SimpleHTTPServer` in Python 2. After doing that, you can visit http://localhost:8000/. -Obsolete features: +## Obsolete features: - Emscripten 2.0 (August 2020) obsoleted the fastcomp back-end, only llvm is supported. -- Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: - -`#EMS += -s BINARYEN_TRAP_MODE=clamp` +- Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: `#EMS += -s BINARYEN_TRAP_MODE=clamp` From b36d1d465dc25488455a6ab728d322e57b2fed3e Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 11 Aug 2020 11:53:04 +0200 Subject: [PATCH 200/959] Docking: Untangle a little bit of the ActiveIdClickOffset mess. --- imgui.cpp | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 75699181..fdc76f7a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3414,7 +3414,7 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window) SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; g.ActiveIdNoClearOnFocusLoss = true; - g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos; bool can_move_window = true; if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) @@ -3447,15 +3447,9 @@ void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* nod const bool clicked = IsMouseClicked(0); const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f); if (can_undock_node && dragging) - { - DockContextQueueUndockNode(&g, node); - g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; - } + DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window) - { StartMouseMovingWindow(window); - g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos; - } } // Handle mouse moving window @@ -12775,11 +12769,10 @@ static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWind { ImGuiContext& g = *GImGui; IM_ASSERT(node->WantMouseMove == true); - ImVec2 backup_active_click_offset = g.ActiveIdClickOffset; StartMouseMovingWindow(window); + g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. node->WantMouseMove = false; - g.ActiveIdClickOffset = backup_active_click_offset; } // Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. @@ -13296,7 +13289,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w window->DockTabItemRect = host_window->DC.LastItemRect; // Update navigation ID on menu layer - if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << 1)) == 0) + if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0) host_window->NavLastIds[1] = window->ID; } } From c6b01e8e1d12b246925842013a6d30e5024a94fc Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Aug 2020 17:02:58 +0200 Subject: [PATCH 201/959] Drag, Sliders: Merged ImGuiDragFlags back into ImGuiSliderFlags. (#3361, #1823, #1316, #642, #1829, #3209) Technically API breaking (but ImGuiDragFlags were pushed on master 16 hours ago) --- docs/CHANGELOG.txt | 29 ++++++++++--------- imgui.cpp | 4 +-- imgui.h | 56 +++++++++++++++---------------------- imgui_demo.cpp | 53 +++++++++++++++-------------------- imgui_internal.h | 11 ++------ imgui_widgets.cpp | 70 +++++++++++++++++++++++----------------------- 6 files changed, 98 insertions(+), 125 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dfe76747..0520ca9f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,8 +41,7 @@ Breaking Changes: - DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN() - SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN() - VSliderFloat(), VSliderScalar() - Replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). - The type of those flags are ImGuiDragFlags and ImGuiSliderFlags (underlying int storage). + Replaced the 'float power=1.0f' argument with ImGuiSliderFlags flags defaulting to 0 (as with all our flags). Worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. In short, when calling those functions: - If you omitted the 'power' parameter (likely!), you are not affected. @@ -53,10 +52,10 @@ Breaking Changes: - If you set the 'power' parameter to >1.0f (to enable non-linear editing): - Your compiler may warn on float>int conversion. - Code will assert at runtime for IM_ASSERT(power == 1.0f) with the following assert description: - "Call Drag function with ImGuiDragFlags_Logarithmic instead of using the old 'float power' function!". + "Call Drag function with ImGuiSliderFlags_Logarithmic instead of using the old 'float power' function!". - In case asserts are disabled, the code will not crash and enable the _Logarithmic flag. - - You can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic - to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + - You can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert + and get a _similar_ effect as previous uses of power >1.0f. See https://github.com/ocornut/imgui/issues/3361 for all details. Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. @@ -70,18 +69,18 @@ Other Changes: flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. -- Drag, Slider: Added ImGuiDragFlags and ImGuiSliderFlags parameters. +- Drag, Slider: ImGuiSliderFlags parameters. For float functions they replace the old trailing 'float power=1.0' parameter. (See #3361 and the "Breaking Changes" block above for all details). -- Drag, Slider: Added ImGuiDragFlags_Logarithmic/ImGuiSliderFlags_Logarithmic flags to - enable logarithmic editing (generally more precision around zero), as a replacement to the old - 'float power' parameter which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] -- Drag, Slider: Added ImGuiDragFlags_ClampOnInput/ImGuiSliderFlags_ClampOnInput flags to force - clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). -- Drag, Slider: Added ImGuiDragFlags_NoRoundToFormat/ImGuiSliderFlags_NoRoundToFormat flags - to disable rounding underlying value to match precision of the display format string. (#642) -- Drag, Slider: Added ImGuiDragFlags_NoInput/ImGuiSliderFlags_NoInput to disable turning - widget into a text input with CTRL+Click or Nav Enter. +- Drag, Slider: Added ImGuiSliderFlags_Logarithmic flags to enable logarithmic editing + (generally more precision around zero), as a replacement to the old 'float power' parameter + which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] +- Drag, Slider: Added ImGuiSliderFlags_ClampOnInput flags to force clamping value when using + CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). +- Drag, Slider: Added ImGuiSliderFlags_NoRoundToFormat flags to disable rounding underlying + value to match precision of the display format string. (#642) +- Drag, Slider: Added ImGuiSliderFlags_NoInput to disable turning widget into a text input + with CTRL+Click or Nav Enter. - Nav, Slider: Fix using keyboard/gamepad controls with certain logarithmic sliders where pushing a direction near zero values would be cancelled out. [@Shironekoben] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both diff --git a/imgui.cpp b/imgui.cpp index c78ed393..59415898 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -377,10 +377,10 @@ CODE worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: - if you omitted the 'power' parameter (likely!), you are not affected. - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct. - - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiDragFlags_Logarithmic or ImGuiSliderFlags_Logarithmic flag to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. + - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. see https://github.com/ocornut/imgui/issues/3361 for all details. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. - - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiDragFlags_ReadOnly internal flag in the meantime. + - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. diff --git a/imgui.h b/imgui.h index 6fca6f2b..0ddf24cd 100644 --- a/imgui.h +++ b/imgui.h @@ -157,7 +157,6 @@ typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: f typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() -typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragFloat(), DragInt() etc. typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. @@ -165,7 +164,7 @@ typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: f typedef int ImGuiKeyModFlags; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super) typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() -typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderFloat(), SliderInt() etc. +typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() @@ -460,7 +459,7 @@ namespace ImGui IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1); - // Widgets: Drags + // Widgets: Drag Sliders // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. @@ -468,22 +467,23 @@ namespace ImGui // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. - // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiDragFlags flags=0' argument. - // If you get a warning converting a float to ImGuiDragFlags, read https://github.com/ocornut/imgui/issues/3361 - IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); - IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); - IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiDragFlags flags = 0); - IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiDragFlags flags = 0); - IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); // If v_min >= v_max we have no bound - IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); - IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); - IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiDragFlags flags = 0); - IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiDragFlags flags = 0); - IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); - IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiDragFlags flags = 0); - - // Widgets: Sliders + // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. + // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. + // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0); + + // Widgets: Regular Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. // - Format string may also be set to NULL or use the default format ("%f" or "%d"). @@ -1290,26 +1290,16 @@ enum ImGuiColorEditFlags_ #endif }; -// Flags for DragFloat(), DragInt() etc. -enum ImGuiDragFlags_ -{ - ImGuiDragFlags_None = 0, - ImGuiDragFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. - ImGuiDragFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds (if any) when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. - ImGuiDragFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiDragFlags_NoRoundToFormat with this if using a format-string with small amount of digits. - ImGuiDragFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) - ImGuiDragFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget -}; - -// Flags for SliderFloat(), SliderInt() etc. +// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. enum ImGuiSliderFlags_ { ImGuiSliderFlags_None = 0, - ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) - ImGuiSliderFlags_NoInput = 1 << 7 // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget + ImGuiSliderFlags_InvalidMask_ = 0x7000000F // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5578601f..28cef963 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1490,42 +1490,33 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Drag/Slider Flags")) { - // Demonstrate using advanced flags for DragXXX functions - static ImGuiDragFlags drag_flags = ImGuiDragFlags_None; - ImGui::CheckboxFlags("ImGuiDragFlags_ClampOnInput", (unsigned int*)&drag_flags, ImGuiDragFlags_ClampOnInput); + // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! + static ImGuiSliderFlags flags = ImGuiSliderFlags_None; + ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", (unsigned int*)&flags, ImGuiSliderFlags_ClampOnInput); ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); - ImGui::CheckboxFlags("ImGuiDragFlags_Logarithmic", (unsigned int*)&drag_flags, ImGuiDragFlags_Logarithmic); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&flags, ImGuiSliderFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); - ImGui::CheckboxFlags("ImGuiDragFlags_NoRoundToFormat", (unsigned int*)&drag_flags, ImGuiDragFlags_NoRoundToFormat); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&flags, ImGuiSliderFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); - ImGui::CheckboxFlags("ImGuiDragFlags_NoInput", (unsigned int*)&drag_flags, ImGuiDragFlags_NoInput); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&flags, ImGuiSliderFlags_NoInput); ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + // Drags static float drag_f = 0.5f; static int drag_i = 50; ImGui::Text("Underlying float value: %f", drag_f); - ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", drag_flags); - ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", drag_flags); - ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", drag_flags); - ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", drag_flags); - - // Demonstrate using advanced flags for SliderXXX functions - static ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None; - ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_ClampOnInput); - ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); - ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&slider_flags, ImGuiSliderFlags_Logarithmic); - ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoRoundToFormat); - ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&slider_flags, ImGuiSliderFlags_NoInput); - ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); + ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags); + ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags); + ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags); + // Sliders static float slider_f = 0.5f; static int slider_i = 50; ImGui::Text("Underlying float value: %f", slider_f); - ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", slider_flags); - ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", slider_flags); + ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", flags); ImGui::TreePop(); } @@ -1534,7 +1525,7 @@ static void ShowDemoWindowWidgets() { static float begin = 10, end = 90; static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiDragFlags_ClampOnInput); + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_ClampOnInput); ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); ImGui::TreePop(); @@ -1600,9 +1591,9 @@ static void ShowDemoWindowWidgets() ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL); ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL); ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f"); - ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiDragFlags_Logarithmic); + ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic); ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams"); - ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiDragFlags_Logarithmic); + ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic); ImGui::Text("Sliders"); ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d"); @@ -1622,10 +1613,10 @@ static void ShowDemoWindowWidgets() ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms"); ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms"); ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one); - ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic); ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e"); ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams"); - ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiDragFlags_Logarithmic); + ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic); ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); static bool inputs_step = true; @@ -3896,9 +3887,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "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; - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput)) // Scale only this window + if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_ClampOnInput)) // Scale only this window ImGui::SetWindowFontScale(window_scale); - ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiDragFlags_ClampOnInput); // Scale everything + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_ClampOnInput); // Scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); diff --git a/imgui_internal.h b/imgui_internal.h index 6d1c1cb6..c19d5017 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -631,13 +631,6 @@ enum ImGuiButtonFlagsPrivate_ ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease }; -// Extend ImGuiDragFlags_ -enum ImGuiDragFlagsPrivate_ -{ - ImGuiDragFlags_Vertical = 1 << 20, // Should this widget be orientated vertically? - ImGuiDragFlags_ReadOnly = 1 << 21 -}; - // Extend ImGuiSliderFlags_ enum ImGuiSliderFlagsPrivate_ { @@ -1985,7 +1978,7 @@ namespace ImGui // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); - IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags); + IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); IMGUI_API bool SliderBehavior(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); IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f); IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); @@ -1997,7 +1990,7 @@ namespace ImGui // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); - template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiDragFlags flags); + template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags); template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 52075823..3331a66e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1998,13 +1998,13 @@ TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template -bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags) { ImGuiContext& g = *GImGui; - const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; + const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_clamped = (v_min < v_max); - const bool is_logarithmic = (flags & ImGuiDragFlags_Logarithmic) && is_decimal; + const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal; // Default tweak speed if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX)) @@ -2077,7 +2077,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const } // Round to user desired precision based on format string - if (!(flags & ImGuiDragFlags_NoRoundToFormat)) + if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) v_cur = RoundScalarWithFormatT(format, data_type, v_cur); // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. @@ -2113,10 +2113,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const return true; } -bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. - IM_ASSERT((flags == 1 || (flags & ImGuiDragFlags_InvalidMask_) == 0) && "Invalid ImGuiDragFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiDragFlags_Logarithmic flags instead."); + IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead."); ImGuiContext& g = *GImGui; if (g.ActiveId == id) @@ -2128,7 +2128,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v } if (g.ActiveId != id) return false; - if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiDragFlags_ReadOnly)) + if ((g.CurrentWindow->DC.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly)) return false; switch (data_type) @@ -2151,7 +2151,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional. // Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. -bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2177,7 +2177,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, // Tabbing or CTRL-clicking on Drag turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - const bool temp_input_allowed = (flags & ImGuiDragFlags_NoInput) == 0; + const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0; bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id); if (!temp_input_is_active) { @@ -2200,8 +2200,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (temp_input_is_active) { - // Only clamp CTRL+Click input when ImGuiDragFlags_ClampInput is set - const bool is_clamp_input = (flags & ImGuiDragFlags_ClampOnInput) != 0; + // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } @@ -2227,7 +2227,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, return value_changed; } -bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2262,28 +2262,28 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data return value_changed; } -bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } -// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. -bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiDragFlags flags) +// NB: You likely want to specify the ImGuiSliderFlags_ClampOnInput when using this. +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2296,14 +2296,14 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu float min_min = (v_min >= v_max) ? -FLT_MAX : v_min; float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); float max_max = (v_min >= v_max) ? FLT_MAX : v_max; - ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2315,28 +2315,28 @@ bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_cu } // NB: v_speed is float to allow adjusting the drag speed with more precision -bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags); } -bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiDragFlags flags) +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags) { return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } -// NB: You likely want to specify the ImGuiDragFlags_ClampOnInput when using this. -bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiDragFlags flags) +// NB: You likely want to specify the ImGuiSliderFlags_ClampOnInput when using this. +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) @@ -2349,14 +2349,14 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ int min_min = (v_min >= v_max) ? INT_MIN : v_min; int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max); - ImGuiDragFlags min_flags = flags | ((min_min == min_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0); bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min); int max_max = (v_min >= v_max) ? INT_MAX : v_max; - ImGuiDragFlags max_flags = flags | ((max_min == max_max) ? ImGuiDragFlags_ReadOnly : 0); + ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0); value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); @@ -2373,24 +2373,24 @@ bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_ // Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details. bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None; if (power != 1.0f) { - IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds - drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + drag_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths } return DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, drag_flags); } bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power) { - ImGuiDragFlags drag_flags = ImGuiDragFlags_None; + ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None; if (power != 1.0f) { - IM_ASSERT(power == 1.0f && "Call function with ImGuiDragFlags_Logarithmic flags instead of using the old 'float power' function!"); + IM_ASSERT(power == 1.0f && "Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!"); IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds - drag_flags |= ImGuiDragFlags_Logarithmic; // Fallback for non-asserting paths + drag_flags |= ImGuiSliderFlags_Logarithmic; // Fallback for non-asserting paths } return DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, drag_flags); } @@ -3133,7 +3133,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* } // Note that Drag/Slider functions are only forwarding the min/max values clamping values if the -// ImGuiDragFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! +// ImGuiSliderFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) From 95c99aaa4be611716093edcb6b01146ab9483f30 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Aug 2020 17:50:45 +0200 Subject: [PATCH 202/959] Version 1.78 --- docs/CHANGELOG.txt | 38 +++++++++++------------ examples/README.txt | 2 +- examples/example_win32_directx10/main.cpp | 1 + examples/example_win32_directx11/main.cpp | 1 + examples/example_win32_directx12/main.cpp | 1 + examples/example_win32_directx9/main.cpp | 1 + imgui.cpp | 2 +- imgui.h | 6 ++-- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 12 files changed, 32 insertions(+), 28 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0520ca9f..89fdbdad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -32,7 +32,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.78 WIP (In Progress) + VERSION 1.78 (Released 2020-08-18) ----------------------------------------------------------------------- Breaking Changes: @@ -41,13 +41,13 @@ Breaking Changes: - DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN() - SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN() - VSliderFloat(), VSliderScalar() - Replaced the 'float power=1.0f' argument with ImGuiSliderFlags flags defaulting to 0 (as with all our flags). + Replaced the final 'float power=1.0f' argument with ImGuiSliderFlags defaulting to 0 (as with all our flags). Worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. In short, when calling those functions: - If you omitted the 'power' parameter (likely!), you are not affected. - If you set the 'power' parameter to 1.0f (same as previous default value): - Your compiler may warn on float>int conversion. - - Everything else will work. + - Everything else will work (but will assert if IMGUI_DISABLE_OBSOLETE_FUNCTIONS is defined). - You can replace the 1.0f value with 0 to fix the warning, and be technically correct. - If you set the 'power' parameter to >1.0f (to enable non-linear editing): - Your compiler may warn on float>int conversion. @@ -69,25 +69,25 @@ Other Changes: flag being cleared accordingly. (bug introduced in 1.77 WIP on 2020/06/16) (#3344, #2880) - Window: Fixed clicking over an item which hovering has been disabled (e.g inhibited by a popup) from marking the window as moved. -- Drag, Slider: ImGuiSliderFlags parameters. - For float functions they replace the old trailing 'float power=1.0' parameter. - (See #3361 and the "Breaking Changes" block above for all details). -- Drag, Slider: Added ImGuiSliderFlags_Logarithmic flags to enable logarithmic editing - (generally more precision around zero), as a replacement to the old 'float power' parameter - which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] -- Drag, Slider: Added ImGuiSliderFlags_ClampOnInput flags to force clamping value when using - CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). -- Drag, Slider: Added ImGuiSliderFlags_NoRoundToFormat flags to disable rounding underlying - value to match precision of the display format string. (#642) -- Drag, Slider: Added ImGuiSliderFlags_NoInput to disable turning widget into a text input - with CTRL+Click or Nav Enter. +- Drag, Slider: Added ImGuiSliderFlags parameters. + - For float functions they replace the old trailing 'float power=1.0' parameter. + (See #3361 and the "Breaking Changes" block above for all details). + - Added ImGuiSliderFlags_Logarithmic flag to enable logarithmic editing + (generally more precision around zero), as a replacement to the old 'float power' parameter + which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] + - Added ImGuiSliderFlags_ClampOnInput flag to force clamping value when using + CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). + - Added ImGuiSliderFlags_NoRoundToFormat flag to disable rounding underlying + value to match precision of the display format string. (#642) + - Added ImGuiSliderFlags_NoInput flag to disable turning widget into a text input + with CTRL+Click or Nav Enter. - Nav, Slider: Fix using keyboard/gamepad controls with certain logarithmic sliders where pushing a direction near zero values would be cancelled out. [@Shironekoben] - DragFloatRange2, DragIntRange2: Fixed an issue allowing to drag out of bounds when both min and max value are on the same value. (#1441) - InputText, ImDrawList: Fixed assert triggering when drawing single line of text with more than ~16 KB characters. (Note that current code is going to show corrupted display if after - clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText + clipping, more than 16 KB characters are visible in the same low-level ImDrawList::RenderText() call. ImGui-level functions such as TextUnformatted() are not affected. This is quite rare but it will be addressed later). (#3349) - Selectable: Fixed highlight/hit extent when used with horizontal scrolling (in or outside columns). @@ -109,15 +109,15 @@ Other Changes: path, reducing the amount of vertices/indices and CPU/GPU usage. (#3245) [@Shironekoben] - This change will facilitate the wider use of thick borders in future style changes. - Requires an extra bit of texture space (~64x64 by default), relies on GPU bilinear filtering. - - Clear io.AntiAliasedLinesUseTex = false; to disable rendering using this method. - - Clear ImFontAtlasFlags_NoBakedLines in ImFontAtlas::Flags to disable baking data in texture. + - Set `io.AntiAliasedLinesUseTex = false` to disable rendering using this method. + - Clear `ImFontAtlasFlags_NoBakedLines` in ImFontAtlas::Flags to disable baking data in texture. - ImDrawList: changed AddCircle(), AddCircleFilled() default num_segments from 12 to 0, effectively enabling auto-tessellation by default. Tweak tessellation in Style Editor->Rendering section, or by modifying the 'style.CircleSegmentMaxError' value. [@ShironekoBen] - ImDrawList: Fixed minor bug introduced in 1.75 where AddCircle() with 12 segments would generate an extra vertex. (This bug was mistakenly marked as fixed in earlier 1.77 release). [@ShironekoBen] - Demo: Improved "Custom Rendering"->"Canvas" demo with a grid, scrolling and context menu. - Also showcase using InvisibleButton() will multiple mouse buttons flags. + Also showcase using InvisibleButton() with multiple mouse buttons flags. - Demo: Improved "Layout & Scrolling" -> "Clipping" section. - Demo: Improved "Layout & Scrolling" -> "Child Windows" section. - Style Editor: Added preview of circle auto-tessellation when editing the corresponding value. diff --git a/examples/README.txt b/examples/README.txt index 8c89ef00..9f0977ae 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.78 WIP + dear imgui, v1.78 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index f6b8b215..2e83e826 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -26,6 +26,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; ::RegisterClassEx(&wc); HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX10 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 2cc36a7f..310dc04a 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -26,6 +26,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; ::RegisterClassEx(&wc); HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 6ea896bc..4a263916 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -57,6 +57,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; ::RegisterClassEx(&wc); HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index c8ad69f1..57a61c0d 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -24,6 +24,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int main(int, char**) { // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; ::RegisterClassEx(&wc); HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); diff --git a/imgui.cpp b/imgui.cpp index 59415898..d0840e24 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 0ddf24cd..83576022 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (headers) // Help: @@ -59,8 +59,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.78 WIP" -#define IMGUI_VERSION_NUM 17704 +#define IMGUI_VERSION "1.78" +#define IMGUI_VERSION_NUM 17800 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 28cef963..77a7d870 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 39209287..487cdbd0 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index c19d5017..22ce4634 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3331a66e..1a10a2e8 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 WIP +// dear imgui, v1.78 // (widgets code) /* From 5dc5610ad5ea9dae696ff51a6af310752c3207f7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 19 Aug 2020 13:25:56 +0200 Subject: [PATCH 203/959] Docs: TODO, FAQ --- docs/CHANGELOG.txt | 7 +++++++ docs/FAQ.md | 4 ++-- docs/TODO.txt | 18 +++++++++++++++--- imgui.cpp | 2 +- imgui.h | 2 +- 5 files changed, 26 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 89fdbdad..40d65885 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -31,6 +31,13 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.79 WIP (In Progress) +----------------------------------------------------------------------- + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.78 (Released 2020-08-18) ----------------------------------------------------------------------- diff --git a/docs/FAQ.md b/docs/FAQ.md index b5fbcc90..2745b122 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -23,7 +23,7 @@ or view this file with any Markdown viewer. | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries..](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | **Q&A: Usage** | -| **[How can I have widgets with an empty label?
How can I have multiple widgets with the same label?
Why are multiple widgets reacting when I interact with one?](#q-how-can-i-have-widgets-with-an-empty-label)** | +| **[Why is my widget not reacting when I click on it?
How can I have multiple widgets with the same label?
Why are multiple widgets reacting when I interact with one?](#q-why-is-my-widget-not-reacting-when-i-click-on-it)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| | [How can I use my own math types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-math-types-instead-of-imvec2imvec4) | | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | @@ -173,9 +173,9 @@ Refer to rendering back-ends in the [examples/](https://github.com/ocornut/imgui # Q&A: Usage +### Q: Why is my widget not reacting when I click on it? ### Q: How can I have widgets with an empty label? ### Q: How can I have multiple widgets with the same label? -### Q: Why are multiple widgets reacting when I interact with one? A primer on labels and the ID Stack... diff --git a/docs/TODO.txt b/docs/TODO.txt index 1f6f8b94..ca026df0 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -27,6 +27,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window: investigate better auto-positioning for new windows. - window: top most window flag? (#2574) - window/size: manually triggered auto-fit (double-click on grip) shouldn't resize window down to viewport size? + - window/size: how to allow to e.g. auto-size vertically to fit contents, but be horizontally resizable? Assuming SetNextWindowSize() is modified to treat -1.0f on each axis as "keep as-is" (would be good but might break erroneous code): Problem is UpdateWindowManualResize() and lots of code treat (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) together. - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - window/child: background options for child windows, border option (disable rounding). - window/child: allow resizing of child windows (possibly given min/max for each axis?.) @@ -35,6 +36,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - window/child: allow SetNextWindowContentSize() to work on child windows. - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - window/tabbing: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). + - window/id_stack: add e.g. window->GetIDFromPath() with support for leading / and ../ (#1390, #331) ! scrolling: exposing horizontal scrolling with Shift+Wheel even when scrollbar is disabled expose lots of issues (#2424, #1463) - scrolling: while holding down a scrollbar, try to keep the same contents visible (at least while not moving mouse) - scrolling: allow immediately effective change of scroll after Begin() if we haven't appended items yet. @@ -54,6 +56,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - drawlist: callback: add an extra void* in ImDrawCallback to allow passing render-local data to the callback (would break API). - drawlist: AddRect vs AddLine position confusing (#2441) - drawlist: channel splitter should be external helper and not stored in ImDrawList. + - drawlist: Add quadratic bezier curves? (#3127) - drawlist/opt: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. (#1962) - drawlist/opt: AddRect() axis aligned pixel aligned (no-aa) could use 8 triangles instead of 16 and no normal calculation. - drawlist/opt: thick AA line could be doable in same number of triangles as 1.0 AA line by storing gradient+full color in atlas. @@ -78,6 +81,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. + - input text: preserve scrolling when unfocused? - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) - input text: expose CursorPos in char filter event (#816) - input text: try usage idiom of using InputText with data only exposed through get/set accessors, without extraneous copy/alloc. (#3009) @@ -134,7 +138,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - columns: allow a same columns set to be interrupted by e.g. CollapsingHeader and resume with columns in sync when moving them. - columns: sizing is lossy when columns width is very small (default width may turn negative etc.) - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) - - columns: flag to add horizontal separator above/below? + - columns: flag to add horizontal separator above/below) - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) !- color: the color conversion helpers/types are a mess and needs sorting out. @@ -155,12 +159,16 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - clipper: horizontal clipping support. (#2580) - separator: expose flags (#759) + - separator: take indent into consideration (optional) - separator: width, thickness, centering (#1643) - splitter: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - dock: merge docking branch (#2109) - dock: dock out from a collapsing header? would work nicely but need emitting window to keep submitting the code. + - tabs: "there is currently a problem because TabItem() will try to submit their own tooltip after 0.50 second, and this will have the effect of making your tooltip flicker once." -> tooltip priority work + - tabs: close button tends to overlap unsaved-document star + - tabs: consider showing the star at the same spot as the close button, like VS Code does. - tabs: while dragging/reordering a tab, close button decoration shouldn't appear on other tabs - tabs: make EndTabBar fail if users doesn't respect BeginTabBar return value, for consistency/future-proofing. - tabs: persistent order/focus in BeginTabBar() api (#261, #351) @@ -179,7 +187,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) - slider: relative dragging? + precision dragging - slider: step option (#1183) - - slider style: fill % of the bar instead of positioning a drag. + - slider: style: fill % of the bar instead of positioning a drag. - knob: rotating knob widget (#942) - drag float: support for reversed drags (min > max) (removed is_locked, also see fdc526e) - drag float: up/down axis @@ -232,13 +240,15 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) - tree node: tweak color scheme to distinguish headers from selected tree node (#581) - tree node: leaf/non-leaf highlight mismatch. - - tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height?) + - tree node: flag to disable formatting and/or detect "%s" + - tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height? format only %s/%c to be able to count height?) - settings: write more decent code to allow saving/loading new fields: columns, selected tree nodes? - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file (#437) - settings/persistence: helpers to make TreeNodeBehavior persist (even during dev!) - may need to store some semantic and/or data type in ImGuiStoragePair - style: better default styles. (#707) + - style: PushStyleVar: allow direct access to individual float X/Y elements. - style: add a highlighted text color (for headers, etc.) - style: border types: out-screen, in-screen, etc. (#447) - style: add window shadow (fading away from the window. Paint-style calculation of vertices alpha after drawlist would be easier) @@ -285,6 +295,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - text: it's currently impossible to have a window title with "##". perhaps an official workaround would be nice. \ style inhibitor? non-visible ascii code to insert between #? - text: provided a framed text helper, e.g. https://pastebin.com/1Laxy8bT - text: refactor TextUnformatted (or underlying function) to more explicitly request if we need width measurement or not + - text/layout/tabs: \t pulling position from base pos + step, or offset array (e.g. could be used in text edit, menus for simple icon+text alignment, etc.) - text link/url button: underlined. should api expose an ID or use text contents as ID? which colors enum to use? - text/wrapped: should be a more first-class citizen, e.g. wrapped text within a Selectable with known width. - text/wrapped: custom separator for text wrapping. (#3002) @@ -383,6 +394,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: window minimize, maximize (#583) - examples: provide a zero frame-rate/idle example. - examples: dx11/dx12: try to use new swapchain blit models (#2970) + - backends: move to backends/ folder? - backends: report it better when not able to create texture? - backends: apple: example_apple should be using modern GL3. - backends: glfw: could go idle when minimized? if (glfwGetWindowAttrib(window, GLFW_ICONIFIED)) { glfwWaitEvents(); continue; } // issue: DeltaTime will be super high on resume, perhaps provide a way to let impl know (#440) diff --git a/imgui.cpp b/imgui.cpp index d0840e24..bb620003 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -657,9 +657,9 @@ CODE Q&A: Usage ---------- + Q: Why is my widget not reacting when I click on it? Q: How can I have widgets with an empty label? Q: How can I have multiple widgets with the same label? - Q: Why are multiple widgets reacting when I interact with one? Q: How can I display an image? What is ImTextureID, how does it works? Q: How can I use my own math types instead of ImVec2/ImVec4? Q: How can I interact with standard C++ types (such as std::string and std::vector)? diff --git a/imgui.h b/imgui.h index 83576022..d661ccfe 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.78" -#define IMGUI_VERSION_NUM 17800 +#define IMGUI_VERSION_NUM 17801 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) From 4c201994d421089493a7a996978e8239ad619a20 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 11:21:15 +0200 Subject: [PATCH 204/959] DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) --- docs/CHANGELOG.txt | 3 ++ examples/example_win32_directx11/main.cpp | 5 ++ imgui_internal.h | 3 +- imgui_widgets.cpp | 58 +++++++++++++++++------ 4 files changed, 53 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 40d65885..83ac4df7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,9 @@ HOW TO UPDATE? Other Changes: +- DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case + where v_min == v_max. (#3361) + ----------------------------------------------------------------------- VERSION 1.78 (Released 2020-08-18) diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 310dc04a..d4920106 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -116,6 +116,11 @@ int main(int, char**) ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + + static float f2 = 0.0f; + ImGui::DragFloat("f2 limit", &f2, 1.0f, 0.0f, 100.0f, NULL, ImGuiSliderFlags_ClampOnInput); + ImGui::DragFloat("f2", &f2, 1.0f, 0.0f, 0.0f, NULL, ImGuiSliderFlags_ClampOnInput); + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) diff --git a/imgui_internal.h b/imgui_internal.h index 22ce4634..1e4384d0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1997,8 +1997,9 @@ namespace ImGui // Data type helpers IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format); - IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); + IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg_1, const void* arg_2); IMGUI_API bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* p_data, const char* format); + IMGUI_API int DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2); IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); // InputText diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1a10a2e8..188bb882 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1758,7 +1758,7 @@ int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type return 0; } -void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2) +void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2) { IM_ASSERT(op == '+' || op == '-'); switch (data_type) @@ -1910,11 +1910,39 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b } template -static bool ClampBehaviorT(T* v, const T* v_min, const T* v_max) +static int DataTypeCompareT(const T* lhs, const T* rhs) { - // Clamp, both sides are optional + if (*lhs < *rhs) return -1; + if (*lhs > *rhs) return +1; + return 0; +} + +int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2) +{ + switch (data_type) + { + case ImGuiDataType_S8: return DataTypeCompareT((const ImS8* )arg_1, (const ImS8* )arg_2); + case ImGuiDataType_U8: return DataTypeCompareT((const ImU8* )arg_1, (const ImU8* )arg_2); + case ImGuiDataType_S16: return DataTypeCompareT((const ImS16* )arg_1, (const ImS16* )arg_2); + case ImGuiDataType_U16: return DataTypeCompareT((const ImU16* )arg_1, (const ImU16* )arg_2); + case ImGuiDataType_S32: return DataTypeCompareT((const ImS32* )arg_1, (const ImS32* )arg_2); + case ImGuiDataType_U32: return DataTypeCompareT((const ImU32* )arg_1, (const ImU32* )arg_2); + case ImGuiDataType_S64: return DataTypeCompareT((const ImS64* )arg_1, (const ImS64* )arg_2); + case ImGuiDataType_U64: return DataTypeCompareT((const ImU64* )arg_1, (const ImU64* )arg_2); + case ImGuiDataType_Float: return DataTypeCompareT((const float* )arg_1, (const float* )arg_2); + case ImGuiDataType_Double: return DataTypeCompareT((const double*)arg_1, (const double*)arg_2); + case ImGuiDataType_COUNT: break; + } + IM_ASSERT(0); + return 0; +} + +template +static bool DataTypeClampT(T* v, const T* v_min, const T* v_max) +{ + // Clamp, both sides are optional, return true if modified if (v_min && *v < *v_min) { *v = *v_min; return true; } - if (v_max && *v > *v_max) { *v = *v_max; return true; } + if (v_max && *v > * v_max) { *v = *v_max; return true; } return false; } @@ -1922,16 +1950,16 @@ bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_m { switch (data_type) { - case ImGuiDataType_S8: return ClampBehaviorT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); - case ImGuiDataType_U8: return ClampBehaviorT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); - case ImGuiDataType_S16: return ClampBehaviorT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); - case ImGuiDataType_U16: return ClampBehaviorT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); - case ImGuiDataType_S32: return ClampBehaviorT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); - case ImGuiDataType_U32: return ClampBehaviorT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); - case ImGuiDataType_S64: return ClampBehaviorT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); - case ImGuiDataType_U64: return ClampBehaviorT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); - case ImGuiDataType_Float: return ClampBehaviorT((float* )p_data, (const float* )p_min, (const float* )p_max); - case ImGuiDataType_Double: return ClampBehaviorT((double*)p_data, (const double*)p_min, (const double*)p_max); + case ImGuiDataType_S8: return DataTypeClampT((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max); + case ImGuiDataType_U8: return DataTypeClampT((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max); + case ImGuiDataType_S16: return DataTypeClampT((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max); + case ImGuiDataType_U16: return DataTypeClampT((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max); + case ImGuiDataType_S32: return DataTypeClampT((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max); + case ImGuiDataType_U32: return DataTypeClampT((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max); + case ImGuiDataType_S64: return DataTypeClampT((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max); + case ImGuiDataType_U64: return DataTypeClampT((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max); + case ImGuiDataType_Float: return DataTypeClampT((float* )p_data, (const float* )p_min, (const float* )p_max); + case ImGuiDataType_Double: return DataTypeClampT((double*)p_data, (const double*)p_min, (const double*)p_max); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); @@ -2201,7 +2229,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (temp_input_is_active) { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set - const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; + const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } From 024993adf96f34dd9a176d594d2079242b68b94a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 11:25:05 +0200 Subject: [PATCH 205/959] Revert leftovers from 4c201994d421089493a7a996978e8239ad619a20 --- examples/example_win32_directx11/main.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index d4920106..310dc04a 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -116,11 +116,6 @@ int main(int, char**) ImGui::Checkbox("Another Window", &show_another_window); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - - static float f2 = 0.0f; - ImGui::DragFloat("f2 limit", &f2, 1.0f, 0.0f, 100.0f, NULL, ImGuiSliderFlags_ClampOnInput); - ImGui::DragFloat("f2", &f2, 1.0f, 0.0f, 0.0f, NULL, ImGuiSliderFlags_ClampOnInput); - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) From fc9ccad6b96de70219a644395b6a2bd069e61656 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 11:25:39 +0200 Subject: [PATCH 206/959] InputText: Add ImGuiInputTextFlags_CallbackEdit, selection helpers in ImGuiInputTextCallbackData(). Add simple InputText() callbacks demo. --- docs/CHANGELOG.txt | 5 ++++ imgui.h | 8 ++++-- imgui_demo.cpp | 61 +++++++++++++++++++++++++++++++++++++++++++++- imgui_internal.h | 1 + imgui_widgets.cpp | 11 ++++++++- 5 files changed, 82 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 83ac4df7..5479abb6 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,8 +37,13 @@ HOW TO UPDATE? Other Changes: +- InputText: Added selection helpers in ImGuiInputTextCallbackData(). +- InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. + (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the + underlying buffer while focus is active). - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) +- Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). ----------------------------------------------------------------------- diff --git a/imgui.h b/imgui.h index d661ccfe..07058278 100644 --- a/imgui.h +++ b/imgui.h @@ -854,6 +854,7 @@ enum ImGuiInputTextFlags_ ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input) ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) + ImGuiInputTextFlags_CallbackEdit = 1 << 19, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) // [Internal] ImGuiInputTextFlags_Multiline = 1 << 20, // For internal use by InputTextMultiline() ImGuiInputTextFlags_NoMarkEdited = 1 << 21 // For internal use by functions using InputText() before reformatting data @@ -1634,9 +1635,10 @@ struct ImGuiIO // Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. // The callback function should return 0 by default. // Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) +// - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) +// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration // - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB // - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows -// - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration // - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. // - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. struct ImGuiInputTextCallbackData @@ -1663,7 +1665,9 @@ struct ImGuiInputTextCallbackData IMGUI_API ImGuiInputTextCallbackData(); IMGUI_API void DeleteChars(int pos, int bytes_count); IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); - bool HasSelection() const { return SelectionStart != SelectionEnd; } + void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; } + void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; } + bool HasSelection() const { return SelectionStart != SelectionEnd; } }; // Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 77a7d870..f9d1a9eb 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1177,8 +1177,11 @@ static void ShowDemoWindowWidgets() static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + ImGui::TreePop(); + } - ImGui::Text("Password input"); + if (ImGui::TreeNode("Password Input")) + { static char password[64] = "password123"; ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password); ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); @@ -1187,6 +1190,62 @@ static void ShowDemoWindowWidgets() ImGui::TreePop(); } + if (ImGui::TreeNode("Completion, History, Edit Callbacks")) + { + struct Funcs + { + static int MyCallback(ImGuiInputTextCallbackData* data) + { + if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion) + { + data->InsertChars(data->CursorPos, ".."); + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory) + { + if (data->EventKey == ImGuiKey_UpArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Up!"); + data->SelectAll(); + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + data->DeleteChars(0, data->BufTextLen); + data->InsertChars(0, "Pressed Down!"); + data->SelectAll(); + } + } + else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit) + { + // Toggle casing of first character + char c = data->Buf[0]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32; + data->BufDirty = true; + + // Increment a counter + int* p_int = (int*)data->UserData; + *p_int = *p_int + 1; + } + return 0; + } + }; + static char buf1[64]; + ImGui::InputText("Completion", buf1, 64, 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::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::SameLine(); HelpMarker("Here we toggle the casing of the first character on every edits + count edits."); + ImGui::SameLine(); ImGui::Text("(%d)", edit_count); + + ImGui::TreePop(); + } + if (ImGui::TreeNode("Resize Callback")) { // To wire InputText() with std::string or any other custom string type, diff --git a/imgui_internal.h b/imgui_internal.h index 1e4384d0..58224444 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -858,6 +858,7 @@ struct IMGUI_API ImGuiInputTextState float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection + bool Edited; // edited this frame ImGuiInputTextFlags UserFlags; // Temporarily set while we call user's callback ImGuiInputTextCallback UserCallback; // " void* UserCallbackData; // " diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 188bb882..eee4d0f3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3514,6 +3514,7 @@ static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) ImWchar* dst = obj->TextW.Data + pos; // We maintain our buffer length in both UTF-8 and wchar formats + obj->Edited = true; obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; @@ -3548,6 +3549,7 @@ static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const Im memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + obj->Edited = true; obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; obj->TextW[obj->CurLenW] = '\0'; @@ -3946,6 +3948,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { IM_ASSERT(state != NULL); backup_current_text_length = state->CurLenA; + state->Edited = false; state->BufCapacityA = buf_size; state->UserFlags = flags; state->UserCallback = callback; @@ -4183,7 +4186,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } // User callback - if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0) { IM_ASSERT(callback != NULL); @@ -4205,8 +4208,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } + else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited) + { + event_flag = ImGuiInputTextFlags_CallbackEdit; + } else if (flags & ImGuiInputTextFlags_CallbackAlways) + { event_flag = ImGuiInputTextFlags_CallbackAlways; + } if (event_flag) { From 05a25e5f36a0735592efbfc7b4930db4f79d5443 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 16:19:53 +0200 Subject: [PATCH 207/959] BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5479abb6..2126be29 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,8 @@ Other Changes: underlying buffer while focus is active). - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) +- BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), + so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eee4d0f3..03ff7e10 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6416,7 +6416,8 @@ bool ImGui::BeginMenuBar() clip_rect.ClipWith(window->OuterRectClipped); PushClipRect(clip_rect.Min, clip_rect.Max, false); - window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); + // We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analoguous here, maybe a BeginGroupEx() with flags). + window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); window->DC.LayoutType = ImGuiLayoutType_Horizontal; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); From 9262609eafd915931afa9012cd393a63da53c0e7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 12:19:39 +0200 Subject: [PATCH 208/959] Version 1.79 WIP --- examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/README.txt b/examples/README.txt index 9f0977ae..e2577edb 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.78 + dear imgui, v1.79 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index bb620003..eea7bd81 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 07058278..8f76e93a 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (headers) // Help: @@ -59,8 +59,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.78" -#define IMGUI_VERSION_NUM 17801 +#define IMGUI_VERSION "1.79 WIP" +#define IMGUI_VERSION_NUM 17802 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f9d1a9eb..625bf1aa 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 487cdbd0..bb300e00 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 58224444..999641ae 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 03ff7e10..3d2bfe40 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.78 +// dear imgui, v1.79 WIP // (widgets code) /* From 97dad665166e23473d2be0b6390cc2bab099040e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 16:49:11 +0200 Subject: [PATCH 209/959] Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 48 +++++++++++++++++++++++++++++++++------------- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2126be29..28d1139f 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,7 @@ Other Changes: where v_min == v_max. (#3361) - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. +- Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). diff --git a/imgui.cpp b/imgui.cpp index eea7bd81..797d0a08 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10413,7 +10413,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) { if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) return; - for (int i = 0; i < windows.Size; i++) + ImGui::Text("(In front-to-back order:)"); + for (int i = windows.Size - 1; i >= 0; i--) // Iterate front to back { ImGui::PushID(windows[i]); Funcs::NodeWindow(windows[i], "Window"); @@ -10429,14 +10430,18 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::BulletText("%s: NULL", label); return; } - bool open = ImGui::TreeNode(label, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window); - if (ImGui::IsItemHovered() && window->WasActive) - ImGui::GetForegroundDrawList()->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + + ImGuiContext& g = *GImGui; + const bool is_active = window->WasActive; + ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + const bool open = ImGui::TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*"); + if (!is_active) { PopStyleColor(); } + if (ImGui::IsItemHovered() && is_active) + ImGui::GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!open) return; - if (!window->WasActive) - ImGui::TextDisabled("Note: window is not currently visible."); if (window->MemoryCompacted) ImGui::TextDisabled("Note: some memory buffers have been compacted/freed."); @@ -10481,9 +10486,13 @@ void ImGui::ShowMetricsWindow(bool* p_open) char buf[256]; char* p = buf; const char* buf_end = buf + IM_ARRAYSIZE(buf); - p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : ""); + const bool is_active = (tab_bar->PrevFrameVisible >= ImGui::GetFrameCount() - 2); + p += ImFormatString(p, buf_end - p, "Tab Bar 0x%08X (%d tabs)%s", tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); IM_UNUSED(p); - if (ImGui::TreeNode(tab_bar, "%s", buf)) + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = ImGui::TreeNode(tab_bar, "%s", buf); + if (!is_active) { PopStyleColor(); } + if (open) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { @@ -10635,8 +10644,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { - char* buf = (char*)(void*)(g.SettingsIniData.Buf.Data ? g.SettingsIniData.Buf.Data : ""); - ImGui::InputTextMultiline("##Ini", buf, g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly); + ImGui::InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly); ImGui::TreePop(); } ImGui::TreePop(); @@ -10646,21 +10654,35 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); + + ImGui::Text("WINDOWING"); + ImGui::Indent(); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); - ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + ImGui::Unindent(); + + ImGui::Text("ITEMS"); + ImGui::Indent(); ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); - ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + ImGui::Unindent(); + + ImGui::Text("NAV,FOCUS"); + ImGui::Indent(); ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]); ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); + ImGui::Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId); ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); - ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + ImGui::Unindent(); + ImGui::TreePop(); } From 9b50e691edcc6469685965c1eb928c436dbc4808 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 22:26:10 +0200 Subject: [PATCH 210/959] TreeNode: Made clicking on arrow toggle toggle the open state on the Mouse Down event. Amend 05420ea2c. --- docs/CHANGELOG.txt | 4 ++++ imgui.h | 2 +- imgui_widgets.cpp | 11 ++++------- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 28d1139f..3f2a0474 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,6 +45,10 @@ Other Changes: where v_min == v_max. (#3361) - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. +- TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event + rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior + and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. + (This is also necessary to support full multi/range-select/drag and drop operations.) - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). diff --git a/imgui.h b/imgui.h index 8f76e93a..65a1e304 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.79 WIP" -#define IMGUI_VERSION_NUM 17802 +#define IMGUI_VERSION_NUM 17803 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3d2bfe40..3f929f32 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5644,17 +5644,14 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. - // - Single-click on label = Toggle on MouseUp (default) - // - Single-click on arrow = Toggle on MouseUp (when _OpenOnArrow=0) + // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) + // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0) // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1) // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1) // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0) - // This makes _OpenOnArrow have a subtle effect on _OpenOnDoubleClick: arrow click reacts on Down rather than Up. - // It is rather standard that arrow click react on Down rather than Up and we'd be tempted to make it the default - // (by removing the _OpenOnArrow test below), however this would have a perhaps surprising effect on CollapsingHeader()? - // So right now we are making this optional. May evolve later. + // It is rather standard that arrow click react on Down rather than Up. // We set ImGuiButtonFlags_PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work. - if (is_mouse_x_over_arrow && (flags & ImGuiTreeNodeFlags_OpenOnArrow)) + if (is_mouse_x_over_arrow) button_flags |= ImGuiButtonFlags_PressedOnClick; else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; From 9d20a5f0a515dba3ade46cfcf90953133e34dcbc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 20 Aug 2020 16:21:48 +0200 Subject: [PATCH 211/959] Docking: DockSpace() emits ItemSize() properly + dockspace demo (works now since 05a25e5f3) --- imgui.cpp | 2 ++ imgui_demo.cpp | 33 +++++++++++++++++++++------------ 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 51699b0c..5babd781 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14183,6 +14183,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla char title[256]; ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id); + // FIXME-DOCK: What is the reason for not simply calling BeginChild()? if (node->Windows.Size > 0 || node->IsSplitNode()) PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0)); PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f); @@ -14213,6 +14214,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla g.WithinEndChild = true; End(); + ItemSize(size); g.WithinEndChild = false; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2d6bc7a8..45553465 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -5303,8 +5303,8 @@ static void ShowExampleAppCustomRendering(bool* p_open) // DockSpace() is only useful to construct to a central location for your application. void ShowExampleAppDockSpace(bool* p_open) { - static bool opt_fullscreen_persistant = true; - bool opt_fullscreen = opt_fullscreen_persistant; + static bool opt_fullscreen = true; + static bool opt_padding = false; static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, @@ -5321,6 +5321,10 @@ void ShowExampleAppDockSpace(bool* p_open) window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } + else + { + dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; + } // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background // and handle the pass-thru hole, so we ask Begin() to not render a background. @@ -5332,9 +5336,11 @@ void ShowExampleAppDockSpace(bool* p_open) // all active windows docked into it will lose their parent and become undocked. // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + if (!opt_padding) + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", p_open, window_flags); - ImGui::PopStyleVar(); + if (!opt_padding) + ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); @@ -5353,19 +5359,22 @@ void ShowExampleAppDockSpace(bool* p_open) if (ImGui::BeginMenuBar()) { - if (ImGui::BeginMenu("Docking")) + if (ImGui::BeginMenu("Options")) { // Disabling fullscreen would allow the window to be moved to the front of other windows, // which we can't undo at the moment without finer window depth/z control. - //ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen_persistant); + ImGui::MenuItem("Fullscreen", NULL, &opt_fullscreen); + ImGui::MenuItem("Padding", NULL, &opt_padding); + ImGui::Separator(); - if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; - if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoResize; - if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; - if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; - if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; + if (ImGui::MenuItem("Flag: NoSplit", "", (dockspace_flags & ImGuiDockNodeFlags_NoSplit) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoSplit; } + if (ImGui::MenuItem("Flag: NoResize", "", (dockspace_flags & ImGuiDockNodeFlags_NoResize) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoResize; } + if (ImGui::MenuItem("Flag: NoDockingInCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_NoDockingInCentralNode; } + if (ImGui::MenuItem("Flag: AutoHideTabBar", "", (dockspace_flags & ImGuiDockNodeFlags_AutoHideTabBar) != 0)) { dockspace_flags ^= ImGuiDockNodeFlags_AutoHideTabBar; } + if (ImGui::MenuItem("Flag: PassthruCentralNode", "", (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0, opt_fullscreen)) { dockspace_flags ^= ImGuiDockNodeFlags_PassthruCentralNode; } ImGui::Separator(); - if (ImGui::MenuItem("Close DockSpace", NULL, false, p_open != NULL)) + + if (ImGui::MenuItem("Close", NULL, false, p_open != NULL)) *p_open = false; ImGui::EndMenu(); } From d6f3a8848d005e00748b8e8f9a93ba84620160a3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 15:02:52 +0200 Subject: [PATCH 212/959] Viewports: Backends: DirectX9: Allow D3DERR_DEVICELOST on secondary viewports. (#3424) --- examples/imgui_impl_dx9.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index 6d726af8..f8abc61a 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -408,7 +408,8 @@ static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*) { ImGuiViewportDataDx9* data = (ImGuiViewportDataDx9*)viewport->RendererUserData; HRESULT hr = data->SwapChain->Present(NULL, NULL, data->d3dpp.hDeviceWindow, NULL, NULL); - IM_ASSERT(hr == D3D_OK); + // Let main application handle D3DERR_DEVICELOST by resetting the device. + IM_ASSERT(hr == D3D_OK || hr == D3DERR_DEVICELOST); } static void ImGui_ImplDX9_InitPlatformInterface() From df89a16d265c3f02f403afefc0e60b5d227d94fb Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 7 Aug 2020 15:34:25 +0200 Subject: [PATCH 213/959] Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) --- docs/CHANGELOG.txt | 1 + examples/example_glfw_vulkan/main.cpp | 18 ++++++++---------- examples/example_sdl_vulkan/main.cpp | 19 ++++++++----------- 3 files changed, 17 insertions(+), 21 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3f2a0474..a25f469c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,7 @@ Other Changes: (This is also necessary to support full multi/range-select/drag and drop operations.) - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). +- Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] ----------------------------------------------------------------------- diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 58d0ab7f..8e75abbf 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -310,7 +310,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) } } -static void FramePresent(ImGui_ImplVulkanH_Window* wd) +static void FramePresent(ImGui_ImplVulkanH_Window* wd, GLFWwindow* window) { VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; @@ -321,6 +321,12 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); + if (err == VK_ERROR_OUT_OF_DATE_KHR) + { + glfwGetFramebufferSize(window, &g_SwapChainResizeWidth, &g_SwapChainResizeHeight); + g_SwapChainRebuild = true; + return; + } check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } @@ -330,13 +336,6 @@ static void glfw_error_callback(int error, const char* description) fprintf(stderr, "Glfw Error %d: %s\n", error, description); } -static void glfw_resize_callback(GLFWwindow*, int w, int h) -{ - g_SwapChainRebuild = true; - g_SwapChainResizeWidth = w; - g_SwapChainResizeHeight = h; -} - int main(int, char**) { // Setup GLFW window @@ -365,7 +364,6 @@ int main(int, char**) // Create Framebuffers int w, h; glfwGetFramebufferSize(window, &w, &h); - glfwSetFramebufferSizeCallback(window, glfw_resize_callback); ImGui_ImplVulkanH_Window* wd = &g_MainWindowData; SetupVulkanWindow(wd, surface, w, h); @@ -515,7 +513,7 @@ int main(int, char**) { memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); - FramePresent(wd); + FramePresent(wd, window); } } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 6de7afab..c0a98088 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -302,7 +302,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) } } -static void FramePresent(ImGui_ImplVulkanH_Window* wd) +static void FramePresent(ImGui_ImplVulkanH_Window* wd, SDL_Window* window) { VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; @@ -313,6 +313,12 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) info.pSwapchains = &wd->Swapchain; info.pImageIndices = &wd->FrameIndex; VkResult err = vkQueuePresentKHR(g_Queue, &info); + if (err == VK_ERROR_OUT_OF_DATE_KHR) + { + SDL_GetWindowSize(window, &g_SwapChainResizeWidth, &g_SwapChainResizeHeight); + g_SwapChainRebuild = true; + return; + } check_vk_result(err); wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores } @@ -445,15 +451,6 @@ int main(int, char**) ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; - if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED && event.window.windowID == SDL_GetWindowID(window)) - { - // Note: your own application may rely on SDL_WINDOWEVENT_MINIMIZED/SDL_WINDOWEVENT_RESTORED to skip updating all-together. - // Here ImGui_ImplSDL2_NewFrame() will set io.DisplaySize to zero which will disable rendering but let application run. - // Please note that you can't Present into a minimized window. - g_SwapChainResizeWidth = (int)event.window.data1; - g_SwapChainResizeHeight = (int)event.window.data2; - g_SwapChainRebuild = true; - } } // Resize swap chain? @@ -515,7 +512,7 @@ int main(int, char**) { memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); - FramePresent(wd); + FramePresent(wd, window); } } From cf312545e87146000bd96a1827d94a97ca7b17a0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 16:21:51 +0200 Subject: [PATCH 214/959] Docking: Fixed docking while hovering a child window. (#3420) broken by 85a661d27. Improve metrics debugging. --- imgui.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 5babd781..ac94fc2e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11912,10 +11912,10 @@ void ImGui::DockContextUpdateDocking(ImGuiContext* ctx) g.HoveredDockNode = NULL; if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow) { - if (hovered_window->DockNode) - g.HoveredDockNode = hovered_window->DockNode; - else if (hovered_window->DockNodeAsHost) + if (hovered_window->DockNodeAsHost) g.HoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); + else if (hovered_window->RootWindowDockStop->DockNode) + g.HoveredDockNode = hovered_window->RootWindowDockStop->DockNode; } // Process Docking requests @@ -14872,6 +14872,7 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); if (!g.DragDropActive) return; + //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!BeginDragDropTargetCustom(window->Rect(), window->ID)) return; @@ -15662,11 +15663,17 @@ void ImGui::ShowMetricsWindow(bool* p_open) static void NodeDockNode(ImGuiDockNode* node, const char* label) { ImGuiContext& g = *GImGui; + const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly + const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted + if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } bool open; if (node->Windows.Size > 0) open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); else open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); + if (!is_alive) { PopStyleColor(); } + if (is_active && ImGui::IsItemHovered()) + GetForegroundDrawList(node->HostWindow ? node->HostWindow : node->VisibleWindow)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); if (open) { IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); @@ -15679,8 +15686,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::BulletText("Misc:%s%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", - (g.FrameCount - node->LastFrameAlive < 2) ? " IsAlive" : "", - (g.FrameCount - node->LastFrameActive < 2) ? " IsActive" : "", + is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->WantLockSizeOnce ? " WantLockSizeOnce" : ""); if (ImGui::TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) { @@ -15854,7 +15860,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } ImGui::SameLine(); if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } - ImGui::Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (!root_nodes_only || node->IsRootNode()) @@ -15946,6 +15951,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); + ImGui::Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); ImGui::Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); ImGui::Unindent(); From 831e2c920edf62b1254587418a4f1968de3dc37e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 18:44:56 +0200 Subject: [PATCH 215/959] Docking, Viewport: Fixed a rare edge-case if the window targetted by CTRL+Tab stops being rendered. --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index ac94fc2e..110b73d2 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4386,9 +4386,10 @@ static void ImGui::EndFrameDrawDimmedBackgrounds() } // Draw modal whitening background between CTRL-TAB list - if (dim_bg_for_window_list) + if (dim_bg_for_window_list && g.NavWindowingTargetAnim->Active) { // Choose a draw list that will be front-most across all our children + // In the unlikely case that the window wasn't made active we can't rely on its drawlist and skip rendering all-together. ImGuiWindow* window = g.NavWindowingTargetAnim; ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindow)->DrawList; draw_list->PushClipRectFullScreen(); From fdf952108dd92897fabcba59b834a2ce9241b4ed Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 19:16:59 +0200 Subject: [PATCH 216/959] Drags, Sliders: internal ReadOnly flag gets forwarded properly to temp InputText(). --- imgui_internal.h | 2 +- imgui_widgets.cpp | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 999641ae..ec5bde09 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2006,7 +2006,7 @@ namespace ImGui // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL, ImGuiInputTextFlags flags = 0); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3f929f32..a0810a18 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2230,7 +2230,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); } // Draw frame @@ -2833,7 +2834,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); + const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); } // Draw frame @@ -3164,7 +3166,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* // ImGuiSliderFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. -bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max, ImGuiInputTextFlags flags) { ImGuiContext& g = *GImGui; @@ -3174,8 +3176,9 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format); ImStrTrimBlanks(data_buf); - ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; + flags |= ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); + bool value_changed = false; if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) { From 7b0570d6bac96ed64d379d240907f8fee319d57b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 21 Aug 2020 20:15:07 +0200 Subject: [PATCH 217/959] Revert "Drags, Sliders: internal ReadOnly flag gets forwarded properly to temp InputText()." This reverts commit 640d1f60ce140e4c2bf858ac2f2e8a96d432e6a4. --- imgui_internal.h | 2 +- imgui_widgets.cpp | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ec5bde09..999641ae 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2006,7 +2006,7 @@ namespace ImGui // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); - IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL, ImGuiInputTextFlags flags = 0); + IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a0810a18..3f929f32 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2230,8 +2230,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); - const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } // Draw frame @@ -2834,8 +2833,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat { // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; - const bool is_readonly = (flags & ImGuiSliderFlags_ReadOnly) != 0 && (window->DC.ItemFlags & ImGuiItemFlags_ReadOnly) != 0; - return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL, is_readonly ? ImGuiInputTextFlags_ReadOnly : 0); + return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } // Draw frame @@ -3166,7 +3164,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* // ImGuiSliderFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. -bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max, ImGuiInputTextFlags flags) +bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) { ImGuiContext& g = *GImGui; @@ -3176,9 +3174,8 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format); ImStrTrimBlanks(data_buf); - flags |= ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; + ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); - bool value_changed = false; if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags)) { From d451f6cc30d83e1dcb49c10ffe57b4f881b30de4 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 24 Aug 2020 14:13:18 +0200 Subject: [PATCH 218/959] Nav tweaks. Demo: Fixed drag and drop demo state (broken by f152fac4f1). Fixed incorrect format string (which would work without IMGUI_DISABLE_OBSOLETE_FUNCTIONS). --- imgui.cpp | 15 ++++++++++----- imgui_demo.cpp | 4 ++-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 797d0a08..53864293 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3622,16 +3622,17 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. // - 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; FindHoveredWindow(); // Modal windows prevents mouse from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) - g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; + clear_hovered_windows = true; // Disabled mouse? if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) - g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; + clear_hovered_windows = true; // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward. int mouse_earliest_button_down = -1; @@ -3651,6 +3652,9 @@ void ImGui::UpdateHoveredWindowAndCaptureFlags() // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) + clear_hovered_windows = true; + + if (clear_hovered_windows) g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app) @@ -9116,10 +9120,11 @@ static void ImGui::NavUpdateWindowing() if (move_delta.x != 0.0f || move_delta.y != 0.0f) { const float NAV_MOVE_SPEED = 800.0f; - const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well - SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always); + const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well + ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow; + SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always); + MarkIniSettingsDirty(moving_window); g.NavDisableMouseHover = true; - MarkIniSettingsDirty(g.NavWindowingTarget); } } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 625bf1aa..efb83a4d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1575,7 +1575,7 @@ static void ShowDemoWindowWidgets() static int slider_i = 50; ImGui::Text("Underlying float value: %f", slider_f); ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags); - ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%.3f", flags); + ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags); ImGui::TreePop(); } @@ -1820,7 +1820,7 @@ static void ShowDemoWindowWidgets() if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } - const char* names[9] = + static const char* names[9] = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", From 2e50d0706bf18ee2fe21cf8eb7dc680f64a6fea0 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 24 Aug 2020 16:26:47 +0200 Subject: [PATCH 219/959] Selectable: Tweaks. Added internal ImGuiSelectableFlags_NoPadWithHalfSpacing. --- imgui_internal.h | 13 +++++++------ imgui_widgets.cpp | 47 +++++++++++++++++++++++++---------------------- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 999641ae..b4083d2b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -642,12 +642,13 @@ enum ImGuiSliderFlagsPrivate_ enum ImGuiSelectableFlagsPrivate_ { // NB: need to be in sync with last value of ImGuiSelectableFlags_ - ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, - ImGuiSelectableFlags_SelectOnClick = 1 << 21, // Override button behavior to react on Click (default is Click+Release) - ImGuiSelectableFlags_SelectOnRelease = 1 << 22, // Override button behavior to react on Release (default is Click+Release) - ImGuiSelectableFlags_SpanAvailWidth = 1 << 23, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) - ImGuiSelectableFlags_DrawHoveredWhenHeld= 1 << 24, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. - ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25 + ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, + ImGuiSelectableFlags_SelectOnClick = 1 << 21, // Override button behavior to react on Click (default is Click+Release) + ImGuiSelectableFlags_SelectOnRelease = 1 << 22, // Override button behavior to react on Release (default is Click+Release) + ImGuiSelectableFlags_SpanAvailWidth = 1 << 23, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) + ImGuiSelectableFlags_DrawHoveredWhenHeld = 1 << 24, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow. + ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25, // Set Nav/Focus ID on mouse hover (used by MenuItem) + ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26 // Disable padding each side with ItemSpacing * 0.5f }; // Extend ImGuiTreeNodeFlags_ diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3f929f32..2ae40d98 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5889,7 +5889,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped. + const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0; + if (span_all_columns && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped. PushColumnsBackground(); // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. @@ -5901,8 +5902,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ItemSize(size, 0.0f); // Fill horizontal space - const float min_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Min.x : pos.x; - const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; + const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x; + const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) size.x = ImMax(label_size.x, max_x - min_x); @@ -5911,33 +5912,35 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const ImVec2 text_max(min_x + size.x, pos.y + size.y); // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable. - ImRect bb_enlarged(min_x, pos.y, text_max.x, text_max.y); - const float spacing_x = style.ItemSpacing.x; - const float spacing_y = style.ItemSpacing.y; - const float spacing_L = IM_FLOOR(spacing_x * 0.50f); - const float spacing_U = IM_FLOOR(spacing_y * 0.50f); - bb_enlarged.Min.x -= spacing_L; - bb_enlarged.Min.y -= spacing_U; - bb_enlarged.Max.x += (spacing_x - spacing_L); - bb_enlarged.Max.y += (spacing_y - spacing_U); - //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb_align.Min, bb_align.Max, IM_COL32(255, 0, 0, 255)); } - //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb_enlarged.Min, bb_enlarged.Max, IM_COL32(0, 255, 0, 255)); } + ImRect bb(min_x, pos.y, text_max.x, text_max.y); + if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0) + { + const float spacing_x = style.ItemSpacing.x; + const float spacing_y = style.ItemSpacing.y; + const float spacing_L = IM_FLOOR(spacing_x * 0.50f); + const float spacing_U = IM_FLOOR(spacing_y * 0.50f); + bb.Min.x -= spacing_L; + bb.Min.y -= spacing_U; + bb.Max.x += (spacing_x - spacing_L); + bb.Max.y += (spacing_y - spacing_U); + } + //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); } bool item_add; if (flags & ImGuiSelectableFlags_Disabled) { ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus; - item_add = ItemAdd(bb_enlarged, id); + item_add = ItemAdd(bb, id); window->DC.ItemFlags = backup_item_flags; } else { - item_add = ItemAdd(bb_enlarged, id); + item_add = ItemAdd(bb, id); } if (!item_add) { - if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) + if (span_all_columns && window->DC.CurrentColumns) PopColumnsBackground(); return false; } @@ -5956,7 +5959,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const bool was_selected = selected; bool hovered, held; - bool pressed = ButtonBehavior(bb_enlarged, id, &hovered, &held, button_flags); + bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover))) @@ -5983,15 +5986,15 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (hovered || selected) { const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); - RenderFrame(bb_enlarged.Min, bb_enlarged.Max, col, false, 0.0f); - RenderNavHighlight(bb_enlarged, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); + RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); } - if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) + if (span_all_columns && window->DC.CurrentColumns) PopColumnsBackground(); if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); - RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb_enlarged); + RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); // Automatically close popups From 08108cf9ee352b9e868d3d7b59ece88b4d4a6d90 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Aug 2020 11:49:16 +0200 Subject: [PATCH 220/959] Tab Bar: Hide tab item close button while dragging a tab. --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 1 - imgui_widgets.cpp | 5 +++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a25f469c..5092f144 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,6 +49,7 @@ Other Changes: rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) +- Tab Bar: Hide tab item close button while dragging a tab. - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] diff --git a/docs/TODO.txt b/docs/TODO.txt index ca026df0..e1b1f3e3 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -169,7 +169,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tabs: "there is currently a problem because TabItem() will try to submit their own tooltip after 0.50 second, and this will have the effect of making your tooltip flicker once." -> tooltip priority work - tabs: close button tends to overlap unsaved-document star - tabs: consider showing the star at the same spot as the close button, like VS Code does. - - tabs: while dragging/reordering a tab, close button decoration shouldn't appear on other tabs - tabs: make EndTabBar fail if users doesn't respect BeginTabBar return value, for consistency/future-proofing. - tabs: persistent order/focus in BeginTabBar() api (#261, #351) - tabs: TabItem could honor SetNextItemWidth()? diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ae40d98..6dd2eff1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7453,7 +7453,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, SetItemAllowOverlap(); // Drag and drop: re-order tabs - if (held && !tab_appearing && IsMouseDragging(0)) + const bool is_dragging = (held && !tab_appearing && IsMouseDragging(0)); + if (is_dragging) { if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) { @@ -7496,7 +7497,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; // Render tab label, process close button - const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; + const ImGuiID close_button_id = (p_open && !is_dragging) ? window->GetID((void*)((intptr_t)id + 1)) : 0; bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); if (just_closed && p_open != NULL) { From 021c28ae39594b0d6dc78ab8581f35cb8776012c Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Tue, 25 Aug 2020 13:13:03 +0300 Subject: [PATCH 221/959] Nav: Fix ScrollToBringRectIntoView() not bringing entire item into view when nav moves to the left. Correct some comments. --- imgui.cpp | 2 +- imgui_internal.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 53864293..bd25ed1c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7392,7 +7392,7 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_ if (!window_rect.Contains(item_rect)) { if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) - SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x + g.Style.ItemSpacing.x, 0.0f); + SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x - g.Style.ItemSpacing.x, 0.0f); else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f); if (item_rect.Min.y < window_rect.Min.y) diff --git a/imgui_internal.h b/imgui_internal.h index b4083d2b..2cb5dfa3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1191,11 +1191,11 @@ struct ImGuiContext ImGuiKeyModFlags NavJustMovedToKeyMods; ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard. - ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring. + ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring. int NavScoringCount; // Metrics for debugging ImGuiNavLayer NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later. int NavIdTabCounter; // == NavWindow->DC.FocusIdxTabCounter at time of NavId processing - bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRefRectRel is valid + bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel is valid bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default) bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover) bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again. From 30f0900b1c5c840b817f73d0dadd1511e21f224c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Aug 2020 19:03:08 +0200 Subject: [PATCH 222/959] Docking: Fix honoring payload filter with overlapping nodes. (we incorrectly over-relied on g.HoveredDockNode when making change for #3398) Essentially undo part of 85a661d (#3398) + ref cf31254 (#3420) --- imgui.cpp | 28 ++++++++++++++++++---------- imgui_internal.h | 2 +- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 110b73d2..15749d3a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -14890,18 +14890,26 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { // Select target node - // (we should not assume that g.HoveredDockNode is != NULL when window is a host dock node: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos) - ImGuiDockNode* node = g.HoveredDockNode; - const bool allow_null_target_node = window->DockNode == NULL && window->DockNodeAsHost == NULL; + // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) + bool dock_into_floating_window = false; + ImGuiDockNode* node = NULL; + if (window->DockNodeAsHost) + { + // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). + node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); - // There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active) - // In this case we need to fallback into any leaf mode, possibly the central node. - if (window->DockNodeAsHost && node && node->IsDockSpace() && node->IsRootNode()) + // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) + // In this case we need to fallback into any leaf mode, possibly the central node. + // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. + if (node && node->IsDockSpace() && node->IsRootNode()) + node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node); + } + else { - if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. - node = node->CentralNode; + if (window->DockNode) + node = window->DockNode; else - node = DockNodeTreeFindFallbackLeafNode(node); + dock_into_floating_window = true; // Dock into a regular window } const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); @@ -14910,7 +14918,7 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) // Preview docking request and find out split direction/ratio //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. const bool do_preview = payload->IsPreview() || payload->IsDelivery(); - if (do_preview && (node != NULL || allow_null_target_node)) + if (do_preview && (node != NULL || dock_into_floating_window)) { ImGuiDockPreviewData split_inner; ImGuiDockPreviewData split_outer; diff --git a/imgui_internal.h b/imgui_internal.h index 0105add4..5ccf0581 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1296,7 +1296,7 @@ struct ImGuiContext ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. ImGuiWindow* HoveredRootWindow; // == HoveredWindow ? HoveredWindow->RootWindow : NULL, merely a shortcut to avoid null test in some situation. ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. - ImGuiDockNode* HoveredDockNode; + ImGuiDockNode* HoveredDockNode; // Hovered dock node. ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; From 5919a6fa89e077e0b94f93036a2cef690790b06b Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Aug 2020 19:28:20 +0200 Subject: [PATCH 223/959] Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). Improve 08108cf --- docs/CHANGELOG.txt | 2 +- imgui_widgets.cpp | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5092f144..573b813a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -49,7 +49,7 @@ Other Changes: rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) -- Tab Bar: Hide tab item close button while dragging a tab. +- Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6dd2eff1..2ee4c191 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7453,8 +7453,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, SetItemAllowOverlap(); // Drag and drop: re-order tabs - const bool is_dragging = (held && !tab_appearing && IsMouseDragging(0)); - if (is_dragging) + if (held && !tab_appearing && IsMouseDragging(0)) { if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) { @@ -7497,7 +7496,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; // Render tab label, process close button - const ImGuiID close_button_id = (p_open && !is_dragging) ? window->GetID((void*)((intptr_t)id + 1)) : 0; + const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); if (just_closed && p_open != NULL) { @@ -7609,7 +7608,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, bool close_button_visible = false; if (close_button_id != 0) if (is_contents_visible || bb.GetWidth() >= g.Style.TabMinWidthForUnselectedCloseButton) - if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id) + if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id) close_button_visible = true; if (close_button_visible) { From 32be6c064b9036341fd36e7c34a11f2dc4104f6c Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 25 Aug 2020 20:08:24 +0200 Subject: [PATCH 224/959] InputText: Fixed using ImGuiInputTextFlags_Password with InputTextMultiline(). (#3427, #3428) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 573b813a..156a54c2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -41,6 +41,8 @@ Other Changes: - InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active). +- InputText: Fixed using ImGuiInputTextFlags_Password with InputTextMultiline(). (#3427, #3428) + It is a rather unusual or useless combination of features but no reason it shouldn't work! - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ee4c191..59fa0918 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4505,6 +4505,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ } } + if (is_password && !is_displaying_hint) + PopFont(); + if (is_multiline) { Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line @@ -4512,9 +4515,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ EndGroup(); } - if (is_password && !is_displaying_hint) - PopFont(); - // Log as text if (g.LogEnabled && (!is_password || is_displaying_hint)) LogRenderedText(&draw_pos, buf_display, buf_display_end); From 4448734041bfff23c86dbc68dac88e69df112536 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Aug 2020 11:03:55 +0200 Subject: [PATCH 225/959] ImVector: added max_size() to facilitate usage with sol2 binding generator (#3429) --- imgui.h | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui.h b/imgui.h index 65a1e304..27ef591d 100644 --- a/imgui.h +++ b/imgui.h @@ -1395,6 +1395,7 @@ struct ImVector inline bool empty() const { return Size == 0; } inline int size() const { return Size; } inline int size_in_bytes() const { return Size * (int)sizeof(T); } + inline int max_size() const { return (~(unsigned int)0) / (int)sizeof(T); } inline int capacity() const { return Capacity; } inline T& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } inline const T& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } From 1e8b9f84da30bda10e7a6b09341d10d77313f037 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Aug 2020 11:28:35 +0200 Subject: [PATCH 226/959] Nav: Removed stateful NavMoveFromClampedRefRect and made it more explicit that nav move request from gamepad start from a clipped location. --- imgui.cpp | 14 ++++---------- imgui_internal.h | 2 -- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index bd25ed1c..c1d044c8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8746,15 +8746,9 @@ static void ImGui::NavUpdate() // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f); if (scroll_dir.x != 0.0f && window->ScrollbarX) - { SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); - g.NavMoveFromClampedRefRect = true; - } if (scroll_dir.y != 0.0f) - { SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); - g.NavMoveFromClampedRefRect = true; - } } // Reset search results @@ -8762,8 +8756,10 @@ static void ImGui::NavUpdate() g.NavMoveResultLocalVisibleSet.Clear(); g.NavMoveResultOther.Clear(); - // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items - if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == ImGuiNavLayer_Main) + // When using gamepad, we project the reference nav bounding box into window visible area. + // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative + // (can't focus a visible object like we can with the mouse). + if (g.NavMoveRequest && g.NavInputSource == ImGuiInputSource_NavGamepad && g.NavLayer == ImGuiNavLayer_Main) { ImGuiWindow* window = g.NavWindow; ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1)); @@ -8774,7 +8770,6 @@ static void ImGui::NavUpdate() window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel); g.NavId = g.NavFocusScopeId = 0; } - g.NavMoveFromClampedRefRect = false; } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) @@ -8856,7 +8851,6 @@ static void ImGui::NavUpdateMoveResult() g.NavJustMovedToKeyMods = g.NavMoveRequestKeyMods; } SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel); - g.NavMoveFromClampedRefRect = false; } // Handle PageUp/PageDown/Home/End keys diff --git a/imgui_internal.h b/imgui_internal.h index 2cb5dfa3..6bf49337 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1204,7 +1204,6 @@ struct ImGuiContext bool NavInitRequestFromMove; ImGuiID NavInitResultId; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) ImRect NavInitResultRectRel; // Init request result rectangle (relative to parent window) - bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items bool NavMoveRequest; // Move request for this frame ImGuiNavMoveFlags NavMoveRequestFlags; ImGuiNavForward NavMoveRequestForward; // None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu) @@ -1390,7 +1389,6 @@ struct ImGuiContext NavInitRequest = false; NavInitRequestFromMove = false; NavInitResultId = 0; - NavMoveFromClampedRefRect = false; NavMoveRequest = false; NavMoveRequestFlags = ImGuiNavMoveFlags_None; NavMoveRequestForward = ImGuiNavForward_None; From 833eb771f24c29bf3bf1788a57bd16ead7bb9d42 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 26 Aug 2020 12:21:37 +0300 Subject: [PATCH 227/959] Nav: Fix navigation resuming on first visible item when using gamepad. In cases where navigation was requested with focused item out of view, clipping of current item rect resulted in an inverted rect, which was completely discarded and ImRect(0,0,0,0) was used as current point from which navigation scoring was calculated. IsInverted() check is completely removed as rect can no longer be inverted. Since rects are not initialized to ImRect(0,0,0,0) - old .Min.x != FLT_MAX check (which was changed in c7835dd1892ab11750cd6917b37b74e426fe13b9) is not necessary either. --- docs/CHANGELOG.txt | 7 ++++--- imgui.cpp | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 156a54c2..61600a6c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -45,11 +45,12 @@ Other Changes: It is a rather unusual or useless combination of features but no reason it shouldn't work! - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) +- Nav: Fix navigation resuming on first visible item when using gamepad. [@rokups] - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. -- TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event - rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior - and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. +- TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event + rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior + and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) - Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. diff --git a/imgui.cpp b/imgui.cpp index c1d044c8..f7f49479 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8767,13 +8767,13 @@ static void ImGui::NavUpdate() { float pad = window->CalcFontSize() * 0.5f; window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item - window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel); + window->NavRectRel[g.NavLayer].ClipWithFull(window_rect_rel); g.NavId = g.NavFocusScopeId = 0; } } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) - ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); + ImRect nav_rect_rel = g.NavWindow ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0); g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y); g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x); From 8d71bc2132b71bb3e564efa12d3829a91e00453f Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Aug 2020 12:39:29 +0200 Subject: [PATCH 228/959] Internals: Nav: shallow refactor. --- imgui.cpp | 62 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f7f49479..9baba2e9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8515,7 +8515,9 @@ ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInput static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; - g.IO.WantSetMousePos = false; + ImGuiIO& io = g.IO; + + io.WantSetMousePos = false; g.NavWrapRequestWindow = NULL; g.NavWrapRequestFlags = ImGuiNavMoveFlags_None; #if 0 @@ -8524,16 +8526,16 @@ static void ImGui::NavUpdate() // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard) // (do it before we map Keyboard input!) - bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; - bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; if (nav_gamepad_active) - if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f) + if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f) g.NavInputSource = ImGuiInputSource_NavGamepad; // Update Keyboard->Nav inputs mapping if (nav_keyboard_active) { - #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0) + #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(io.KeyMap[_KEY])) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0) NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate ); NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input ); NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel ); @@ -8541,17 +8543,17 @@ static void ImGui::NavUpdate() NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_); NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ ); NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ ); - if (g.IO.KeyCtrl) - g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; - if (g.IO.KeyShift) - g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; - if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu. - g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; + if (io.KeyCtrl) + io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; + if (io.KeyShift) + io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; + if (io.KeyAlt && !io.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu. + io.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; #undef NAV_MAP_KEY } - memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration)); - for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++) - g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f; + memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) + io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f; // Process navigation init request (select first/default focus) // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) @@ -8587,12 +8589,12 @@ static void ImGui::NavUpdate() if (g.NavMousePosDirty && g.NavIdIsAlive) { // Set mouse position given our knowledge of the navigated item position from last frame - if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) { if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow) { - g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos(); - g.IO.WantSetMousePos = true; + io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos(); + io.WantSetMousePos = true; } } g.NavMousePosDirty = false; @@ -8611,8 +8613,8 @@ static void ImGui::NavUpdate() NavUpdateWindowing(); // Set output flags for user application - g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); - g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL); + io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); + io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL); // Process NavCancel input (to close a popup, get back to parent, clear focus) if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed)) @@ -8715,7 +8717,7 @@ static void ImGui::NavUpdate() if (g.NavMoveDir != ImGuiDir_None) { g.NavMoveRequest = true; - g.NavMoveRequestKeyMods = g.IO.KeyMods; + g.NavMoveRequestKeyMods = io.KeyMods; g.NavMoveDirLast = g.NavMoveDir; } if (g.NavMoveRequest && g.NavId == 0) @@ -8733,7 +8735,7 @@ static void ImGui::NavUpdate() { // *Fallback* manual-scroll with Nav directional keys when window has no navigable item ImGuiWindow* window = g.NavWindow; - const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * g.IO.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. + const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest) { if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) @@ -8857,24 +8859,26 @@ static void ImGui::NavUpdateMoveResult() static float ImGui::NavUpdatePageUpPageDown() { ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL) return 0.0f; if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != ImGuiNavLayer_Main) return 0.0f; ImGuiWindow* window = g.NavWindow; - const bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp); - const bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown); - const bool home_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home); - const bool end_pressed = IsKeyPressed(g.IO.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End); + const bool page_up_held = IsKeyDown(io.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp); + const bool page_down_held = IsKeyDown(io.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown); + const bool home_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home); + const bool end_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End); if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed { if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll) { // Fallback manual-scroll when window has no navigable item - if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) + if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true)) SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); - else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) + else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true)) SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); else if (home_pressed) SetScrollY(window, 0.0f); @@ -8886,14 +8890,14 @@ static float ImGui::NavUpdatePageUpPageDown() ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); float nav_scoring_rect_offset_y = 0.0f; - if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) + if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true)) { nav_scoring_rect_offset_y = -page_offset_y; g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Up; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } - else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) + else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true)) { nav_scoring_rect_offset_y = +page_offset_y; g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) From b30d33378d36546fedc021177129b5882062ff76 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Aug 2020 12:41:05 +0200 Subject: [PATCH 229/959] Nav: Activate InputSource as Gamepad when pressing any of the digital d-pad button. --- imgui.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 9baba2e9..5918e087 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8528,9 +8528,12 @@ static void ImGui::NavUpdate() // (do it before we map Keyboard input!) bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; - if (nav_gamepad_active) - if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f) + if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_NavGamepad) + { + if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f + || io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f) g.NavInputSource = ImGuiInputSource_NavGamepad; + } // Update Keyboard->Nav inputs mapping if (nav_keyboard_active) From 8c80d533d96a9b9ef83b1d16dd8396f61f4dd743 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Wed, 26 Aug 2020 12:18:02 +0200 Subject: [PATCH 230/959] Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave tabs reordered in the tab list popup. --- docs/CHANGELOG.txt | 2 ++ imgui_internal.h | 6 ++++-- imgui_widgets.cpp | 14 ++++++++------ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 61600a6c..d5d601f9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,8 @@ Other Changes: and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) - Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). +- Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave + tabs reordered in the tab list popup. [@Xipiryon] - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] diff --git a/imgui_internal.h b/imgui_internal.h index 6bf49337..00baf037 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1710,9 +1710,10 @@ struct ImGuiTabItem float Width; // Width currently displayed float ContentWidth; // Width of actual contents, stored during BeginTabItem() call ImS16 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames + ImS8 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable bool WantClose; // Marked as closed by SetTabItemClosed() - ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; WantClose = false; } + ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; WantClose = false; } }; // Storage for a tab bar (sizeof() 92~96 bytes) @@ -1737,9 +1738,10 @@ struct ImGuiTabBar ImGuiTabBarFlags Flags; ImGuiID ReorderRequestTabId; ImS8 ReorderRequestDir; + ImS8 TabsActiveCount; // Number of tabs submitted this frame. bool WantLayout; bool VisibleTabWasSubmitted; - short LastTabItemIdx; // For BeginTabItem()/EndTabItem() + short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 59fa0918..352b687a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6782,15 +6782,16 @@ ImGuiTabBar::ImGuiTabBar() Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; ReorderRequestDir = 0; + TabsActiveCount = 0; WantLayout = VisibleTabWasSubmitted = false; LastTabItemIdx = -1; } -static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const void* rhs) +static int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs) { const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; - return (int)(a->Offset - b->Offset); + return (int)(a->BeginOrder - b->BeginOrder); } static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref) @@ -6842,10 +6843,9 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG return true; } - // When toggling back from ordered to manually-reorderable, shuffle tabs to enforce the last visible order. - // Otherwise, the most recently inserted tabs would move at the end of visible list which can be a little too confusing or magic for the user. - if ((flags & ImGuiTabBarFlags_Reorderable) && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1 && tab_bar->PrevFrameVisible != -1) - ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByVisibleOffset); + // When toggling ImGuiTabBarFlags_Reorderable flag, ensure tabs are ordered based on their submission order. + if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1) + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); // Flags if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) @@ -6857,6 +6857,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible; tab_bar->CurrFrameVisible = g.FrameCount; tab_bar->FramePadding = g.Style.FramePadding; + tab_bar->TabsActiveCount = 0; // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap window->DC.CursorPos.x = tab_bar->BarRect.Min.x; @@ -7362,6 +7363,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab); tab->ContentWidth = size.x; + tab->BeginOrder = tab_bar->TabsActiveCount++; const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0; From 45499b8f2f9e95f6e4b4adfe0d29219761ae9378 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Aug 2020 20:18:54 +0200 Subject: [PATCH 231/959] Window: Fixed using non-zero pivot in SetNextWindowPos() when the window is collapsed. (#3433) --- docs/CHANGELOG.txt | 3 ++- imgui.cpp | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d5d601f9..6543dacf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,8 @@ HOW TO UPDATE? Other Changes: +- Window: Fixed using non-zero pivot in SetNextWindowPos() when the window is collapsed. (#3433) +- Nav: Fixed navigation resuming on first visible item when using gamepad. [@rokups] - InputText: Added selection helpers in ImGuiInputTextCallbackData(). - InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the @@ -45,7 +47,6 @@ Other Changes: It is a rather unusual or useless combination of features but no reason it shouldn't work! - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) -- Nav: Fix navigation resuming on first visible item when using gamepad. [@rokups] - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. - TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event diff --git a/imgui.cpp b/imgui.cpp index 5918e087..922cbd0e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5721,7 +5721,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); if (window_pos_with_pivot) - SetWindowPos(window, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) + SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) From 093afd4f7f1ae3b0cb204896b134e01a142829e1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 26 Aug 2020 20:50:19 +0200 Subject: [PATCH 232/959] Internals: Added Name to ImGuiDataTypeInfo + minor misc comments in BeginGroup(). --- imgui.cpp | 11 ++++++----- imgui_internal.h | 3 ++- imgui_widgets.cpp | 24 ++++++++++++------------ 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 922cbd0e..c352c8a5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7271,10 +7271,11 @@ float ImGui::GetWindowContentRegionWidth() } // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) +// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated. void ImGui::BeginGroup() { ImGuiContext& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = g.CurrentWindow; window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); @@ -7299,8 +7300,8 @@ void ImGui::BeginGroup() void ImGui::EndGroup() { ImGuiContext& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(window->DC.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); @@ -7328,9 +7329,9 @@ void ImGui::EndGroup() // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. // Also if you grep for LastItemId you'll notice it is only used in that context. - // (The tests not symmetrical because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.) + // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.) const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId; - const bool group_contains_prev_active_id = !group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive; + const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true); if (group_contains_curr_active_id) window->DC.LastItemId = g.ActiveId; else if (group_contains_prev_active_id) diff --git a/imgui_internal.h b/imgui_internal.h index 00baf037..5f55d218 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -786,7 +786,8 @@ struct ImGuiDataTypeTempStorage // Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). struct ImGuiDataTypeInfo { - size_t Size; // Size in byte + size_t Size; // Size in bytes + const char* Name; // Short descriptive name for the type, for debugging const char* PrintFmt; // Default printf format for the type const char* ScanFmt; // Default scanf format for the type }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 352b687a..691b36f7 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1687,21 +1687,21 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa static const ImGuiDataTypeInfo GDataTypeInfo[] = { - { sizeof(char), "%d", "%d" }, // ImGuiDataType_S8 - { sizeof(unsigned char), "%u", "%u" }, - { sizeof(short), "%d", "%d" }, // ImGuiDataType_S16 - { sizeof(unsigned short), "%u", "%u" }, - { sizeof(int), "%d", "%d" }, // ImGuiDataType_S32 - { sizeof(unsigned int), "%u", "%u" }, + { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8 + { sizeof(unsigned char), "U8", "%u", "%u" }, + { sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16 + { sizeof(unsigned short), "U16", "%u", "%u" }, + { sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32 + { sizeof(unsigned int), "U32", "%u", "%u" }, #ifdef _MSC_VER - { sizeof(ImS64), "%I64d","%I64d" }, // ImGuiDataType_S64 - { sizeof(ImU64), "%I64u","%I64u" }, + { sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64 + { sizeof(ImU64), "U64", "%I64u","%I64u" }, #else - { sizeof(ImS64), "%lld", "%lld" }, // ImGuiDataType_S64 - { sizeof(ImU64), "%llu", "%llu" }, + { sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64 + { sizeof(ImU64), "U64", "%llu", "%llu" }, #endif - { sizeof(float), "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) - { sizeof(double), "%f", "%lf" }, // ImGuiDataType_Double + { sizeof(float), "float", "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) + { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double }; IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); From 302896d4884896128ffe59257bb64b4f5af8aae5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Aug 2020 12:19:13 +0200 Subject: [PATCH 233/959] Basic optimization for ShadeVertsLinearColorGradientKeepAlpha() - especially for debug overhead - since it's used massively by some of our experiments. --- imgui_draw.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index bb300e00..5b79a449 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1599,13 +1599,19 @@ void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int ve float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + const int col0_r = (int)(col0 >> IM_COL32_R_SHIFT) & 0xFF; + const int col0_g = (int)(col0 >> IM_COL32_G_SHIFT) & 0xFF; + const int col0_b = (int)(col0 >> IM_COL32_B_SHIFT) & 0xFF; + const int col_delta_r = ((int)(col1 >> IM_COL32_R_SHIFT) & 0xFF) - col0_r; + const int col_delta_g = ((int)(col1 >> IM_COL32_G_SHIFT) & 0xFF) - col0_g; + const int col_delta_b = ((int)(col1 >> IM_COL32_B_SHIFT) & 0xFF) - col0_b; for (ImDrawVert* vert = vert_start; vert < vert_end; vert++) { float d = ImDot(vert->pos - gradient_p0, gradient_extent); float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); - int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t); - int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t); - int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t); + int r = (int)(col0_r + col_delta_r * t); + int g = (int)(col0_g + col_delta_g * t); + int b = (int)(col0_b + col_delta_b * t); vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK); } } From 901d432cb7b2fa25bac2ccf8f55805e65aa9debc Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Aug 2020 19:51:25 +0200 Subject: [PATCH 234/959] Nav: Fixed using Alt to toggle the Menu layer when inside a Modal window. (#787) Tidying up todo items. --- docs/CHANGELOG.txt | 1 + docs/TODO.txt | 16 ++++++++-------- imgui.cpp | 10 ++++------ 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6543dacf..70235720 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,6 +39,7 @@ Other Changes: - Window: Fixed using non-zero pivot in SetNextWindowPos() when the window is collapsed. (#3433) - Nav: Fixed navigation resuming on first visible item when using gamepad. [@rokups] +- Nav: Fixed using Alt to toggle the Menu layer when inside a Modal window. (#787) - InputText: Added selection helpers in ImGuiInputTextCallbackData(). - InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the diff --git a/docs/TODO.txt b/docs/TODO.txt index e1b1f3e3..509fcca5 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -333,20 +333,24 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font/opt: Glyph currently 40 bytes (2+9*4). Consider storing UV as 16 bits integer? (->32 bytes). X0/Y0/X1/Y1 as 16 fixed-point integers? Or X0/Y0 as float and X1/Y1 as fixed8_8? - nav: some features such as PageUp/Down/Home/End should probably work without ImGuiConfigFlags_NavEnableKeyboard? (where do we draw the line?) + - nav: configuration flag to disable global shortcuts (currently only CTRL-Tab) ? ! nav: never clear NavId on some setup (e.g. gamepad centric) + - nav: there's currently no way to completely clear focus with the keyboard. depending on patterns used by the application to dispatch inputs, it may be desirable. - nav: code to focus child-window on restoring NavId appears to have issue: e.g. when focus change is implicit because of window closure. - - nav: configuration flag to disable global shortcuts (currently only CTRL-Tab) ? - nav: Home/End behavior when navigable item is not fully visible at the edge of scrolling? should be backtrack to keep item into view? - nav: NavScrollToBringItemIntoView() with item bigger than view should focus top-right? Repro: using Nav in "About Window" - nav: wrap around logic to allow e.g. grid based layout (pressing NavRight on the right-most element would go to the next row, etc.). see internal's NavMoveRequestTryWrapping(). - - nav: patterns to make it possible for arrows key to update selection + - nav: patterns to make it possible for arrows key to update selection (see JustMovedTo in range_select branch) - nav: restore/find nearest NavId when current one disappear (e.g. pressed a button that disappear, or perhaps auto restoring when current button change name) - nav: SetItemDefaultFocus() level of priority, so widget like Selectable when inside a popup could claim a low-priority default focus on the first selected iem - nav: NavFlattened: ESC on a flattened child should select something. - nav: NavFlattened: broken: in typical usage scenario, the items of a fully clipped child are currently not considered to enter into a NavFlattened child. - nav: NavFlattened: init request doesn't select items that are part of a NavFlattened child - nav: NavFlattened: cannot access menu-bar of a flattened child window with Alt/menu key (not a very common use case..). - - nav/treenode: Left within a tree node block as a fallback (ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default?) + - nav: simulate right-click or context activation? (SHIFT+F10) + - nav/tabbing: refactor old tabbing system and turn into navigation, should pass through all widgets (in submission order?). + - nav/popup: esc/enter default behavior for popups, e.g. be able to mark an "ok" or "cancel" button that would get triggered by those keys, default validation button, etc. + - nav/treenode: left within a tree node block as a fallback (ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default?) - nav/menus: pressing left-right on a vertically clipped menu bar tends to jump to the collapse/close buttons. - nav/menus: allow pressing Menu to leave a sub-menu. - nav/menus: a way to access the main menu bar with Alt? (currently needs CTRL+TAB) or last focused window menu bar? @@ -355,11 +359,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - nav/menus: Alt,Up could open the first menu (e.g. "File") currently it tends to nav into the window/collapse menu. Do do that we would need custom transition? - nav/windowing: configure fade-in/fade-out delay on Ctrl+Tab? - nav/windowing: when CTRL-Tab/windowing is active, the HoveredWindow detection doesn't take account of the window display re-ordering. - - nav: simulate right-click or context activation? (SHIFT+F10) - - nav: tabs should go through most/all widgets (in submission order?). - - nav: esc/enter default behavior for popups, e.g. be able to mark an "ok" or "cancel" button that would get triggered by those keys. - - nav: when activating a button that changes label (without a static ID) or disappear, can we somehow automatically recover into a nearest highlight item? - - nav: there's currently no way to completely clear focus with the keyboard. depending on patterns used by the application to dispatch inputs, it may be desirable. + - nav/windowing: Resizing window will currently fail with certain types of resizing constraints/callback applied - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) - focus: unable to use SetKeyboardFocusHere() on clipped widgets. (#787) diff --git a/imgui.cpp b/imgui.cpp index c352c8a5..36c4df2d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9039,11 +9039,9 @@ static void ImGui::NavUpdateWindowing() bool apply_toggle_layer = false; ImGuiWindow* modal_window = GetTopMostPopupModal(); - if (modal_window != NULL) - { + bool allow_windowing = (modal_window == NULL); + if (!allow_windowing) g.NavWindowingTarget = NULL; - return; - } // Fade out if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL) @@ -9054,8 +9052,8 @@ static void ImGui::NavUpdateWindowing() } // Start CTRL-TAB or Square+L/R window selection - bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); - bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard); + bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); + bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard); if (start_windowing_with_gamepad || start_windowing_with_keyboard) if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) { From 13f718337ac4df2c66727e85174d48e9a91eabcf Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Aug 2020 16:49:46 +0200 Subject: [PATCH 235/959] Internals: Added support for overriding locale decimal point, undocumented. (#2278) + Misc doc update. Doc: Mention IMGUI_VERSION_NUM in recent api breaking changes + textwrap some demo code. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 1 + imgui.h | 3 ++- imgui_demo.cpp | 46 +++++++++++++++++++++++++++++++++------------- imgui_internal.h | 2 ++ imgui_widgets.cpp | 12 ++++++++++-- 6 files changed, 49 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 70235720..032360ad 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -88,6 +88,7 @@ Breaking Changes: - You can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. See https://github.com/ocornut/imgui/issues/3361 for all details. + For shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. Kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used. - DragInt, DragFloat, DragScalar: Obsoleted use of v_min > v_max to lock edits (introduced in 1.73, this was not diff --git a/imgui.cpp b/imgui.cpp index 36c4df2d..9fe70421 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -380,6 +380,7 @@ CODE - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. see https://github.com/ocornut/imgui/issues/3361 for all details. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. + for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). diff --git a/imgui.h b/imgui.h index 27ef591d..40ffedad 100644 --- a/imgui.h +++ b/imgui.h @@ -1712,7 +1712,8 @@ struct ImGuiPayload namespace ImGui { // OBSOLETED in 1.78 (from August 2020) - // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags + // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags. + // For shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power); static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index efb83a4d..05bb729a 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -560,7 +560,9 @@ static void ShowDemoWindowWidgets() const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }; static int item_current = 0; ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items)); - ImGui::SameLine(); HelpMarker("Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, and demonstration of various flags.\n"); + ImGui::SameLine(); HelpMarker( + "Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, " + "and demonstration of various flags.\n"); } { @@ -834,7 +836,9 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Word Wrapping")) { // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. - ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::TextWrapped( + "This text should automatically wrap on the edge of the window. The current implementation " + "for text wrapping follows simple rules suitable for English and possibly other languages."); ImGui::Spacing(); static float wrap_width = 200.0f; @@ -891,7 +895,10 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Images")) { ImGuiIO& io = ImGui::GetIO(); - ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); + ImGui::TextWrapped( + "Below we are displaying the font texture (which is the only texture we have access to in this demo). " + "Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. " + "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 @@ -1000,9 +1007,9 @@ static void ShowDemoWindowWidgets() ImGui::Combo("combo 3 (array)", &item_current_3, items, IM_ARRAYSIZE(items)); // Simplified one-liner Combo() using an accessor function - struct FuncHolder { static bool ItemGetter(void* data, int idx, const char** out_str) { *out_str = ((const char**)data)[idx]; return true; } }; + struct Funcs { static bool ItemGetter(void* data, int n, const char** out_str) { *out_str = ((const char**)data)[n]; return true; } }; static int item_current_4 = 0; - ImGui::Combo("combo 4 (function)", &item_current_4, &FuncHolder::ItemGetter, items, IM_ARRAYSIZE(items)); + ImGui::Combo("combo 4 (function)", &item_current_4, &Funcs::ItemGetter, items, IM_ARRAYSIZE(items)); ImGui::TreePop(); } @@ -1640,7 +1647,10 @@ static void ShowDemoWindowWidgets() const float drag_speed = 0.2f; static bool drag_clamp = false; ImGui::Text("Drags:"); - ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); ImGui::SameLine(); HelpMarker("As with every widgets in dear imgui, we never modify values unless there is a user interaction.\nYou can override the clamping limits by using CTRL+Click to input a value."); + ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp); + ImGui::SameLine(); HelpMarker( + "As with every widgets in dear imgui, we never modify values unless there is a user interaction.\n" + "You can override the clamping limits by using CTRL+Click to input a value."); ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL); ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms"); ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL); @@ -3957,9 +3967,13 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::BeginTabItem("Rendering")) { ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); - ImGui::SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); + ImGui::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(); HelpMarker("Faster lines using texture data. Require back-end to render with bilinear filtering (not point/nearest filtering)."); + ImGui::SameLine(); + HelpMarker("Faster lines using texture data. Require back-end to render with bilinear filtering (not point/nearest filtering)."); + ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill); ImGui::PushItemWidth(100); ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f"); @@ -3972,12 +3986,13 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); ImGui::BeginTooltip(); ImVec2 p = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); float RAD_MIN = 10.0f, RAD_MAX = 80.0f; float off_x = 10.0f; for (int n = 0; n < 7; n++) { const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (7.0f - 1.0f); - ImGui::GetWindowDrawList()->AddCircle(ImVec2(p.x + off_x + rad, p.y + RAD_MAX), rad, ImGui::GetColorU32(ImGuiCol_Text), 0); + draw_list->AddCircle(ImVec2(p.x + off_x + rad, p.y + RAD_MAX), rad, ImGui::GetColorU32(ImGuiCol_Text), 0); off_x += 10.0f + rad * 2.0f; } ImGui::Dummy(ImVec2(off_x, RAD_MAX * 2.0f)); @@ -4200,9 +4215,12 @@ struct ExampleAppConsole // TODO: display items starting from the bottom - if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); - if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); - if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } + ImGui::SameLine(); + if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); } + ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) { ClearLog(); } + ImGui::SameLine(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } @@ -4695,7 +4713,9 @@ static void ShowPlaceholderObject(const char* prefix, int uid) { // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. ImGui::PushID(uid); - ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than framed widgets, here we add vertical spacing to make the tree lines equal high. + + // Text and Tree nodes are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the tree lines equal high. + ImGui::AlignTextToFramePadding(); bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); ImGui::NextColumn(); ImGui::AlignTextToFramePadding(); diff --git a/imgui_internal.h b/imgui_internal.h index 5f55d218..6c9a3f75 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1290,6 +1290,7 @@ struct ImGuiContext // Platform support ImVec2 PlatformImePos; // Cursor position request & last passed to the OS Input Method Editor ImVec2 PlatformImeLastPos; + char PlatformLocaleDecimalPoint; // '.' or *localeconv()->decimal_point // Settings bool SettingsLoaded; @@ -1440,6 +1441,7 @@ struct ImGuiContext TooltipOverrideCount = 0; PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX); + PlatformLocaleDecimalPoint = '.'; SettingsLoaded = false; SettingsDirtyTimer = 0.0f; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 691b36f7..181fbd7b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3691,14 +3691,22 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f // Generic named filters if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific)) { + // The libc allows overriding locale, with e.g. 'setlocale(LC_NUMERIC, "de_DE.UTF-8");' which affect the output/input of printf/scanf. + // The standard mandate that programs starts in the "C" locale where the decimal point is '.'. + // We don't really intend to provide widespread support for it, but out of empathy for people stuck with using odd API, we support the bare minimum aka overriding the decimal point. + // Change the default decimal_point with: + // ImGui::GetCurrentContext()->PlatformLocaleDecimalPoint = *localeconv()->decimal_point; + ImGuiContext& g = *GImGui; + const unsigned c_decimal_point = (unsigned int)g.PlatformLocaleDecimalPoint; + // Allow 0-9 . - + * / if (flags & ImGuiInputTextFlags_CharsDecimal) - if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) + if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; // Allow 0-9 . - + * / e E if (flags & ImGuiInputTextFlags_CharsScientific) - if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) + if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) return false; // Allow 0-9 a-F A-F From 600b8f60b48f8a038065753830e99e975412379e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 28 Aug 2020 20:20:28 +0200 Subject: [PATCH 236/959] Docking: Fixed crash in metrics. --- imgui.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index c0279359..68ebd424 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -15687,7 +15687,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); if (!is_alive) { PopStyleColor(); } if (is_active && ImGui::IsItemHovered()) - GetForegroundDrawList(node->HostWindow ? node->HostWindow : node->VisibleWindow)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); + if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow) + GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); if (open) { IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); From ce230fc370c29af565b3e380a521b07a7f321563 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 31 Aug 2020 17:25:16 +0200 Subject: [PATCH 237/959] Internals: TabBar renaming and shuffling stuff around. + sneaking a readme change --- docs/README.md | 2 +- imgui.cpp | 4 +-- imgui_internal.h | 7 ++--- imgui_widgets.cpp | 66 ++++++++++++++++++++++++++--------------------- 4 files changed, 44 insertions(+), 35 deletions(-) diff --git a/docs/README.md b/docs/README.md index 58fb208e..230aa03c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -115,7 +115,7 @@ Officially maintained bindings (in repository): Third-party bindings (see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings/) page): - Languages: C, C# and: Beef, ChaiScript, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... -- Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. +- Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, nCine, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. - Note that C bindings ([cimgui](https://github.com/cimgui/cimgui)) are auto-generated, you can use its json/lua output to generate bindings for other languages. Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. diff --git a/imgui.cpp b/imgui.cpp index 9fe70421..f0d2a47a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10504,8 +10504,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) { const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; ImGui::PushID(tab); - if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); - if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine(); + if (ImGui::SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); + if (ImGui::SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } ImGui::SameLine(); ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : ""); ImGui::PopID(); } diff --git a/imgui_internal.h b/imgui_internal.h index 6c9a3f75..7c5cb0fd 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1731,8 +1731,8 @@ struct ImGuiTabBar int PrevFrameVisible; ImRect BarRect; float LastTabContentHeight; // Record the height of contents submitted below the tab bar - float OffsetMax; // Distance from BarRect.Min.x, locked during layout - float OffsetMaxIdeal; // Ideal offset if all tabs were visible and not clipped + float WidthAllTabs; // Actual width of all tabs (locked during layout) + float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped float OffsetNextTab; // Distance from BarRect.Min.x, incremented with each BeginTabItem() call, not used if ImGuiTabBarFlags_Reorderable if set. float ScrollingAnim; float ScrollingTarget; @@ -1931,7 +1931,8 @@ namespace ImGui IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id); IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); - IMGUI_API void TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir); + IMGUI_API void TabBarQueueReorder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir); + IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar); IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags); IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button); IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 181fbd7b..eb5e4ad9 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6761,7 +6761,7 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, // - TabBarFindTabById() [Internal] // - TabBarRemoveTab() [Internal] // - TabBarCloseTab() [Internal] -// - TabBarScrollClamp()v +// - TabBarScrollClamp() [Internal] // - TabBarScrollToTab() [Internal] // - TabBarQueueChangeTabOrder() [Internal] // - TabBarScrollingButtons() [Internal] @@ -6785,7 +6785,7 @@ ImGuiTabBar::ImGuiTabBar() SelectedTabId = NextSelectedTabId = VisibleTabId = 0; CurrFrameVisible = PrevFrameVisible = -1; LastTabContentHeight = 0.0f; - OffsetMax = OffsetMaxIdeal = OffsetNextTab = 0.0f; + WidthAllTabs = WidthAllTabsIdeal = OffsetNextTab = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; @@ -6951,23 +6951,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot). if (tab_bar->ReorderRequestTabId != 0) { - if (ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId)) - { - //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools - int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir; - if (tab2_order >= 0 && tab2_order < tab_bar->Tabs.Size) - { - ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order]; - ImGuiTabItem item_tmp = *tab1; - *tab1 = *tab2; - *tab2 = item_tmp; - if (tab2->ID == tab_bar->SelectedTabId) - scroll_track_selected_tab_id = tab2->ID; - tab1 = tab2 = NULL; - } - if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings) - MarkIniSettingsDirty(); - } + if (TabBarProcessReorder(tab_bar)) + if (tab_bar->ReorderRequestTabId == tab_bar->SelectedTabId) + scroll_track_selected_tab_id = tab_bar->ReorderRequestTabId; tab_bar->ReorderRequestTabId = 0; } @@ -7041,11 +7027,11 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) offset_x += tab->Width + g.Style.ItemInnerSpacing.x; offset_x_ideal += tab->ContentWidth + g.Style.ItemInnerSpacing.x; } - tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); - tab_bar->OffsetMaxIdeal = ImMax(offset_x_ideal - g.Style.ItemInnerSpacing.x, 0.0f); + tab_bar->WidthAllTabs = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); + tab_bar->WidthAllTabsIdeal = ImMax(offset_x_ideal - g.Style.ItemInnerSpacing.x, 0.0f); // Horizontal scrolling buttons - const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); + const bool scrolling_buttons = (tab_bar->WidthAllTabs > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) if (ImGuiTabItem* tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; @@ -7087,7 +7073,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos = tab_bar->BarRect.Min; - ItemSize(ImVec2(tab_bar->OffsetMaxIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); + ItemSize(ImVec2(tab_bar->WidthAllTabsIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. @@ -7150,7 +7136,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling) { - scrolling = ImMin(scrolling, tab_bar->OffsetMax - tab_bar->BarRect.GetWidth()); + scrolling = ImMin(scrolling, tab_bar->WidthAllTabs - tab_bar->BarRect.GetWidth()); return ImMax(scrolling, 0.0f); } @@ -7174,7 +7160,7 @@ static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) } } -void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir) +void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir) { IM_ASSERT(dir == -1 || dir == +1); IM_ASSERT(tab_bar->ReorderRequestTabId == 0); @@ -7182,6 +7168,28 @@ void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab_bar->ReorderRequestDir = (ImS8)dir; } +bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar) +{ + ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId); + if (!tab1) + return false; + + //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools + int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir; + if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size) + return false; + + ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order]; + ImGuiTabItem item_tmp = *tab1; + *tab1 = *tab2; + *tab2 = item_tmp; + tab1 = tab2 = NULL; + + if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings) + MarkIniSettingsDirty(); + return true; +} + static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; @@ -7293,7 +7301,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f ImGuiTabBar* tab_bar = g.CurrentTabBar; if (tab_bar == NULL) { - IM_ASSERT_USER_ERROR(tab_bar, "BeginTabItem() Needs to be called between BeginTabBar() and EndTabBar()!"); + IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; } bool ret = TabItemEx(tab_bar, label, p_open, flags); @@ -7315,7 +7323,7 @@ void ImGui::EndTabItem() ImGuiTabBar* tab_bar = g.CurrentTabBar; if (tab_bar == NULL) { - IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!"); + IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); return; } IM_ASSERT(tab_bar->LastTabItemIdx >= 0); @@ -7471,12 +7479,12 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x) { if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) - TabBarQueueChangeTabOrder(tab_bar, tab, -1); + TabBarQueueReorder(tab_bar, tab, -1); } else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x) { if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) - TabBarQueueChangeTabOrder(tab_bar, tab, +1); + TabBarQueueReorder(tab_bar, tab, +1); } } } From a456d17dfc7fa5ebbe9d7897552d6e505a593406 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 1 Sep 2020 15:24:24 +0200 Subject: [PATCH 238/959] Internals: Begin: update ->Hidden flags only on first begin of the frame. (ignore whitespace to see simple diff) --- imgui.cpp | 53 +++++++++++++++++++++++++++++------------------------ 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index f0d2a47a..ff6e5fcc 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5248,6 +5248,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar ImGuiWindowFlags flags = window->Flags; // Ensure that ScrollBar doesn't read last frame's SkipItems + IM_ASSERT(window->BeginCount == 0); window->SkipItems = false; // Draw window + handle manual resize @@ -6029,37 +6030,41 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->BeginCount++; g.NextWindowData.ClearFlags(); - if (flags & ImGuiWindowFlags_ChildWindow) + // Update visibility + if (first_begin_of_the_frame) { - // Child window can be out of sight and have "negative" clip windows. - // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). - IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); - if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) - if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + if (flags & ImGuiWindowFlags_ChildWindow) + { + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + window->HiddenFramesCanSkipItems = 1; + + // Hide along with parent or if parent is collapsed + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) window->HiddenFramesCanSkipItems = 1; + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) + window->HiddenFramesCannotSkipItems = 1; + } - // Hide along with parent or if parent is collapsed - if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) + // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) + if (style.Alpha <= 0.0f) window->HiddenFramesCanSkipItems = 1; - if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) - window->HiddenFramesCannotSkipItems = 1; - } - // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) - if (style.Alpha <= 0.0f) - window->HiddenFramesCanSkipItems = 1; + // Update the Hidden flag + window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); - // Update the Hidden flag - window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); - - // Update the SkipItems flag, used to early out of all items functions (no layout required) - bool skip_items = false; - if (window->Collapsed || !window->Active || window->Hidden) - if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) - skip_items = true; - window->SkipItems = skip_items; + // Update the SkipItems flag, used to early out of all items functions (no layout required) + bool skip_items = false; + if (window->Collapsed || !window->Active || window->Hidden) + if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) + skip_items = true; + window->SkipItems = skip_items; + } - return !skip_items; + return !window->SkipItems; } void ImGui::End() From fc625d249f4f31c42cb0d73cca954c97d120c0bb Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 1 Sep 2020 15:24:24 +0200 Subject: [PATCH 239/959] Internals: Begin: update ->Hidden flags only on first begin of the frame. (ignore whitespace to see simple diff) # Conflicts: # imgui.cpp --- imgui.cpp | 75 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 40 insertions(+), 35 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 3d6662a1..cdfa456d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5602,6 +5602,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar ImGuiWindowFlags flags = window->Flags; // Ensure that ScrollBar doesn't read last frame's SkipItems + IM_ASSERT(window->BeginCount == 0); window->SkipItems = false; // Draw window + handle manual resize @@ -6626,49 +6627,53 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->BeginCount++; g.NextWindowData.ClearFlags(); - // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. - // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. - // This is analogous to regular windows being hidden from one frame. - // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. - if (window->DockIsActive && !window->DockTabIsVisible) + // Update visibility + if (first_begin_of_the_frame) { - if (window->LastFrameJustFocused == g.FrameCount) - window->HiddenFramesCannotSkipItems = 1; - else - window->HiddenFramesCanSkipItems = 1; - } + // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. + // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. + // This is analogous to regular windows being hidden from one frame. + // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. + if (window->DockIsActive && !window->DockTabIsVisible) + { + if (window->LastFrameJustFocused == g.FrameCount) + window->HiddenFramesCannotSkipItems = 1; + else + window->HiddenFramesCanSkipItems = 1; + } - if (flags & ImGuiWindowFlags_ChildWindow) - { - // Child window can be out of sight and have "negative" clip windows. - // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). - IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive)); - if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) - if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + if (flags & ImGuiWindowFlags_ChildWindow) + { + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive)); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + window->HiddenFramesCanSkipItems = 1; + + // Hide along with parent or if parent is collapsed + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) window->HiddenFramesCanSkipItems = 1; + if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) + window->HiddenFramesCannotSkipItems = 1; + } - // Hide along with parent or if parent is collapsed - if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) + // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) + if (style.Alpha <= 0.0f) window->HiddenFramesCanSkipItems = 1; - if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) - window->HiddenFramesCannotSkipItems = 1; - } - // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) - if (style.Alpha <= 0.0f) - window->HiddenFramesCanSkipItems = 1; + // Update the Hidden flag + window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); - // Update the Hidden flag - window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); - - // Update the SkipItems flag, used to early out of all items functions (no layout required) - bool skip_items = false; - if (window->Collapsed || !window->Active || window->Hidden) - if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) - skip_items = true; - window->SkipItems = skip_items; + // Update the SkipItems flag, used to early out of all items functions (no layout required) + bool skip_items = false; + if (window->Collapsed || !window->Active || window->Hidden) + if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) + skip_items = true; + window->SkipItems = skip_items; + } - return !skip_items; + return !window->SkipItems; } void ImGui::End() From f4d062fa110560ef1336acc73b254f265d3dc9fd Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 1 Sep 2020 18:33:51 +0200 Subject: [PATCH 240/959] Nav: Added debug logging, extract bits of code into NavUpdateInitResult(). --- imgui.cpp | 38 +++++++++++++++++++++++++------------- imgui_internal.h | 2 ++ 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ff6e5fcc..7beb69b1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -841,6 +841,7 @@ static void NavUpdate(); static void NavUpdateWindowing(); static void NavUpdateWindowingOverlay(); static void NavUpdateMoveResult(); +static void NavUpdateInitResult(); static float NavUpdatePageUpPageDown(); static inline void NavUpdateAnyRequestFlag(); static void NavEndFrame(); @@ -8444,7 +8445,7 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) if (!(window->Flags & ImGuiWindowFlags_NoNavInputs)) if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) init_for_nav = true; - //IMGUI_DEBUG_LOG("[Nav] NavInitWindow() init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer); + IMGUI_DEBUG_LOG("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer); if (init_for_nav) { SetNavID(0, g.NavLayer, 0); @@ -8566,17 +8567,8 @@ static void ImGui::NavUpdate() io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f; // Process navigation init request (select first/default focus) - // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) - if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow) - { - // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) - //IMGUI_DEBUG_LOG("[Nav] Apply NavInitRequest result: 0x%08X Layer %d in \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name); - if (g.NavInitRequestFromMove) - SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel); - else - SetNavID(g.NavInitResultId, g.NavLayer, 0); - g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; - } + if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove)) + NavUpdateInitResult(); g.NavInitRequest = false; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; @@ -8629,6 +8621,7 @@ static void ImGui::NavUpdate() // Process NavCancel input (to close a popup, get back to parent, clear focus) if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed)) { + IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n"); if (g.ActiveId != 0) { if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel)) @@ -8714,6 +8707,7 @@ static void ImGui::NavUpdate() // (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function) IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None); IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued); + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir); g.NavMoveRequestForward = ImGuiNavForward_ForwardActive; } @@ -8732,7 +8726,7 @@ static void ImGui::NavUpdate() } if (g.NavMoveRequest && g.NavId == 0) { - //IMGUI_DEBUG_LOG("[Nav] NavInitRequest from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer); + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer); g.NavInitRequest = g.NavInitRequestFromMove = true; // Reassigning with same value, we're being explicit here. g.NavInitResultId = 0; // -V1048 @@ -8777,6 +8771,7 @@ static void ImGui::NavUpdate() ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1)); if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel\n"); float pad = window->CalcFontSize() * 0.5f; window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item window->NavRectRel[g.NavLayer].ClipWithFull(window_rect_rel); @@ -8803,6 +8798,22 @@ static void ImGui::NavUpdate() #endif } +static void ImGui::NavUpdateInitResult() +{ + // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) + ImGuiContext& g = *GImGui; + if (!g.NavWindow) + return; + + // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name); + if (g.NavInitRequestFromMove) + SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel); + else + SetNavID(g.NavInitResultId, g.NavLayer, 0); + g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; +} + // Apply result from previous frame navigation directional move request static void ImGui::NavUpdateMoveResult() { @@ -8862,6 +8873,7 @@ static void ImGui::NavUpdateMoveResult() g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = g.NavMoveRequestKeyMods; } + IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name); SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel); } diff --git a/imgui_internal.h b/imgui_internal.h index 7c5cb0fd..1eed0d5b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -163,7 +163,9 @@ namespace ImStb // Debug Logging for selected systems. Remove the '((void)0) //' to enable. //#define IMGUI_DEBUG_LOG_POPUP IMGUI_DEBUG_LOG // Enable log +//#define IMGUI_DEBUG_LOG_NAV IMGUI_DEBUG_LOG // Enable log #define IMGUI_DEBUG_LOG_POPUP(...) ((void)0) // Disable log +#define IMGUI_DEBUG_LOG_NAV(...) ((void)0) // Disable log // Static Asserts #if (__cplusplus >= 201100) From 9a9ee7f813b9f1beb8b0709824b576acd335cbf6 Mon Sep 17 00:00:00 2001 From: Valentin Vanelslande Date: Tue, 1 Sep 2020 16:19:33 -0500 Subject: [PATCH 241/959] NavInitWindow: Change IMGUI_DEBUG_LOG to IMGUI_DEBUG_LOG_NAV (#3450) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 7beb69b1..e0a15289 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8445,7 +8445,7 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) if (!(window->Flags & ImGuiWindowFlags_NoNavInputs)) if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) init_for_nav = true; - IMGUI_DEBUG_LOG("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer); + IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer); if (init_for_nav) { SetNavID(0, g.NavLayer, 0); From 8dacb4da20021f4289ac56a83738672604a0db61 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 1 Sep 2020 19:43:46 +0200 Subject: [PATCH 242/959] Docking: Fixed DockNode tab bar initial order broken by 8c80d533d --- imgui.cpp | 5 +++-- imgui.h | 2 +- imgui_widgets.cpp | 3 ++- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cdfa456d..3611c424 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13256,8 +13256,8 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w IMGUI_DEBUG_LOG_DOCKING("In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : ""); for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++) IMGUI_DEBUG_LOG_DOCKING(" - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder); - if (tab_bar->Tabs.Size > tabs_unsorted_start + 1) - ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder); + if (tab_bar->Tabs.Size > tabs_unsorted_start + 1) + ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder); } // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated @@ -14144,6 +14144,7 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla flags |= ImGuiDockNodeFlags_KeepAliveOnly; IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); + IM_ASSERT(id != 0); ImGuiDockNode* node = DockContextFindNodeByID(ctx, id); if (!node) { diff --git a/imgui.h b/imgui.h index 12cc980e..ae5b40ca 100644 --- a/imgui.h +++ b/imgui.h @@ -1180,7 +1180,7 @@ 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 ImGuiConfigFlags_PlatformHasViewports + ImGuiConfigFlags_RendererHasViewports set by the respective back-ends) + ImGuiConfigFlags_ViewportsEnable = 1 << 10, // Viewport enable flags (require both ImGuiBackendFlags_PlatformHasViewports + ImGuiBackendFlags_RendererHasViewports set by the respective back-ends) 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. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9dc515ae..2d516bc1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6885,7 +6885,8 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG // When toggling ImGuiTabBarFlags_Reorderable flag, ensure tabs are ordered based on their submission order. if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1) - ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); + if ((flags & ImGuiTabBarFlags_DockNode) == 0) + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); // Flags if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) From b73305be117158b21a94eee8fe3668c0275b1e26 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 2 Sep 2020 12:43:05 +0200 Subject: [PATCH 243/959] Examples: Vulkan: Reworked buffer resize handling, amend df89a16d (#3390, #2626) --- examples/example_glfw_vulkan/main.cpp | 29 ++++++++++++++++++--------- examples/example_sdl_vulkan/main.cpp | 29 ++++++++++++++++++--------- 2 files changed, 38 insertions(+), 20 deletions(-) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 8e75abbf..6dc2e6cf 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -43,8 +43,6 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static int g_MinImageCount = 2; static bool g_SwapChainRebuild = false; -static int g_SwapChainResizeWidth = 0; -static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { @@ -255,6 +253,11 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + if (err == VK_ERROR_OUT_OF_DATE_KHR) + { + g_SwapChainRebuild = true; + return; + } check_vk_result(err); ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; @@ -310,8 +313,10 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) } } -static void FramePresent(ImGui_ImplVulkanH_Window* wd, GLFWwindow* window) +static void FramePresent(ImGui_ImplVulkanH_Window* wd) { + if (g_SwapChainRebuild) + return; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; @@ -323,7 +328,6 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd, GLFWwindow* window) VkResult err = vkQueuePresentKHR(g_Queue, &info); if (err == VK_ERROR_OUT_OF_DATE_KHR) { - glfwGetFramebufferSize(window, &g_SwapChainResizeWidth, &g_SwapChainResizeHeight); g_SwapChainRebuild = true; return; } @@ -455,12 +459,17 @@ int main(int, char**) glfwPollEvents(); // Resize swap chain? - if (g_SwapChainRebuild && g_SwapChainResizeWidth > 0 && g_SwapChainResizeHeight > 0) + if (g_SwapChainRebuild) { - g_SwapChainRebuild = false; - ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); - g_MainWindowData.FrameIndex = 0; + int width, height; + glfwGetFramebufferSize(window, &width, &height); + if (width > 0 && height > 0) + { + ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + g_MainWindowData.FrameIndex = 0; + g_SwapChainRebuild = false; + } } // Start the Dear ImGui frame @@ -513,7 +522,7 @@ int main(int, char**) { memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); - FramePresent(wd, window); + FramePresent(wd); } } diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index c0a98088..b22e4247 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -35,8 +35,6 @@ static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE; static ImGui_ImplVulkanH_Window g_MainWindowData; static uint32_t g_MinImageCount = 2; static bool g_SwapChainRebuild = false; -static int g_SwapChainResizeWidth = 0; -static int g_SwapChainResizeHeight = 0; static void check_vk_result(VkResult err) { @@ -247,6 +245,11 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) VkSemaphore image_acquired_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].ImageAcquiredSemaphore; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR(g_Device, wd->Swapchain, UINT64_MAX, image_acquired_semaphore, VK_NULL_HANDLE, &wd->FrameIndex); + if (err == VK_ERROR_OUT_OF_DATE_KHR) + { + g_SwapChainRebuild = true; + return; + } check_vk_result(err); ImGui_ImplVulkanH_Frame* fd = &wd->Frames[wd->FrameIndex]; @@ -302,8 +305,10 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd, ImDrawData* draw_data) } } -static void FramePresent(ImGui_ImplVulkanH_Window* wd, SDL_Window* window) +static void FramePresent(ImGui_ImplVulkanH_Window* wd) { + if (g_SwapChainRebuild) + return; VkSemaphore render_complete_semaphore = wd->FrameSemaphores[wd->SemaphoreIndex].RenderCompleteSemaphore; VkPresentInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; @@ -315,7 +320,6 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd, SDL_Window* window) VkResult err = vkQueuePresentKHR(g_Queue, &info); if (err == VK_ERROR_OUT_OF_DATE_KHR) { - SDL_GetWindowSize(window, &g_SwapChainResizeWidth, &g_SwapChainResizeHeight); g_SwapChainRebuild = true; return; } @@ -454,12 +458,17 @@ int main(int, char**) } // Resize swap chain? - if (g_SwapChainRebuild && g_SwapChainResizeWidth > 0 && g_SwapChainResizeHeight > 0) + if (g_SwapChainRebuild) { - g_SwapChainRebuild = false; - ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); - ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount); - g_MainWindowData.FrameIndex = 0; + int width, height; + SDL_GetWindowSize(window, &width, &height); + if (width > 0 && height > 0) + { + ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); + ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + g_MainWindowData.FrameIndex = 0; + g_SwapChainRebuild = false; + } } // Start the Dear ImGui frame @@ -512,7 +521,7 @@ int main(int, char**) { memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float)); FrameRender(wd, draw_data); - FramePresent(wd, window); + FramePresent(wd); } } From 8db94cd99283b0af971f95d372ac6be273fe79c6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 3 Sep 2020 16:11:01 +0200 Subject: [PATCH 244/959] Internals: Scroll related, comments & shallow tweaks. --- imgui.cpp | 58 ++++++++++++++++++++++++++---------------------- imgui_internal.h | 8 +++---- 2 files changed, 36 insertions(+), 30 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e0a15289..e133fd1a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7368,16 +7368,16 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) ImVec2 scroll = window->Scroll; if (window->ScrollTarget.x < FLT_MAX) { - float cr_x = window->ScrollTargetCenterRatio.x; - float target_x = window->ScrollTarget.x; - scroll.x = target_x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x); + float center_x_ratio = window->ScrollTargetCenterRatio.x; + float scroll_target_x = window->ScrollTarget.x; + scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - window->ScrollbarSizes.x); } if (window->ScrollTarget.y < FLT_MAX) { float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); - float cr_y = window->ScrollTargetCenterRatio.y; - float target_y = window->ScrollTarget.y; - scroll.y = target_y - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height); + float center_y_ratio = window->ScrollTargetCenterRatio.y; + float scroll_target_y = window->ScrollTarget.y; + scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height); } scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f)); scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f)); @@ -7443,38 +7443,44 @@ float ImGui::GetScrollMaxY() return window->ScrollMax.y; } -void ImGui::SetScrollX(float scroll_x) +void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x) { - ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.x = scroll_x; window->ScrollTargetCenterRatio.x = 0.0f; } -void ImGui::SetScrollY(float scroll_y) +void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y) { - ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.y = scroll_y; window->ScrollTargetCenterRatio.y = 0.0f; } -void ImGui::SetScrollX(ImGuiWindow* window, float new_scroll_x) +void ImGui::SetScrollX(float scroll_x) { - window->ScrollTarget.x = new_scroll_x; - window->ScrollTargetCenterRatio.x = 0.0f; + ImGuiContext& g = *GImGui; + SetScrollX(g.CurrentWindow, scroll_x); } -void ImGui::SetScrollY(ImGuiWindow* window, float new_scroll_y) +void ImGui::SetScrollY(float scroll_y) { - window->ScrollTarget.y = new_scroll_y; - window->ScrollTargetCenterRatio.y = 0.0f; + ImGuiContext& g = *GImGui; + SetScrollY(g.CurrentWindow, scroll_y); } -// Note that a local position will vary depending on initial scroll value -// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size +// Note that a local position will vary depending on initial scroll value, +// This is a little bit confusing so bear with us: +// - local_pos = (absolution_pos - window->Pos) +// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window, +// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area. +// - They mostly exists because of legacy API. +// Following the rules above, when trying to work with scrolling code, consider that: +// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect! +// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense +// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio) { IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); - window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); + window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset window->ScrollTargetCenterRatio.x = center_x_ratio; } @@ -7482,7 +7488,7 @@ void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y { IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect - window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); + window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset window->ScrollTargetCenterRatio.y = center_y_ratio; } @@ -7517,15 +7523,15 @@ void ImGui::SetScrollHereX(float center_x_ratio) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float spacing_x = g.Style.ItemSpacing.x; - float target_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio); + float target_pos_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio); // Tweak: snap on edges when aiming at an item very close to the edge const float snap_x_threshold = ImMax(0.0f, window->WindowPadding.x - spacing_x); const float snap_x_min = window->DC.CursorStartPos.x - window->WindowPadding.x; const float snap_x_max = window->DC.CursorStartPos.x + window->ContentSize.x + window->WindowPadding.x; - target_x = CalcScrollSnap(target_x, snap_x_min, snap_x_max, snap_x_threshold, center_x_ratio); + target_pos_x = CalcScrollSnap(target_pos_x, snap_x_min, snap_x_max, snap_x_threshold, center_x_ratio); - SetScrollFromPosX(window, target_x - window->Pos.x, center_x_ratio); + SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos } // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. @@ -7534,15 +7540,15 @@ void ImGui::SetScrollHereY(float center_y_ratio) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float spacing_y = g.Style.ItemSpacing.y; - float target_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); + float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); // Tweak: snap on edges when aiming at an item very close to the edge const float snap_y_threshold = ImMax(0.0f, window->WindowPadding.y - spacing_y); const float snap_y_min = window->DC.CursorStartPos.y - window->WindowPadding.y; const float snap_y_max = window->DC.CursorStartPos.y + window->ContentSize.y + window->WindowPadding.y; - target_y = CalcScrollSnap(target_y, snap_y_min, snap_y_max, snap_y_threshold, center_y_ratio); + target_pos_y = CalcScrollSnap(target_pos_y, snap_y_min, snap_y_max, snap_y_threshold, center_y_ratio); - SetScrollFromPosY(window, target_y - window->Pos.y, center_y_ratio); + SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos } //----------------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index 1eed0d5b..b147c5a2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1826,10 +1826,10 @@ namespace ImGui // Scrolling IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // Use -1.0f on one axis to leave as-is - IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x); - IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y); - IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio = 0.5f); - IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio = 0.5f); + IMGUI_API void SetScrollX(ImGuiWindow* window, float scroll_x); + IMGUI_API void SetScrollY(ImGuiWindow* window, float scroll_y); + IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio); + IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio); IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect); // Basic Accessors From 70289ab42ca01fccc4c3d18a6ce880cd79b203e4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 3 Sep 2020 17:38:51 +0200 Subject: [PATCH 245/959] Scrolling: Fixed edge snapping being applied prior to knowing ContentSize. (#3452) Fix 473a01adb. --- imgui.cpp | 54 ++++++++++++++++++++++++++---------------------- imgui_internal.h | 1 + 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e133fd1a..ecb3d7be 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -7363,6 +7363,19 @@ void ImGui::EndGroup() // [SECTION] SCROLLING //----------------------------------------------------------------------------- +// Helper to snap on edges when aiming at an item very close to the edge, +// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +// When we refactor the scrolling API this may be configurable with a flag? +// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. +static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio) +{ + if (target <= snap_min + snap_threshold) + return ImLerp(snap_min, target, center_ratio); + if (target >= snap_max - snap_threshold) + return ImLerp(target, snap_max, center_ratio); + return target; +} + static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) { ImVec2 scroll = window->Scroll; @@ -7370,6 +7383,10 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) { float center_x_ratio = window->ScrollTargetCenterRatio.x; float scroll_target_x = window->ScrollTarget.x; + float snap_x_min = 0.0f; + float snap_x_max = window->ScrollMax.x + window->Size.x; + if (window->ScrollTargetEdgeSnapDist.x > 0.0f) + scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio); scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - window->ScrollbarSizes.x); } if (window->ScrollTarget.y < FLT_MAX) @@ -7377,6 +7394,10 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); float center_y_ratio = window->ScrollTargetCenterRatio.y; float scroll_target_y = window->ScrollTarget.y; + float snap_y_min = 0.0f; + float snap_y_max = window->ScrollMax.y + window->Size.y - decoration_up_height; + if (window->ScrollTargetEdgeSnapDist.y > 0.0f) + scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio); scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height); } scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f)); @@ -7447,12 +7468,14 @@ void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x) { window->ScrollTarget.x = scroll_x; window->ScrollTargetCenterRatio.x = 0.0f; + window->ScrollTargetEdgeSnapDist.x = 0.0f; } void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y) { window->ScrollTarget.y = scroll_y; window->ScrollTargetCenterRatio.y = 0.0f; + window->ScrollTargetEdgeSnapDist.y = 0.0f; } void ImGui::SetScrollX(float scroll_x) @@ -7482,6 +7505,7 @@ void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset window->ScrollTargetCenterRatio.x = center_x_ratio; + window->ScrollTargetEdgeSnapDist.x = 0.0f; } void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio) @@ -7490,6 +7514,7 @@ void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset window->ScrollTargetCenterRatio.y = center_y_ratio; + window->ScrollTargetEdgeSnapDist.y = 0.0f; } void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) @@ -7504,19 +7529,6 @@ void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio); } -// Tweak: snap on edges when aiming at an item very close to the edge, -// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. -// When we refactor the scrolling API this may be configurable with a flag? -// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. -static float CalcScrollSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio) -{ - if (target <= snap_min + snap_threshold) - return ImLerp(snap_min, target, center_ratio); - if (target >= snap_max - snap_threshold) - return ImLerp(target, snap_max, center_ratio); - return target; -} - // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. void ImGui::SetScrollHereX(float center_x_ratio) { @@ -7524,14 +7536,10 @@ void ImGui::SetScrollHereX(float center_x_ratio) ImGuiWindow* window = g.CurrentWindow; float spacing_x = g.Style.ItemSpacing.x; float target_pos_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio); + SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos // Tweak: snap on edges when aiming at an item very close to the edge - const float snap_x_threshold = ImMax(0.0f, window->WindowPadding.x - spacing_x); - const float snap_x_min = window->DC.CursorStartPos.x - window->WindowPadding.x; - const float snap_x_max = window->DC.CursorStartPos.x + window->ContentSize.x + window->WindowPadding.x; - target_pos_x = CalcScrollSnap(target_pos_x, snap_x_min, snap_x_max, snap_x_threshold, center_x_ratio); - - SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos + window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x); } // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. @@ -7541,14 +7549,10 @@ void ImGui::SetScrollHereY(float center_y_ratio) ImGuiWindow* window = g.CurrentWindow; float spacing_y = g.Style.ItemSpacing.y; float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); + SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos // Tweak: snap on edges when aiming at an item very close to the edge - const float snap_y_threshold = ImMax(0.0f, window->WindowPadding.y - spacing_y); - const float snap_y_min = window->DC.CursorStartPos.y - window->WindowPadding.y; - const float snap_y_max = window->DC.CursorStartPos.y + window->ContentSize.y + window->WindowPadding.y; - target_pos_y = CalcScrollSnap(target_pos_y, snap_y_min, snap_y_max, snap_y_threshold, center_y_ratio); - - SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos + window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y); } //----------------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index b147c5a2..f6655bd5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1585,6 +1585,7 @@ struct IMGUI_API ImGuiWindow ImVec2 ScrollMax; ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered + ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar. bool ScrollbarX, ScrollbarY; // Are scrollbars visible? bool Active; // Set to true on Begin(), unless Collapsed From 751d153ca9f338ec7159e7a250abe198b6a17d73 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 3 Sep 2020 19:09:57 +0200 Subject: [PATCH 246/959] InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454). --- docs/CHANGELOG.txt | 3 +++ imgui_demo.cpp | 4 ++-- imgui_widgets.cpp | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 032360ad..8f9aa012 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -40,12 +40,15 @@ Other Changes: - Window: Fixed using non-zero pivot in SetNextWindowPos() when the window is collapsed. (#3433) - Nav: Fixed navigation resuming on first visible item when using gamepad. [@rokups] - Nav: Fixed using Alt to toggle the Menu layer when inside a Modal window. (#787) +- Scrolling: Fixed SetScrollHere functions edge snapping when called during a frame where ContentSize + is changing (issue introduced in 1.78). (#3452). - InputText: Added selection helpers in ImGuiInputTextCallbackData(). - InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active). - InputText: Fixed using ImGuiInputTextFlags_Password with InputTextMultiline(). (#3427, #3428) It is a rather unusual or useless combination of features but no reason it shouldn't work! +- InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454). - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 05bb729a..9d0929a2 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4209,9 +4209,9 @@ struct ExampleAppConsole } ImGui::TextWrapped( - "This example implements a console with basic coloring, completion and history. A more elaborate " + "This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate " "implementation may want to store entries along with extra data such as timestamp, emitter, etc."); - ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); + ImGui::TextWrapped("Enter 'HELP' for help."); // TODO: display items starting from the bottom diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eb5e4ad9..ba84c934 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3620,7 +3620,7 @@ void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) *dst++ = c; *dst = '\0'; - if (CursorPos + bytes_count >= pos) + if (CursorPos >= pos + bytes_count) CursorPos -= bytes_count; else if (CursorPos >= pos) CursorPos = pos; From aa8e09d7f1481641792e3bb6419acda896af62ae Mon Sep 17 00:00:00 2001 From: Doug Binks Date: Fri, 4 Sep 2020 16:26:31 +0100 Subject: [PATCH 247/959] Backends: GLFW: workaround for cases where glfwGetMonitorWorkarea fails (#3457) --- examples/imgui_impl_glfw.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index e7dc10ca..caded5c4 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -442,16 +442,16 @@ static void ImGui_ImplGlfw_UpdateMonitors() int x, y; glfwGetMonitorPos(glfw_monitors[n], &x, &y); const GLFWvidmode* vid_mode = glfwGetVideoMode(glfw_monitors[n]); + monitor.MainPos = monitor.WorkPos = ImVec2((float)x, (float)y); + monitor.MainSize = monitor.WorkSize = ImVec2((float)vid_mode->width, (float)vid_mode->height); #if GLFW_HAS_MONITOR_WORK_AREA - monitor.MainPos = ImVec2((float)x, (float)y); - monitor.MainSize = ImVec2((float)vid_mode->width, (float)vid_mode->height); int w, h; glfwGetMonitorWorkarea(glfw_monitors[n], &x, &y, &w, &h); - monitor.WorkPos = ImVec2((float)x, (float)y);; - monitor.WorkSize = ImVec2((float)w, (float)h); -#else - monitor.MainPos = monitor.WorkPos = ImVec2((float)x, (float)y); - monitor.MainSize = monitor.WorkSize = ImVec2((float)vid_mode->width, (float)vid_mode->height); + if (w > 0 && h > 0) // Workaround a small GLFW issue reporting zero on monitor changes: https://github.com/glfw/glfw/pull/1761 + { + monitor.WorkPos = ImVec2((float)x, (float)y); + 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. From b25756be4aa618d2d827363fc7d9014abe23df8e Mon Sep 17 00:00:00 2001 From: Michel Lesoinne Date: Fri, 8 May 2020 17:58:05 -0600 Subject: [PATCH 248/959] Examples: Vulkan: Switch validation layer. Fix CMakeLists to find Vulkan the standard way. (#3459) --- docs/CHANGELOG.txt | 2 ++ examples/example_glfw_vulkan/CMakeLists.txt | 8 +++++--- examples/example_glfw_vulkan/main.cpp | 5 ++--- examples/example_sdl_vulkan/main.cpp | 5 ++--- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8f9aa012..515b0ff1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,8 @@ Other Changes: - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] +- Examples: Vulkan: Switch validation layer to use "VK_LAYER_KHRONOS_validation" instead of + "VK_LAYER_LUNARG_standard_validation" which is deprecated (#3459) [@FunMiles] ----------------------------------------------------------------------- diff --git a/examples/example_glfw_vulkan/CMakeLists.txt b/examples/example_glfw_vulkan/CMakeLists.txt index 68155ec8..023d791b 100644 --- a/examples/example_glfw_vulkan/CMakeLists.txt +++ b/examples/example_glfw_vulkan/CMakeLists.txt @@ -28,9 +28,11 @@ set(IMGUI_DIR ../../) include_directories(${IMGUI_DIR} ..) # Libraries -find_library(VULKAN_LIBRARY - NAMES vulkan vulkan-1) -set(LIBRARIES "glfw;${VULKAN_LIBRARY}") +find_package(Vulkan REQUIRED) +#find_library(VULKAN_LIBRARY + #NAMES vulkan vulkan-1) +#set(LIBRARIES "glfw;${VULKAN_LIBRARY}") +set(LIBRARIES "glfw;Vulkan::Vulkan") # Use vulkan headers from glfw: include_directories(${GLFW_DIR}/deps) diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 6dc2e6cf..5e5f7323 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -72,10 +72,9 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; create_info.enabledExtensionCount = extensions_count; create_info.ppEnabledExtensionNames = extensions; - #ifdef IMGUI_VULKAN_DEBUG_REPORT - // Enabling multiple validation layers grouped as LunarG standard validation - const char* layers[] = { "VK_LAYER_LUNARG_standard_validation" }; + // Enabling validation layers + const char* layers[] = { "VK_LAYER_KHRONOS_validation" }; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = layers; diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index b22e4247..03d7ded3 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -64,10 +64,9 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; create_info.enabledExtensionCount = extensions_count; create_info.ppEnabledExtensionNames = extensions; - #ifdef IMGUI_VULKAN_DEBUG_REPORT - // Enabling multiple validation layers grouped as LunarG standard validation - const char* layers[] = { "VK_LAYER_LUNARG_standard_validation" }; + // Enabling validation layers + const char* layers[] = { "VK_LAYER_KHRONOS_validation" }; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = layers; From 6461fd40ab815e14358923d4ffabbb8c40d8d049 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 7 Sep 2020 12:19:50 +0200 Subject: [PATCH 249/959] Examples: Fixed SDL+OpenGL2 and SDL+Vulkan examples not processing SDL_WINDOWEVENT_CLOSE events which tends to be needed in multi-viewport setting. --- examples/example_sdl_opengl2/main.cpp | 2 ++ examples/example_sdl_vulkan/main.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index fcd9ae32..34ea80d0 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -87,6 +87,8 @@ int main(int, char**) ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; + if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) + done = true; } // Start the Dear ImGui frame diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index 03d7ded3..c6ce12a1 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -454,6 +454,8 @@ int main(int, char**) ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; + if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) + done = true; } // Resize swap chain? From b2039aac671bde42cbcc95de34e73419857fba68 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 7 Sep 2020 17:38:56 +0200 Subject: [PATCH 250/959] Slider: Fixed to reach maximum value with inverted integer min/max ranges, both with signed and unsigned types. Added reverse Sliders to Demo. (#3432, #3449) --- imgui_demo.cpp | 10 +++++++++- imgui_internal.h | 4 ++-- imgui_widgets.cpp | 42 +++++++++++++++++++++++------------------- 3 files changed, 34 insertions(+), 22 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9d0929a2..c7ab4310 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -617,7 +617,7 @@ static void ShowDemoWindowWidgets() "Hold SHIFT/ALT for faster/slower edit.\n" "Double-click or CTRL+click to input value."); - ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%"); + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_ClampOnInput); static float f1 = 1.00f, f2 = 0.0067f; ImGui::DragFloat("drag float", &f1, 0.005f); @@ -1688,6 +1688,14 @@ static void ShowDemoWindowWidgets() ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic); ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams"); + ImGui::Text("Sliders (reverse)"); + ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d"); + ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u"); + ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d"); + ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u"); + ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%I64d"); + ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%I64u ms"); + static bool inputs_step = true; ImGui::Text("Inputs"); ImGui::Checkbox("Show step buttons", &inputs_step); diff --git a/imgui_internal.h b/imgui_internal.h index f6655bd5..aceeebca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1997,8 +1997,8 @@ namespace ImGui // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, float v); " - template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); - template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); + template IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags); template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ba84c934..b0cf70bc 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2094,9 +2094,9 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision); // Convert to parametric space, apply delta, convert back - float v_old_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + float v_old_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); float v_new_parametric = v_old_parametric + g.DragCurrentAccum; - v_cur = ScaleValueFromRatioT(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + v_cur = ScaleValueFromRatioT(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); v_old_ref_for_accum_remainder = v_old_parametric; } else @@ -2113,7 +2113,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_logarithmic) { // Convert to parametric space, apply delta, convert back - float v_new_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + float v_new_parametric = ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder); } else @@ -2449,7 +2449,7 @@ bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data //------------------------------------------------------------------------- // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) -template +template float ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) { if (v_min == v_max) @@ -2501,11 +2501,11 @@ float ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, T } // Linear slider - return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); + return (float)((FLOATTYPE)(SIGNEDTYPE)(v_clamped - v_min) / (FLOATTYPE)(SIGNEDTYPE)(v_max - v_min)); } // Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT) -template +template TYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize) { if (v_min == v_max) @@ -2564,15 +2564,19 @@ TYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, T } else { - // For integer values we want the clicking position to match the grab box so we round above - // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. - FLOATTYPE v_new_off_f = (v_max - v_min) * t; - TYPE v_new_off_floor = (TYPE)(v_new_off_f); - TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5); - if (v_new_off_floor < v_new_off_round) - result = v_min + v_new_off_round; + // - For integer values we want the clicking position to match the grab box so we round above + // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + // - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 + // range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. + if (t < 1.0) + { + FLOATTYPE v_new_off_f = (SIGNEDTYPE)(v_max - v_min) * t; + result = (TYPE)((SIGNEDTYPE)v_min + (SIGNEDTYPE)(v_new_off_f + (FLOATTYPE)(v_min > v_max ? -0.5 : 0.5))); + } else - result = v_min + v_new_off_floor; + { + result = v_max; + } } } @@ -2672,7 +2676,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ } else if (g.SliderCurrentAccumDirty) { - clicked_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + clicked_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits { @@ -2686,10 +2690,10 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ clicked_t = ImSaturate(clicked_t + delta); // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator - TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) v_new = RoundScalarWithFormatT(format, data_type, v_new); - float new_clicked_t = ScaleRatioFromValueT(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + float new_clicked_t = ScaleRatioFromValueT(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (delta > 0) g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta); @@ -2703,7 +2707,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ if (set_new_value) { - TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + TYPE v_new = ScaleValueFromRatioT(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); // Round to user desired precision based on format string if (!(flags & ImGuiSliderFlags_NoRoundToFormat)) @@ -2725,7 +2729,7 @@ bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_typ else { // Output grab position so it can be displayed by the caller - float grab_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); + float grab_t = ScaleRatioFromValueT(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); From 36af39805605828b1a75e781abb3b1bdc72a49f5 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 7 Sep 2020 19:52:11 +0200 Subject: [PATCH 251/959] Sliders: Fixed using ImGuiSliderFlags_ClampOnInput with reverse sliders. (#3432, #3449) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 515b0ff1..b401c0ee 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -51,6 +51,8 @@ Other Changes: - InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454). - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) +- SliderInt, SliderScalar: Fixed reaching of maximum value with inverted integer min/max ranges, both + with signed and unsigned types. Added reverse Sliders to Demo. (#3432, #3449) [@rokups] - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. - TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b0cf70bc..628d4cfd 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1942,7 +1942,7 @@ static bool DataTypeClampT(T* v, const T* v_min, const T* v_max) { // Clamp, both sides are optional, return true if modified if (v_min && *v < *v_min) { *v = *v_min; return true; } - if (v_max && *v > * v_max) { *v = *v_max; return true; } + if (v_max && *v > *v_max) { *v = *v_max; return true; } return false; } @@ -3191,7 +3191,11 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG // Apply new value (or operations) then clamp DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL); if (p_clamp_min || p_clamp_max) + { + if (DataTypeCompare(data_type, p_clamp_min, p_clamp_max) > 0) + ImSwap(p_clamp_min, p_clamp_max); DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max); + } // Only mark as edited if new value is different value_changed = memcmp(&data_backup, p_data, data_type_size) != 0; From 206d78a524bbd44e7ab611054e753bd63d5f4b20 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 8 Sep 2020 11:39:56 +0200 Subject: [PATCH 252/959] InputText: Fixed minor glitch when erasing trailing lines in InputTextMultiline(). Fixed cursor being partially covered after using Ctrl+End key. Removed unncessary one-empty-line-worth-of-scrolling. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b401c0ee..31410eda 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -48,6 +48,8 @@ Other Changes: underlying buffer while focus is active). - InputText: Fixed using ImGuiInputTextFlags_Password with InputTextMultiline(). (#3427, #3428) It is a rather unusual or useless combination of features but no reason it shouldn't work! +- InputText: Fixed minor scrolling glitch when erasing trailing lines in InputTextMultiline(). +- InputText: Fixed cursor being partially covered after using Ctrl+End key. - InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454). - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 628d4cfd..c797b1a0 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4433,11 +4433,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Vertical scroll if (is_multiline) { + // Test if cursor is vertically visible float scroll_y = draw_window->Scroll.y; + const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); if (cursor_offset.y - g.FontSize < scroll_y) scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - inner_size.y >= scroll_y) - scroll_y = cursor_offset.y - inner_size.y; + scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f; + scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y); draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; } @@ -4526,7 +4529,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_multiline) { - Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line + Dummy(text_size); EndChild(); EndGroup(); } From 8a9ee9cdedd6f729a58a29cbfcce1bf8951a18f1 Mon Sep 17 00:00:00 2001 From: HALX99 Date: Tue, 8 Sep 2020 03:18:28 -0700 Subject: [PATCH 253/959] Add const qualifier for parameter ImFontConfig of ImFont::AddGlyph (#3461) --- imgui.h | 2 +- imgui_draw.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui.h b/imgui.h index 40ffedad..71d1b20b 100644 --- a/imgui.h +++ b/imgui.h @@ -2442,7 +2442,7 @@ struct ImFont IMGUI_API void BuildLookupTable(); IMGUI_API void ClearOutputData(); IMGUI_API void GrowIndex(int new_size); - IMGUI_API void AddGlyph(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 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 SetGlyphVisible(ImWchar c, bool visible); IMGUI_API void SetFallbackChar(ImWchar c); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 5b79a449..2f87366a 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2886,7 +2886,7 @@ void ImFont::GrowIndex(int new_size) // 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). // 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font. -void ImFont::AddGlyph(ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) +void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x) { if (cfg != NULL) { From 6a546a500fb94e11c195850996575cb0d3f0e983 Mon Sep 17 00:00:00 2001 From: xndcn Date: Tue, 8 Sep 2020 11:49:30 +0800 Subject: [PATCH 254/959] ImVector: fix max_size() for signed int value. Amend 444873404 (#3429, #3460) --- imgui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.h b/imgui.h index 71d1b20b..98a65699 100644 --- a/imgui.h +++ b/imgui.h @@ -1395,7 +1395,7 @@ struct ImVector inline bool empty() const { return Size == 0; } inline int size() const { return Size; } inline int size_in_bytes() const { return Size * (int)sizeof(T); } - inline int max_size() const { return (~(unsigned int)0) / (int)sizeof(T); } + inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); } inline int capacity() const { return Capacity; } inline T& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } inline const T& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } From 41e2aa2e7af93c070d9dfd0b822a29968e752cde Mon Sep 17 00:00:00 2001 From: Michel Lesoinne Date: Tue, 8 Sep 2020 16:47:06 +0200 Subject: [PATCH 255/959] Backends: Vulkan: Separate the pipeline of the dear imgui created windows from the one created with the user's render-pass. (#3455, #3459) This is mostly for the benefit of multi-viewports. --- docs/CHANGELOG.txt | 2 + examples/imgui_impl_vulkan.cpp | 259 +++++++++++++++++++++++---------- examples/imgui_impl_vulkan.h | 3 +- 3 files changed, 183 insertions(+), 81 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 31410eda..9cec4446 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -66,6 +66,8 @@ Other Changes: tabs reordered in the tab list popup. [@Xipiryon] - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). +- Backends: Vulkan: Some internal refactor aimed at allowing multi-viewport feature to create their + own render pass. (#3455, #3459) [@FunMiles] - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] - Examples: Vulkan: Switch validation layer to use "VK_LAYER_KHRONOS_validation" instead of "VK_LAYER_LUNARG_standard_validation" which is deprecated (#3459) [@FunMiles] diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 465060d5..c47d5aab 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-09-07: Vulkan: Added VkPipeline parameter to ImGui_ImplVulkan_RenderDrawData (default to one passed to ImGui_ImplVulkan_Init). // 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices. // 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. // 2019-08-01: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. @@ -80,6 +81,8 @@ static VkDescriptorSetLayout g_DescriptorSetLayout = VK_NULL_HANDLE; static VkPipelineLayout g_PipelineLayout = VK_NULL_HANDLE; static VkDescriptorSet g_DescriptorSet = VK_NULL_HANDLE; static VkPipeline g_Pipeline = VK_NULL_HANDLE; +static VkShaderModule g_ShaderModuleVert; +static VkShaderModule g_ShaderModuleFrag; // Font data static VkSampler g_FontSampler = VK_NULL_HANDLE; @@ -266,11 +269,11 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory p_buffer_size = new_size; } -static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkCommandBuffer command_buffer, ImGui_ImplVulkanH_FrameRenderBuffers* rb, int fb_width, int fb_height) +static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkanH_FrameRenderBuffers* rb, int fb_width, int fb_height) { // Bind pipeline and descriptor sets: { - vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_Pipeline); + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); VkDescriptorSet desc_set[1] = { g_DescriptorSet }; vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, g_PipelineLayout, 0, 1, desc_set, 0, NULL); } @@ -312,7 +315,7 @@ static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkCommandBu // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) -void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer) +void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); @@ -321,6 +324,8 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm return; ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; + if (pipeline == VK_NULL_HANDLE) + pipeline = g_Pipeline; // Allocate array to store enough vertex/index buffers ImGui_ImplVulkanH_WindowRenderBuffers* wrb = &g_MainWindowRenderBuffers; @@ -374,7 +379,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm } // Setup desired Vulkan state - ImGui_ImplVulkan_SetupRenderState(draw_data, command_buffer, rb, fb_width, fb_height); + ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports @@ -395,7 +400,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - ImGui_ImplVulkan_SetupRenderState(draw_data, command_buffer, rb, fb_width, fb_height); + ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height); else pcmd->UserCallback(cmd_list, pcmd); } @@ -586,99 +591,103 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) return true; } -bool ImGui_ImplVulkan_CreateDeviceObjects() +static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator) { - ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; - VkResult err; - VkShaderModule vert_module; - VkShaderModule frag_module; - - // Create The Shader Modules: + // Create the shader modules + if (g_ShaderModuleVert == NULL) { VkShaderModuleCreateInfo vert_info = {}; vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; vert_info.codeSize = sizeof(__glsl_shader_vert_spv); vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; - err = vkCreateShaderModule(v->Device, &vert_info, v->Allocator, &vert_module); + VkResult err = vkCreateShaderModule(device, &vert_info, allocator, &g_ShaderModuleVert); check_vk_result(err); + } + if (g_ShaderModuleFrag == NULL) + { VkShaderModuleCreateInfo frag_info = {}; frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; frag_info.codeSize = sizeof(__glsl_shader_frag_spv); frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; - err = vkCreateShaderModule(v->Device, &frag_info, v->Allocator, &frag_module); + VkResult err = vkCreateShaderModule(device, &frag_info, allocator, &g_ShaderModuleFrag); check_vk_result(err); } +} - if (!g_FontSampler) - { - VkSamplerCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - info.magFilter = VK_FILTER_LINEAR; - info.minFilter = VK_FILTER_LINEAR; - info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; - info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; - info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; - info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; - info.minLod = -1000; - info.maxLod = 1000; - info.maxAnisotropy = 1.0f; - err = vkCreateSampler(v->Device, &info, v->Allocator, &g_FontSampler); - check_vk_result(err); - } +static void ImGui_ImplVulkan_CreateFontSampler(VkDevice device, const VkAllocationCallbacks* allocator) +{ + if (g_FontSampler) + return; - if (!g_DescriptorSetLayout) - { - VkSampler sampler[1] = {g_FontSampler}; - VkDescriptorSetLayoutBinding binding[1] = {}; - binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - binding[0].descriptorCount = 1; - binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - binding[0].pImmutableSamplers = sampler; - VkDescriptorSetLayoutCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - info.bindingCount = 1; - info.pBindings = binding; - err = vkCreateDescriptorSetLayout(v->Device, &info, v->Allocator, &g_DescriptorSetLayout); - check_vk_result(err); - } + VkSamplerCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + info.magFilter = VK_FILTER_LINEAR; + info.minFilter = VK_FILTER_LINEAR; + info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.minLod = -1000; + info.maxLod = 1000; + info.maxAnisotropy = 1.0f; + VkResult err = vkCreateSampler(device, &info, allocator, &g_FontSampler); + check_vk_result(err); +} - // Create Descriptor Set: - { - VkDescriptorSetAllocateInfo alloc_info = {}; - alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - alloc_info.descriptorPool = v->DescriptorPool; - alloc_info.descriptorSetCount = 1; - alloc_info.pSetLayouts = &g_DescriptorSetLayout; - err = vkAllocateDescriptorSets(v->Device, &alloc_info, &g_DescriptorSet); - check_vk_result(err); - } +static void ImGui_ImplVulkan_CreateDescriptorSetLayout(VkDevice device, const VkAllocationCallbacks* allocator) +{ + if (g_DescriptorSetLayout) + return; - if (!g_PipelineLayout) - { - // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix - VkPushConstantRange push_constants[1] = {}; - push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; - push_constants[0].offset = sizeof(float) * 0; - push_constants[0].size = sizeof(float) * 4; - VkDescriptorSetLayout set_layout[1] = { g_DescriptorSetLayout }; - VkPipelineLayoutCreateInfo layout_info = {}; - layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - layout_info.setLayoutCount = 1; - layout_info.pSetLayouts = set_layout; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = push_constants; - err = vkCreatePipelineLayout(v->Device, &layout_info, v->Allocator, &g_PipelineLayout); - check_vk_result(err); - } + ImGui_ImplVulkan_CreateFontSampler(device, allocator); + VkSampler sampler[1] = { g_FontSampler }; + VkDescriptorSetLayoutBinding binding[1] = {}; + binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding[0].descriptorCount = 1; + binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + binding[0].pImmutableSamplers = sampler; + VkDescriptorSetLayoutCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + info.bindingCount = 1; + info.pBindings = binding; + VkResult err = vkCreateDescriptorSetLayout(device, &info, allocator, &g_DescriptorSetLayout); + check_vk_result(err); +} + +static void ImGui_ImplVulkan_CreatePipelineLayout(VkDevice device, const VkAllocationCallbacks* allocator) +{ + if (g_PipelineLayout) + return; + + // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix + ImGui_ImplVulkan_CreateDescriptorSetLayout(device, allocator); + VkPushConstantRange push_constants[1] = {}; + push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + push_constants[0].offset = sizeof(float) * 0; + push_constants[0].size = sizeof(float) * 4; + VkDescriptorSetLayout set_layout[1] = { g_DescriptorSetLayout }; + VkPipelineLayoutCreateInfo layout_info = {}; + layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = set_layout; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = push_constants; + VkResult err = vkCreatePipelineLayout(device, &layout_info, allocator, &g_PipelineLayout); + check_vk_result(err); +} + +static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline *pipeline) +{ + ImGui_ImplVulkan_CreateShaderModules(device, allocator); VkPipelineShaderStageCreateInfo stage[2] = {}; stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT; - stage[0].module = vert_module; + stage[0].module = g_ShaderModuleVert; stage[0].pName = "main"; stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; - stage[1].module = frag_module; + stage[1].module = g_ShaderModuleFrag; stage[1].pName = "main"; VkVertexInputBindingDescription binding_desc[1] = {}; @@ -724,10 +733,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() VkPipelineMultisampleStateCreateInfo ms_info = {}; ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; - if (v->MSAASamples != 0) - ms_info.rasterizationSamples = v->MSAASamples; - else - ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState color_attachment[1] = {}; color_attachment[0].blendEnable = VK_TRUE; @@ -753,6 +759,8 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states); dynamic_state.pDynamicStates = dynamic_states; + ImGui_ImplVulkan_CreatePipelineLayout(device, allocator); + VkGraphicsPipelineCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; info.flags = g_PipelineCreateFlags; @@ -767,9 +775,97 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() info.pColorBlendState = &blend_info; info.pDynamicState = &dynamic_state; info.layout = g_PipelineLayout; - info.renderPass = g_RenderPass; - err = vkCreateGraphicsPipelines(v->Device, v->PipelineCache, 1, &info, v->Allocator, &g_Pipeline); + info.renderPass = renderPass; + VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline); check_vk_result(err); +} + +bool ImGui_ImplVulkan_CreateDeviceObjects() +{ + ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; + VkResult err; + VkShaderModule vert_module; + VkShaderModule frag_module; + + // Create The Shader Modules: + { + VkShaderModuleCreateInfo vert_info = {}; + vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + vert_info.codeSize = sizeof(__glsl_shader_vert_spv); + vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; + err = vkCreateShaderModule(v->Device, &vert_info, v->Allocator, &vert_module); + check_vk_result(err); + VkShaderModuleCreateInfo frag_info = {}; + frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + frag_info.codeSize = sizeof(__glsl_shader_frag_spv); + frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; + err = vkCreateShaderModule(v->Device, &frag_info, v->Allocator, &frag_module); + check_vk_result(err); + } + + if (!g_FontSampler) + { + VkSamplerCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + info.magFilter = VK_FILTER_LINEAR; + info.minFilter = VK_FILTER_LINEAR; + info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + info.minLod = -1000; + info.maxLod = 1000; + info.maxAnisotropy = 1.0f; + err = vkCreateSampler(v->Device, &info, v->Allocator, &g_FontSampler); + check_vk_result(err); + } + + if (!g_DescriptorSetLayout) + { + VkSampler sampler[1] = {g_FontSampler}; + VkDescriptorSetLayoutBinding binding[1] = {}; + binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding[0].descriptorCount = 1; + binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + binding[0].pImmutableSamplers = sampler; + VkDescriptorSetLayoutCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + info.bindingCount = 1; + info.pBindings = binding; + err = vkCreateDescriptorSetLayout(v->Device, &info, v->Allocator, &g_DescriptorSetLayout); + check_vk_result(err); + } + + // Create Descriptor Set: + { + VkDescriptorSetAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc_info.descriptorPool = v->DescriptorPool; + alloc_info.descriptorSetCount = 1; + alloc_info.pSetLayouts = &g_DescriptorSetLayout; + err = vkAllocateDescriptorSets(v->Device, &alloc_info, &g_DescriptorSet); + check_vk_result(err); + } + + if (!g_PipelineLayout) + { + // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix + VkPushConstantRange push_constants[1] = {}; + push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + push_constants[0].offset = sizeof(float) * 0; + push_constants[0].size = sizeof(float) * 4; + VkDescriptorSetLayout set_layout[1] = { g_DescriptorSetLayout }; + VkPipelineLayoutCreateInfo layout_info = {}; + layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = set_layout; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = push_constants; + err = vkCreatePipelineLayout(v->Device, &layout_info, v->Allocator, &g_PipelineLayout); + check_vk_result(err); + } + + ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, g_RenderPass, v->MSAASamples, &g_Pipeline); vkDestroyShaderModule(v->Device, vert_module, v->Allocator); vkDestroyShaderModule(v->Device, frag_module, v->Allocator); @@ -1017,6 +1113,8 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V wd->ImageCount = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); + if (wd->Pipeline) + vkDestroyPipeline(device, wd->Pipeline, allocator); // If min image count was not specified, request different count of images dependent on selected present mode if (min_image_count == 0) @@ -1112,6 +1210,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V info.pDependencies = &dependency; err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass); check_vk_result(err); + ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); } // Create The Image Views diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 0eb772e7..951574cd 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -46,7 +46,7 @@ struct ImGui_ImplVulkan_InitInfo IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); -IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); +IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) @@ -108,6 +108,7 @@ struct ImGui_ImplVulkanH_Window VkSurfaceFormatKHR SurfaceFormat; VkPresentModeKHR PresentMode; VkRenderPass RenderPass; + VkPipeline Pipeline; // The window pipeline uses a different VkRenderPass than the user's bool ClearEnable; VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) From d8d58b038eb22e3d8f2591efcb228a5a1dfee291 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 8 Sep 2020 20:02:28 +0200 Subject: [PATCH 256/959] Backends, Examples: DX12: Clarify support for 32-bit building in project files and comments. (#301) --- docs/CHANGELOG.txt | 4 ++ .../example_win32_directx12/build_win32.bat | 3 +- .../example_win32_directx12.vcxproj | 4 ++ examples/imgui_examples.sln | 42 ++++++++++++------- examples/imgui_impl_dx12.cpp | 7 +++- examples/imgui_impl_dx12.h | 6 ++- imconfig.h | 9 ++-- 7 files changed, 50 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9cec4446..092bd005 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,9 +68,13 @@ Other Changes: - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Backends: Vulkan: Some internal refactor aimed at allowing multi-viewport feature to create their own render pass. (#3455, #3459) [@FunMiles] +- Backends: DX12: Clarified that imgui_impl_dx12 can be compiled on 32-bit systems by redefining + the ImTextureID to be 64-bit (e.g. '#define ImTextureID ImU64' in imconfig.h). (#301) - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] - Examples: Vulkan: Switch validation layer to use "VK_LAYER_KHRONOS_validation" instead of "VK_LAYER_LUNARG_standard_validation" which is deprecated (#3459) [@FunMiles] +- Examples: DX12: Added '#define ImTextureID ImU64' in project and build files to also allow building + on 32-bit systems. Added project to default Visual Studio solution file. (#301) ----------------------------------------------------------------------- diff --git a/examples/example_win32_directx12/build_win32.bat b/examples/example_win32_directx12/build_win32.bat index 2cd7fcdf..85a52b70 100644 --- a/examples/example_win32_directx12/build_win32.bat +++ b/examples/example_win32_directx12/build_win32.bat @@ -1,4 +1,5 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@REM Important: to build on 32-bit systems, the DX12 back-ends needs '#define ImTextureID ImU64', so we pass it here. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /D UNICODE /D _UNICODE *.cpp ..\imgui_impl_dx12.cpp ..\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx12.exe /FoDebug/ /link d3d12.lib d3dcompiler.lib dxgi.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /D ImTextureID=ImU64 /D UNICODE /D _UNICODE *.cpp ..\imgui_impl_dx12.cpp ..\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx12.exe /FoDebug/ /link d3d12.lib d3dcompiler.lib dxgi.lib diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj index dabd6d84..f03bf760 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj @@ -87,6 +87,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) true @@ -100,6 +101,7 @@ Level4 Disabled ..\..;..;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) true @@ -115,6 +117,7 @@ true true ..\..;..;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) true @@ -132,6 +135,7 @@ true true ..\..;..;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) true diff --git a/examples/imgui_examples.sln b/examples/imgui_examples.sln index 49b2ff89..605b1f57 100644 --- a/examples/imgui_examples.sln +++ b/examples/imgui_examples.sln @@ -13,6 +13,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_glfw_opengl2", "exa EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_glfw_opengl3", "example_glfw_opengl3\example_glfw_opengl3.vcxproj", "{4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_directx12", "example_win32_directx12\example_win32_directx12.vcxproj", "{B4CF9797-519D-4AFE-A8F4-5141A6B521D3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -21,14 +23,6 @@ Global Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.ActiveCfg = Debug|Win32 - {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.Build.0 = Debug|Win32 - {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|x64.ActiveCfg = Debug|x64 - {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|x64.Build.0 = Debug|x64 - {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.ActiveCfg = Release|Win32 - {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.Build.0 = Release|Win32 - {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|x64.ActiveCfg = Release|x64 - {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|x64.Build.0 = Release|x64 {4165A294-21F2-44CA-9B38-E3F935ABADF5}.Debug|Win32.ActiveCfg = Debug|Win32 {4165A294-21F2-44CA-9B38-E3F935ABADF5}.Debug|Win32.Build.0 = Debug|Win32 {4165A294-21F2-44CA-9B38-E3F935ABADF5}.Debug|x64.ActiveCfg = Debug|x64 @@ -37,6 +31,14 @@ Global {4165A294-21F2-44CA-9B38-E3F935ABADF5}.Release|Win32.Build.0 = Release|Win32 {4165A294-21F2-44CA-9B38-E3F935ABADF5}.Release|x64.ActiveCfg = Release|x64 {4165A294-21F2-44CA-9B38-E3F935ABADF5}.Release|x64.Build.0 = Release|x64 + {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|Win32.ActiveCfg = Debug|Win32 + {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|Win32.Build.0 = Debug|Win32 + {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|x64.ActiveCfg = Debug|x64 + {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|x64.Build.0 = Debug|x64 + {345A953E-A004-4648-B442-DC5F9F11068C}.Release|Win32.ActiveCfg = Release|Win32 + {345A953E-A004-4648-B442-DC5F9F11068C}.Release|Win32.Build.0 = Release|Win32 + {345A953E-A004-4648-B442-DC5F9F11068C}.Release|x64.ActiveCfg = Release|x64 + {345A953E-A004-4648-B442-DC5F9F11068C}.Release|x64.Build.0 = Release|x64 {9F316E83-5AE5-4939-A723-305A94F48005}.Debug|Win32.ActiveCfg = Debug|Win32 {9F316E83-5AE5-4939-A723-305A94F48005}.Debug|Win32.Build.0 = Debug|Win32 {9F316E83-5AE5-4939-A723-305A94F48005}.Debug|x64.ActiveCfg = Debug|x64 @@ -45,6 +47,14 @@ Global {9F316E83-5AE5-4939-A723-305A94F48005}.Release|Win32.Build.0 = Release|Win32 {9F316E83-5AE5-4939-A723-305A94F48005}.Release|x64.ActiveCfg = Release|x64 {9F316E83-5AE5-4939-A723-305A94F48005}.Release|x64.Build.0 = Release|x64 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.ActiveCfg = Debug|Win32 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|Win32.Build.0 = Debug|Win32 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|x64.ActiveCfg = Debug|x64 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Debug|x64.Build.0 = Debug|x64 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.ActiveCfg = Release|Win32 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|Win32.Build.0 = Release|Win32 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|x64.ActiveCfg = Release|x64 + {9CDA7840-B7A5-496D-A527-E95571496D18}.Release|x64.Build.0 = Release|x64 {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Debug|Win32.ActiveCfg = Debug|Win32 {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Debug|Win32.Build.0 = Debug|Win32 {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Debug|x64.ActiveCfg = Debug|x64 @@ -53,14 +63,14 @@ Global {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|Win32.Build.0 = Release|Win32 {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|x64.ActiveCfg = Release|x64 {4A1FB5EA-22F5-42A8-AB92-1D2DF5D47FB9}.Release|x64.Build.0 = Release|x64 - {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|Win32.ActiveCfg = Debug|Win32 - {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|Win32.Build.0 = Debug|Win32 - {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|x64.ActiveCfg = Debug|x64 - {345A953E-A004-4648-B442-DC5F9F11068C}.Debug|x64.Build.0 = Debug|x64 - {345A953E-A004-4648-B442-DC5F9F11068C}.Release|Win32.ActiveCfg = Release|Win32 - {345A953E-A004-4648-B442-DC5F9F11068C}.Release|Win32.Build.0 = Release|Win32 - {345A953E-A004-4648-B442-DC5F9F11068C}.Release|x64.ActiveCfg = Release|x64 - {345A953E-A004-4648-B442-DC5F9F11068C}.Release|x64.Build.0 = Release|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|Win32.ActiveCfg = Debug|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|Win32.Build.0 = Debug|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|x64.ActiveCfg = Debug|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Debug|x64.Build.0 = Debug|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|Win32.ActiveCfg = Release|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|Win32.Build.0 = Release|Win32 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|x64.ActiveCfg = Release|x64 + {B4CF9797-519D-4AFE-A8F4-5141A6B521D3}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index e9cd45c6..e55fdaf9 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -4,8 +4,10 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// Issues: -// [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See github.com/ocornut/imgui/pull/301 + +// Important: to compile on 32-bit systems, this back-end requires code to be compiled with '#define ImTextureID ImU64'. +// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. +// This define is done in the example .vcxproj file and need to be replicated in your app (by e.g. editing imconfig.h) // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -13,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. diff --git a/examples/imgui_impl_dx12.h b/examples/imgui_impl_dx12.h index 52dab0ba..dd77ba8c 100644 --- a/examples/imgui_impl_dx12.h +++ b/examples/imgui_impl_dx12.h @@ -4,8 +4,10 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// Issues: -// [ ] 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)). See github.com/ocornut/imgui/pull/301 + +// Important: to compile on 32-bit systems, this back-end requires code to be compiled with '#define ImTextureID ImU64'. +// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. +// This define is done in the example .vcxproj file and need to be replicated in your app (by e.g. editing imconfig.h) // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. diff --git a/imconfig.h b/imconfig.h index c6817de7..6b87dd6c 100644 --- a/imconfig.h +++ b/imconfig.h @@ -3,10 +3,11 @@ // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. //----------------------------------------------------------------------------- -// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/branch with your modifications to imconfig.h) -// B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h" -// If you do so you need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include -// the imgui*.cpp files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. +// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) +// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. +//----------------------------------------------------------------------------- +// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp +// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. //----------------------------------------------------------------------------- From e8447dea453fe11c4f7da6512b86f4e039f03261 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 8 Sep 2020 22:39:53 +0200 Subject: [PATCH 257/959] Backends: Vulkan: Removed unused shader code. Fix leaks. Avoid unnecessary pipeline creation for main viewport. Amend 41e2aa2. (#3459) --- examples/imgui_impl_vulkan.cpp | 31 ++++++++----------------------- examples/imgui_impl_vulkan.h | 2 +- 2 files changed, 9 insertions(+), 24 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index c47d5aab..c3135605 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -676,7 +676,7 @@ static void ImGui_ImplVulkan_CreatePipelineLayout(VkDevice device, const VkAlloc check_vk_result(err); } -static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline *pipeline) +static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline) { ImGui_ImplVulkan_CreateShaderModules(device, allocator); @@ -784,24 +784,6 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() { ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err; - VkShaderModule vert_module; - VkShaderModule frag_module; - - // Create The Shader Modules: - { - VkShaderModuleCreateInfo vert_info = {}; - vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - vert_info.codeSize = sizeof(__glsl_shader_vert_spv); - vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; - err = vkCreateShaderModule(v->Device, &vert_info, v->Allocator, &vert_module); - check_vk_result(err); - VkShaderModuleCreateInfo frag_info = {}; - frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - frag_info.codeSize = sizeof(__glsl_shader_frag_spv); - frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; - err = vkCreateShaderModule(v->Device, &frag_info, v->Allocator, &frag_module); - check_vk_result(err); - } if (!g_FontSampler) { @@ -867,9 +849,6 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, g_RenderPass, v->MSAASamples, &g_Pipeline); - vkDestroyShaderModule(v->Device, vert_module, v->Allocator); - vkDestroyShaderModule(v->Device, frag_module, v->Allocator); - return true; } @@ -894,6 +873,8 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &g_MainWindowRenderBuffers, v->Allocator); ImGui_ImplVulkan_DestroyFontUploadObjects(); + if (g_ShaderModuleVert) { vkDestroyShaderModule(v->Device, g_ShaderModuleVert, v->Allocator); g_ShaderModuleVert = VK_NULL_HANDLE; } + if (g_ShaderModuleFrag) { vkDestroyShaderModule(v->Device, g_ShaderModuleFrag, v->Allocator); g_ShaderModuleFrag = VK_NULL_HANDLE; } if (g_FontView) { vkDestroyImageView(v->Device, g_FontView, v->Allocator); g_FontView = VK_NULL_HANDLE; } if (g_FontImage) { vkDestroyImage(v->Device, g_FontImage, v->Allocator); g_FontImage = VK_NULL_HANDLE; } if (g_FontMemory) { vkFreeMemory(v->Device, g_FontMemory, v->Allocator); g_FontMemory = VK_NULL_HANDLE; } @@ -1210,7 +1191,10 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V info.pDependencies = &dependency; err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass); check_vk_result(err); - ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); + + // We do not create a pipeline by default as this is also used by examples' main.cpp, + // but secondary viewport in multi-viewport mode may want to create one with: + //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); } // Create The Image Views @@ -1277,6 +1261,7 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui IM_FREE(wd->FrameSemaphores); wd->Frames = NULL; wd->FrameSemaphores = NULL; + vkDestroyPipeline(device, wd->Pipeline, allocator); vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index 951574cd..d5d2516a 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -108,7 +108,7 @@ struct ImGui_ImplVulkanH_Window VkSurfaceFormatKHR SurfaceFormat; VkPresentModeKHR PresentMode; VkRenderPass RenderPass; - VkPipeline Pipeline; // The window pipeline uses a different VkRenderPass than the user's + VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo bool ClearEnable; VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) From 770c99536533923d2cf07fc5004c752ef2c63f5c Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 8 Sep 2020 22:39:53 +0200 Subject: [PATCH 258/959] Backends: Vulkan: Removed unused shader code. Fix leaks. Avoid unnecessary pipeline creation for main viewport. Amend 41e2aa2. (#3459) + Add ImGui_ImplVulkanH_CreateWindowSwapChain in ImGui_ImplVulkanH_CreateOrResizeWindow(). --- examples/imgui_impl_vulkan.cpp | 32 +++++++++----------------------- examples/imgui_impl_vulkan.h | 2 +- 2 files changed, 10 insertions(+), 24 deletions(-) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 52238ffb..1cf5c789 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -693,7 +693,7 @@ static void ImGui_ImplVulkan_CreatePipelineLayout(VkDevice device, const VkAlloc check_vk_result(err); } -static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline *pipeline) +static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline) { ImGui_ImplVulkan_CreateShaderModules(device, allocator); @@ -801,24 +801,6 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() { ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo; VkResult err; - VkShaderModule vert_module; - VkShaderModule frag_module; - - // Create The Shader Modules: - { - VkShaderModuleCreateInfo vert_info = {}; - vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - vert_info.codeSize = sizeof(__glsl_shader_vert_spv); - vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; - err = vkCreateShaderModule(v->Device, &vert_info, v->Allocator, &vert_module); - check_vk_result(err); - VkShaderModuleCreateInfo frag_info = {}; - frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; - frag_info.codeSize = sizeof(__glsl_shader_frag_spv); - frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; - err = vkCreateShaderModule(v->Device, &frag_info, v->Allocator, &frag_module); - check_vk_result(err); - } if (!g_FontSampler) { @@ -884,9 +866,6 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, g_RenderPass, v->MSAASamples, &g_Pipeline); - vkDestroyShaderModule(v->Device, vert_module, v->Allocator); - vkDestroyShaderModule(v->Device, frag_module, v->Allocator); - return true; } @@ -911,6 +890,8 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() ImGui_ImplVulkanH_DestroyAllViewportsRenderBuffers(v->Device, v->Allocator); ImGui_ImplVulkan_DestroyFontUploadObjects(); + if (g_ShaderModuleVert) { vkDestroyShaderModule(v->Device, g_ShaderModuleVert, v->Allocator); g_ShaderModuleVert = VK_NULL_HANDLE; } + if (g_ShaderModuleFrag) { vkDestroyShaderModule(v->Device, g_ShaderModuleFrag, v->Allocator); g_ShaderModuleFrag = VK_NULL_HANDLE; } if (g_FontView) { vkDestroyImageView(v->Device, g_FontView, v->Allocator); g_FontView = VK_NULL_HANDLE; } if (g_FontImage) { vkDestroyImage(v->Device, g_FontImage, v->Allocator); g_FontImage = VK_NULL_HANDLE; } if (g_FontMemory) { vkFreeMemory(v->Device, g_FontMemory, v->Allocator); g_FontMemory = VK_NULL_HANDLE; } @@ -1247,7 +1228,10 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V info.pDependencies = &dependency; err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass); check_vk_result(err); - ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); + + // We do not create a pipeline by default as this is also used by examples' main.cpp, + // but secondary viewport in multi-viewport mode may want to create one with: + //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); } // Create The Image Views @@ -1297,6 +1281,7 @@ void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevic { (void)instance; ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); + ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); } @@ -1314,6 +1299,7 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui IM_FREE(wd->FrameSemaphores); wd->Frames = NULL; wd->FrameSemaphores = NULL; + vkDestroyPipeline(device, wd->Pipeline, allocator); vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index f20a72f4..31dbd01f 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -109,7 +109,7 @@ struct ImGui_ImplVulkanH_Window VkSurfaceFormatKHR SurfaceFormat; VkPresentModeKHR PresentMode; VkRenderPass RenderPass; - VkPipeline Pipeline; // The window pipeline uses a different VkRenderPass than the user's + VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo bool ClearEnable; VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) From a8f409a84895fc7ab291ea7ca3eec555aa47cc37 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 16 Sep 2020 10:28:58 +0200 Subject: [PATCH 259/959] Examples: DX12: Enable breaking on any warning/error when debug interface is enabled. (#3462, #3472) + misc comments & minor fixes. --- docs/CHANGELOG.txt | 1 + examples/example_win32_directx12/main.cpp | 19 ++++++++++++++++--- imgui.h | 8 +++++--- imgui_demo.cpp | 11 +++++------ imgui_draw.cpp | 4 ++-- 5 files changed, 29 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 092bd005..0ad6048e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -73,6 +73,7 @@ Other Changes: - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] - Examples: Vulkan: Switch validation layer to use "VK_LAYER_KHRONOS_validation" instead of "VK_LAYER_LUNARG_standard_validation" which is deprecated (#3459) [@FunMiles] +- Examples: DX12: Enable breaking on any warning/error when debug interface is enabled. - Examples: DX12: Added '#define ImTextureID ImU64' in project and build files to also allow building on 32-bit systems. Added project to default Visual Studio solution file. (#301) diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 4a263916..a2cd494a 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -241,19 +241,32 @@ bool CreateDeviceD3D(HWND hWnd) sd.Stereo = FALSE; } + // [DEBUG] Enable debug interface #ifdef DX12_ENABLE_DEBUG_LAYER ID3D12Debug* pdx12Debug = NULL; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&pdx12Debug)))) - { pdx12Debug->EnableDebugLayer(); - pdx12Debug->Release(); - } #endif + // Create device D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; if (D3D12CreateDevice(NULL, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK) return false; + // [DEBUG] Setup debug interface to break on any warnings/errors +#ifdef DX12_ENABLE_DEBUG_LAYER + if (pdx12Debug != NULL) + { + ID3D12InfoQueue* pInfoQueue = NULL; + g_pd3dDevice->QueryInterface(IID_PPV_ARGS(&pInfoQueue)); + pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true); + pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true); + pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true); + pInfoQueue->Release(); + pdx12Debug->Release(); + } +#endif + { D3D12_DESCRIPTOR_HEAP_DESC desc = {}; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; diff --git a/imgui.h b/imgui.h index 98a65699..d59bef30 100644 --- a/imgui.h +++ b/imgui.h @@ -887,13 +887,15 @@ enum ImGuiTreeNodeFlags_ // small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. // It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. // - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. +// IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter +// and want to another another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag. // - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). enum ImGuiPopupFlags_ { ImGuiPopupFlags_None = 0, - ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranted to always be == 0 (same as ImGuiMouseButton_Left) - ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranted to always be == 1 (same as ImGuiMouseButton_Right) - ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranted to always be == 2 (same as ImGuiMouseButton_Middle) + ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left) + ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right) + ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle) ImGuiPopupFlags_MouseButtonMask_ = 0x1F, ImGuiPopupFlags_MouseButtonDefault_ = 1, ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c7ab4310..f6bc7de4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -854,7 +854,7 @@ static void ShowDemoWindowWidgets() ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); if (n == 0) ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); - if (n == 1) + else ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); // Draw actual text bounding box, following by marker of our expected limit (should not overlap!) @@ -953,7 +953,7 @@ static void ShowDemoWindowWidgets() int frame_padding = -1 + i; // -1 == uses default padding (style.FramePadding) ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left - ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32 / my_tex_h); // UV coordinates for (32,32) in our texture + ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h);// UV coordinates for (32,32) in our texture ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint if (ImGui::ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col)) @@ -982,7 +982,7 @@ static void ShowDemoWindowWidgets() // stored in the object itself, etc.) const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" }; static int item_current_idx = 0; // Here our selection data is an index. - const char* combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically could be anything)( + const char* combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically it could be anything) if (ImGui::BeginCombo("combo 1", combo_label, flags)) { for (int n = 0; n < IM_ARRAYSIZE(items); n++) @@ -4939,16 +4939,15 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) const float DISTANCE = 10.0f; static int corner = 0; ImGuiIO& io = ImGui::GetIO(); + ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; if (corner != -1) { + window_flags |= ImGuiWindowFlags_NoMove; ImVec2 window_pos = ImVec2((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE); ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); } ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background - ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav; - if (corner != -1) - window_flags |= ImGuiWindowFlags_NoMove; if (ImGui::Begin("Example: Simple overlay", p_open, window_flags)) { ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 2f87366a..80d8d617 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -339,7 +339,7 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) } //----------------------------------------------------------------------------- -// ImDrawList +// [SECTION] ImDrawList //----------------------------------------------------------------------------- ImDrawListSharedData::ImDrawListSharedData() @@ -1405,7 +1405,7 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi //----------------------------------------------------------------------------- -// ImDrawListSplitter +// [SECTION] ImDrawListSplitter //----------------------------------------------------------------------------- // FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. //----------------------------------------------------------------------------- From a1597cff088a827e98688632f6523fae2b6513af Mon Sep 17 00:00:00 2001 From: Pierre-Loup Pagniez Date: Tue, 15 Sep 2020 12:39:55 +0200 Subject: [PATCH 260/959] Backends: DX12: Fix D3D12 Debug Layer warning if scissor rect is 0 width or 0 height. (#3472, #3462) In the event where the scissor rect is 0 width or 0 height, don't call Draw, as it generates warnings if the D3D12 Debug Layer is enabled, and nothing would have been drawn anyway. --- docs/CHANGELOG.txt | 1 + examples/imgui_impl_dx12.cpp | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0ad6048e..3f659f8e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,7 @@ Other Changes: own render pass. (#3455, #3459) [@FunMiles] - Backends: DX12: Clarified that imgui_impl_dx12 can be compiled on 32-bit systems by redefining the ImTextureID to be 64-bit (e.g. '#define ImTextureID ImU64' in imconfig.h). (#301) +- Backends: DX12: Fix debug layer warning when scissor rect is zero-sized. (#3472, #3462) [@StoneWolf] - Examples: Vulkan: Reworked buffer resize handling, fix for Linux/X11. (#3390, #2626) [@RoryO] - Examples: Vulkan: Switch validation layer to use "VK_LAYER_KHRONOS_validation" instead of "VK_LAYER_LUNARG_standard_validation" which is deprecated (#3459) [@FunMiles] diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index e55fdaf9..c33ca64f 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -235,9 +235,12 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL { // Apply Scissor, Bind texture, Draw const D3D12_RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) }; - ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId); - ctx->RSSetScissorRects(1, &r); - ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); + if (r.right > r.left && r.bottom > r.top) + { + ctx->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId); + ctx->RSSetScissorRects(1, &r); + ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); + } } } global_idx_offset += cmd_list->IdxBuffer.Size; From e230ec5a01d7c8da5a61ba0a19bbb8a0441c717b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 16 Sep 2020 11:05:02 +0200 Subject: [PATCH 261/959] Viewports, Backends: DX12: Make secondary viewport format match main viewport one (#3462) {@BeastLe9enD] --- examples/imgui_impl_dx12.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 690f3a8b..fcda0d5f 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -806,7 +806,7 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) sd1.BufferCount = g_numFramesInFlight; sd1.Width = (UINT)viewport->Size.x; sd1.Height = (UINT)viewport->Size.y; - sd1.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + sd1.Format = g_RTVFormat; sd1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd1.SampleDesc.Count = 1; sd1.SampleDesc.Quality = 0; From 6bc526676c45186ff8420fac3ecca71a3c3e87df Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 10 Sep 2020 11:02:40 +0200 Subject: [PATCH 262/959] Viewports: Comments, removed unnecessary use of ViewportFrontMostStampCount (the LastFrontMostStampCount is enough) --- imgui.cpp | 13 ++++++------- imgui_internal.h | 2 -- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index cb26785d..b8de6caf 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3493,7 +3493,7 @@ void ImGui::UpdateMouseMovingWindowNewFrame() g.MouseViewport = moving_window->Viewport; // Clear the NoInput window flag set by the Viewport system - moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; + moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL. ClearActiveID(); g.MovingWindow = NULL; @@ -11523,6 +11523,7 @@ void ImGui::UpdatePlatformWindows() // Update our implicit z-order knowledge of platform windows, which is used when the back-end cannot provide io.MouseHoveredViewport. // When setting Platform_GetWindowFocus, it is expected that the platform back-end can handle calls without crashing if it doesn't have data stored. + // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab. if (g.PlatformIO.Platform_GetWindowFocus != NULL) { ImGuiViewportP* focused_viewport = NULL; @@ -11533,12 +11534,10 @@ void ImGui::UpdatePlatformWindows() if (g.PlatformIO.Platform_GetWindowFocus(viewport)) focused_viewport = viewport; } - if (focused_viewport && g.PlatformLastFocusedViewport != focused_viewport->ID) - { - if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) - focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; - g.PlatformLastFocusedViewport = focused_viewport->ID; - } + + // Store a tag so we can infer z-order easily from all our windows + if (focused_viewport && focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) + focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; } } diff --git a/imgui_internal.h b/imgui_internal.h index 607ae378..98c231ac 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1353,7 +1353,6 @@ struct ImGuiContext ImGuiViewportP* CurrentViewport; // We track changes of viewport (happening in Begin) so we can call Platform_OnChangedViewport() ImGuiViewportP* MouseViewport; ImGuiViewportP* MouseLastHoveredViewport; // Last known viewport that was hovered by mouse (even if we are not hovering any viewport any more) + honoring the _NoInputs flag. - ImGuiID PlatformLastFocusedViewport; // Record of last focused platform window/viewport, when this changes we stamp the viewport as front-most int ViewportFrontMostStampCount; // Every time the front-most window changes, we stamp its viewport with an incrementing counter // Gamepad/keyboard Navigation @@ -1558,7 +1557,6 @@ struct ImGuiContext CurrentDpiScale = 0.0f; CurrentViewport = NULL; MouseViewport = MouseLastHoveredViewport = NULL; - PlatformLastFocusedViewport = 0; ViewportFrontMostStampCount = 0; NavWindow = NULL; From d2939ce0a11116a63b942ca4b02ba33cbf3635a7 Mon Sep 17 00:00:00 2001 From: Bartosz Szreder Date: Wed, 16 Sep 2020 15:17:45 +0200 Subject: [PATCH 263/959] Columns: Make sure the ClipRect is valid. (#3475) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3f659f8e..922e30b3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,8 @@ Other Changes: - Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). - Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave tabs reordered in the tab list popup. [@Xipiryon] +- Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of + a fully clipped column. (#3475) [@szreder] - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Backends: Vulkan: Some internal refactor aimed at allowing multi-viewport feature to create their diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c797b1a0..d6bf2811 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7938,7 +7938,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n)); float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f); column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); - column->ClipRect.ClipWith(window->ClipRect); + column->ClipRect.ClipWithFull(window->ClipRect); } if (columns->Count > 1) From 645a6e03425a1462d71d81b04b5186b225af01a7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 16 Sep 2020 18:36:42 +0200 Subject: [PATCH 264/959] Bypass unnecessary formatting when using the TextColored()/TextWrapped()/TextDisabled() helpers with a "%s" format string. (#3466) --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 22 ++++++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 922e30b3..50af7875 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,8 @@ Other Changes: where v_min == v_max. (#3361) - SliderInt, SliderScalar: Fixed reaching of maximum value with inverted integer min/max ranges, both with signed and unsigned types. Added reverse Sliders to Demo. (#3432, #3449) [@rokups] +- Text: Bypass unnecessary formatting when using the TextColored()/TextWrapped()/TextDisabled() helpers + with a "%s" format string. (#3466) - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. - TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d6bf2811..6894f257 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -274,7 +274,10 @@ void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, col); - TextV(fmt, args); + if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) + TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + else + TextV(fmt, args); PopStyleColor(); } @@ -288,8 +291,12 @@ void ImGui::TextDisabled(const char* fmt, ...) void ImGui::TextDisabledV(const char* fmt, va_list args) { - PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); - TextV(fmt, args); + ImGuiContext& g = *GImGui; + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) + TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + else + TextV(fmt, args); PopStyleColor(); } @@ -303,11 +310,14 @@ void ImGui::TextWrapped(const char* fmt, ...) void ImGui::TextWrappedV(const char* fmt, va_list args) { - ImGuiWindow* window = GetCurrentWindow(); - bool need_backup = (window->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set + ImGuiContext& g = *GImGui; + bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set if (need_backup) PushTextWrapPos(0.0f); - TextV(fmt, args); + if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0) + TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting + else + TextV(fmt, args); if (need_backup) PopTextWrapPos(); } From 2460f2abe3eed4e81b37eee5b4cabf920f05df16 Mon Sep 17 00:00:00 2001 From: Julian Webb Date: Thu, 10 Sep 2020 13:02:45 -0500 Subject: [PATCH 265/959] Backends: OpenGL3: Fix to avoid calling glBindSampler() with version <= 3.2 (#3467, #1985) (nb: GLEW sets the define we previously used) --- examples/imgui_impl_opengl3.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 21e8852b..a24de1ff 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -263,10 +263,12 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glUseProgram(g_ShaderHandle); glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); -#ifdef GL_SAMPLER_BINDING - glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. + +#if (!defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)) + if(g_GlVersion > 320) + glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. #endif - + (void)vertex_array_object; #ifndef IMGUI_IMPL_OPENGL_ES2 glBindVertexArray(vertex_array_object); @@ -299,8 +301,10 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) glActiveTexture(GL_TEXTURE0); GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); -#ifdef GL_SAMPLER_BINDING - GLuint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); +#if (!defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)) + GLuint last_sampler; + if(g_GlVersion > 320) + glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); #endif GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_ES2 @@ -391,8 +395,9 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Restore modified GL state glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); -#ifdef GL_SAMPLER_BINDING - glBindSampler(0, last_sampler); +#if (!defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)) + if(g_GlVersion > 320) + glBindSampler(0, last_sampler); #endif glActiveTexture(last_active_texture); #ifndef IMGUI_IMPL_OPENGL_ES2 From 42575d4a9979b0c880c00670f0165beed680175c Mon Sep 17 00:00:00 2001 From: Sven Balzer <4653051+Kodokuna@users.noreply.github.com> Date: Thu, 17 Sep 2020 02:58:23 +0200 Subject: [PATCH 266/959] Viewports, Backends: Win32: Fix toggling of ImGuiViewportFlags_TopMost (#3477) --- examples/imgui_impl_win32.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index 878efeeb..07a0c560 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -660,13 +660,19 @@ static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport* viewport) // Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows) if (data->DwStyle != new_style || data->DwExStyle != new_ex_style) { + // (Optional) Update TopMost state if it changed _after_ creation + bool top_most_changed = (data->DwExStyle & WS_EX_TOPMOST) != (new_ex_style & WS_EX_TOPMOST); + HWND insert_after = top_most_changed ? ((viewport->Flags & ImGuiViewportFlags_TopMost) ? HWND_TOPMOST : HWND_NOTOPMOST) : 0; + UINT swp_flag = top_most_changed ? 0 : SWP_NOZORDER; + + // Apply flags and position (since it is affected by flags) data->DwStyle = new_style; data->DwExStyle = new_ex_style; ::SetWindowLong(data->Hwnd, GWL_STYLE, data->DwStyle); ::SetWindowLong(data->Hwnd, GWL_EXSTYLE, data->DwExStyle); RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) }; ::AdjustWindowRectEx(&rect, data->DwStyle, FALSE, data->DwExStyle); // Client to Screen - ::SetWindowPos(data->Hwnd, NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); + ::SetWindowPos(data->Hwnd, insert_after, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, swp_flag | SWP_NOACTIVATE | SWP_FRAMECHANGED); ::ShowWindow(data->Hwnd, SW_SHOWNA); // This is necessary when we alter the style viewport->PlatformRequestMove = viewport->PlatformRequestResize = true; } From 825f699bde188a5c471e0c424009699165d39a3d Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 17 Sep 2020 09:33:48 +0200 Subject: [PATCH 267/959] Backends: OpenGL3: Amends (#3467, #1985) --- docs/CHANGELOG.txt | 2 ++ examples/imgui_impl_dx12.cpp | 1 + examples/imgui_impl_opengl3.cpp | 31 ++++++++++++++++--------------- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 50af7875..7df46943 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -70,6 +70,8 @@ Other Changes: a fully clipped column. (#3475) [@szreder] - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). +- Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 contexts which have + the defines set by a loader. (#3467, #1985) [@jjwebb] - Backends: Vulkan: Some internal refactor aimed at allowing multi-viewport feature to create their own render pass. (#3455, #3459) [@FunMiles] - Backends: DX12: Clarified that imgui_impl_dx12 can be compiled on 32-bit systems by redefining diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index c33ca64f..8d3ee417 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -15,6 +15,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index a24de1ff..8a1f5873 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 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. @@ -81,7 +82,6 @@ #include // intptr_t #endif - // GL includes #if defined(IMGUI_IMPL_OPENGL_ES2) #include @@ -124,10 +124,13 @@ using namespace gl; #endif // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have. -#if defined(IMGUI_IMPL_OPENGL_ES2) || defined(IMGUI_IMPL_OPENGL_ES3) || !defined(GL_VERSION_3_2) -#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 0 -#else -#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET 1 +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET +#endif + +// Desktop GL 3.3+ has glBindSampler() +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_3) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER #endif // OpenGL Data @@ -155,7 +158,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_opengl3"; -#if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET if (g_GlVersion >= 320) io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. #endif @@ -264,8 +267,8 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); -#if (!defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)) - if(g_GlVersion > 320) +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + if (g_GlVersion >= 330) glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. #endif @@ -301,10 +304,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) glActiveTexture(GL_TEXTURE0); GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); -#if (!defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)) - GLuint last_sampler; - if(g_GlVersion > 320) - glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + GLuint last_sampler; if (g_GlVersion >= 330) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } #endif GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_ES2 @@ -376,7 +377,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); -#if IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET if (g_GlVersion >= 320) glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset); else @@ -395,8 +396,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // Restore modified GL state glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); -#if (!defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)) - if(g_GlVersion > 320) +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER + if (g_GlVersion >= 330) glBindSampler(0, last_sampler); #endif glActiveTexture(last_active_texture); From b7b08f52a4b9c08bbcacb55209139cc9e58dc732 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 13 May 2020 14:56:13 +0300 Subject: [PATCH 268/959] Fix popup and tooltip positioning when not fitting in the screen. --- imgui.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index ecb3d7be..7eec4e08 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8016,11 +8016,22 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s continue; float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); - if (avail_w < size.x || avail_h < size.y) + + // There is no point in switching left/right sides when popup height exceeds available height or top/bottom + // sides when popup width exceeds available width. + if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down)) + continue; + else if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right)) continue; + ImVec2 pos; pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; + + // Clamp top-left (or top-right for RTL languages in the future) corner of popup to remain visible. + pos.x = ImMax(pos.x, r_outer.Min.x); + pos.y = ImMax(pos.y, r_outer.Min.y); + *last_dir = dir; return pos; } From c47bcb25edbe05e694d83910d6e4c719d1fec7b9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 17 Sep 2020 11:00:56 +0200 Subject: [PATCH 269/959] Fix popup and tooltip positioning when not fitting in the screen. Amend fa42ccea8. # Conflicts: # docs/CHANGELOG.txt --- docs/CHANGELOG.txt | 2 ++ docs/TODO.txt | 1 - imgui.cpp | 65 +++++++++++++++++++++++++--------------------- imgui_internal.h | 5 ++-- 4 files changed, 41 insertions(+), 32 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7df46943..f27ed543 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,8 @@ Other Changes: tabs reordered in the tab list popup. [@Xipiryon] - Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of a fully clipped column. (#3475) [@szreder] +- Popups, Tooltips: Fix edge cases issues with positionning popups and tooltips when they are larger than + viewport on either or both axises. [@Rokups] - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 contexts which have diff --git a/docs/TODO.txt b/docs/TODO.txt index 509fcca5..9f99871f 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -219,7 +219,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - popups/modals: although it is sometimes convenient that popups/modals lifetime is owned by imgui, we could also a bool-owned-by-user api as long as Begin() return value testing is enforced. - tooltip: drag and drop with tooltip near monitor edges lose/changes its last direction instead of locking one. The drag and drop tooltip should always follow without changing direction. - - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred direction" and may teleport when moving mouse. - tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. - tooltip: tooltips with delay timers? or general timer policy? (instantaneous vs timed): IsItemHovered() with timer + implicit aabb-id for items with no ID. (#1485) - tooltip: drag tooltip hovering over source widget with IsItemHovered/SetTooltip flickers. diff --git a/imgui.cpp b/imgui.cpp index 7eec4e08..700e7e4e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -8007,37 +8007,47 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s } } - // Default popup policy - const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; - for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + // Tooltip and Default popup policy + // (Always first try the direction we used on the last frame, if any) + if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default) { - const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; - if (n != -1 && dir == *last_dir) // Already tried this direction? - continue; - float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); - float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); + const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; + for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) + { + const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; + if (n != -1 && dir == *last_dir) // Already tried this direction? + continue; - // There is no point in switching left/right sides when popup height exceeds available height or top/bottom - // sides when popup width exceeds available width. - if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down)) - continue; - else if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right)) - continue; + const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); + const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); - ImVec2 pos; - pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; - pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; + // If there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width) + if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right)) + continue; + if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down)) + continue; + + ImVec2 pos; + pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; + pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; - // Clamp top-left (or top-right for RTL languages in the future) corner of popup to remain visible. - pos.x = ImMax(pos.x, r_outer.Min.x); - pos.y = ImMax(pos.y, r_outer.Min.y); + // Clamp top-left corner of popup + pos.x = ImMax(pos.x, r_outer.Min.x); + pos.y = ImMax(pos.y, r_outer.Min.y); - *last_dir = dir; - return pos; + *last_dir = dir; + return pos; + } } - // Fallback, try to keep within display + // Fallback when not enough room: *last_dir = ImGuiDir_None; + + // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. + if (policy == ImGuiPopupPositionPolicy_Tooltip) + return ref_pos + ImVec2(2, 2); + + // Otherwise try to keep within display ImVec2 pos = ref_pos; pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); @@ -8070,12 +8080,12 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field else r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); - return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default); } if (window->Flags & ImGuiWindowFlags_Popup) { ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1); - return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); + return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default); } if (window->Flags & ImGuiWindowFlags_Tooltip) { @@ -8087,10 +8097,7 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8); else r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important. - ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); - if (window->AutoPosLastDirection == ImGuiDir_None) - pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. - return pos; + return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip); } IM_ASSERT(0); return window->Pos; diff --git a/imgui_internal.h b/imgui_internal.h index aceeebca..ec37b38b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -777,7 +777,8 @@ enum ImGuiNavLayer enum ImGuiPopupPositionPolicy { ImGuiPopupPositionPolicy_Default, - ImGuiPopupPositionPolicy_ComboBox + ImGuiPopupPositionPolicy_ComboBox, + ImGuiPopupPositionPolicy_Tooltip }; struct ImGuiDataTypeTempStorage @@ -1879,7 +1880,7 @@ namespace ImGui IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); - IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default); + IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy); // Gamepad/Keyboard Navigation IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); From fbf70070bba5e582c14f4cbe1953f0dab29e78f1 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Thu, 17 Sep 2020 11:32:56 +0200 Subject: [PATCH 270/959] InputText: Fixed minor inconsistency when pressing Down on the last line when it doesn't have a carriage return (it used to move to the end of the line) + fixed two of our typos in stb_textedit.h --- docs/CHANGELOG.txt | 4 +++- imstb_textedit.h | 10 ++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f27ed543..6e08e3af 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,7 +50,9 @@ Other Changes: It is a rather unusual or useless combination of features but no reason it shouldn't work! - InputText: Fixed minor scrolling glitch when erasing trailing lines in InputTextMultiline(). - InputText: Fixed cursor being partially covered after using Ctrl+End key. -- InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454). +- InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454) +- InputText: Fixed minor inconsistency when pressing Down on the last line when it doesn't have a carriage + return (it used to move to the end of the line). [@Xipiryon] - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) - SliderInt, SliderScalar: Fixed reaching of maximum value with inverted integer min/max ranges, both diff --git a/imstb_textedit.h b/imstb_textedit.h index 2077d02a..e7205e77 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -177,7 +177,7 @@ // 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, -// i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. // // You can encode other things, such as CONTROL or ALT, in additional bits, and // then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, @@ -877,6 +877,12 @@ retry: // now find character position down a row if (find.length) { + + // [DEAR IMGUI] + // going down while being on the last line shouldn't bring us to that line end + if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) + break; + float goal_x = state->has_preferred_x ? state->preferred_x : find.x; float x; int start = find.first_char + find.length; @@ -1134,7 +1140,7 @@ static void stb_textedit_discard_redo(StbUndoState *state) state->undo_rec[i].char_storage += n; } // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' - // {DEAR IMGUI] + // [DEAR IMGUI] size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; From c206a193737811193a0b48ef2d35fe028fa0996e Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 17 Sep 2020 16:43:23 +0200 Subject: [PATCH 271/959] Removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. (#1619) + Fonts: AddFontDefault() adjust its vertical offset based on floor(size/13) instead of always +1. --- docs/CHANGELOG.txt | 11 ++++++++++- docs/FONTS.md | 11 ++--------- docs/README.md | 2 +- imgui.cpp | 1 + imgui.h | 3 +-- imgui_demo.cpp | 5 ++--- imgui_draw.cpp | 11 +++++------ imgui_widgets.cpp | 1 - 8 files changed, 22 insertions(+), 23 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6e08e3af..94a069f7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -35,6 +35,14 @@ HOW TO UPDATE? VERSION 1.79 WIP (In Progress) ----------------------------------------------------------------------- +Breaking Changes: + +- Fonts: Removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied + after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. + It was also getting in the way of better font scaling, so let's get rid of it now! + If you used DisplayOffset it was probably in association to rasterizing a font at a specific size, + in which case the corresponding offset may be reported into GlyphOffset. (#1619) + Other Changes: - Window: Fixed using non-zero pivot in SetNextWindowPos() when the window is collapsed. (#3433) @@ -72,6 +80,7 @@ Other Changes: a fully clipped column. (#3475) [@szreder] - Popups, Tooltips: Fix edge cases issues with positionning popups and tooltips when they are larger than viewport on either or both axises. [@Rokups] +- Fonts: AddFontDefault() adjust its vertical offset based on floor(size/13) instead of always +1. - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 contexts which have @@ -1481,7 +1490,7 @@ Breaking Changes: - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts. - Renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums. - Fonts: Moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths. -- Fonts: changed ImFont::DisplayOffset.y to defaults to 0 instead of +1. Fixed vertical rounding of Ascent/Descent to match TrueType renderer. +- Fonts: Changed ImFont::DisplayOffset.y to defaults to 0 instead of +1. Fixed vertical rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting (not assigning) to ImFont::DisplayOffset check if your fonts are correctly aligned vertically. (#1619) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment. - Obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete). diff --git a/docs/FONTS.md b/docs/FONTS.md index 158e08ab..c2312fd5 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -142,13 +142,6 @@ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png)
_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_ - -**Offset font vertically by altering the `io.Font->DisplayOffset` value:** -```cpp -ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); -font->DisplayOffset.y = 1; // Render 1 pixel down -``` - **Font Atlas too large?** - If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. The typical result of failing to upload a texture is if every glyphs appears as white rectangles. @@ -337,13 +330,13 @@ DroidSans.ttf ProggyClean.ttf Copyright (c) 2004, 2005 Tristan Grimmer MIT License - recommended loading setting: Size = 13.0, DisplayOffset.Y = +1 + recommended loading setting: Size = 13.0, GlyphOffset.y = +1 http://www.proggyfonts.net/ ProggyTiny.ttf Copyright (c) 2004, 2005 Tristan Grimmer MIT License - recommended loading setting: Size = 10.0, DisplayOffset.Y = +1 + recommended loading setting: Size = 10.0, GlyphOffset.y = +1 http://www.proggyfonts.net/ Karla-Regular.ttf diff --git a/docs/README.md b/docs/README.md index 230aa03c..41869257 100644 --- a/docs/README.md +++ b/docs/README.md @@ -114,7 +114,7 @@ Officially maintained bindings (in repository): - Frameworks: Emscripten, Allegro5, Marmalade. Third-party bindings (see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings/) page): -- Languages: C, C# and: Beef, ChaiScript, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... +- Languages: C, C# and: Beef, ChaiScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... - Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, nCine, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. - Note that C bindings ([cimgui](https://github.com/cimgui/cimgui)) are auto-generated, you can use its json/lua output to generate bindings for other languages. diff --git a/imgui.cpp b/imgui.cpp index 700e7e4e..a3c7e72a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. It was also getting in the way of better font scaling, so let's get rid of it now! - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: diff --git a/imgui.h b/imgui.h index d59bef30..48889186 100644 --- a/imgui.h +++ b/imgui.h @@ -2406,11 +2406,10 @@ struct ImFont float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) - // Members: Hot ~36/48 bytes (for CalcTextSize + render loop) + // Members: Hot ~28/40 bytes (for CalcTextSize + render loop) ImVector IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. ImVector Glyphs; // 12-16 // out // // All glyphs. const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) - ImVec2 DisplayOffset; // 8 // in // = (0,0) // Offset font rendering by xx pixels // Members: Cold ~32/40 bytes ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f6bc7de4..9099116c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3715,7 +3715,6 @@ static void NodeFont(ImFont* font) "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.)"); - ImGui::InputFloat("Font offset", &font->DisplayOffset.y, 1, 1, "%.0f"); ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); ImGui::Text("Fallback character: '%c' (U+%04X)", font->FallbackChar, font->FallbackChar); ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar); @@ -3724,8 +3723,8 @@ static void NodeFont(ImFont* font) for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) if (font->ConfigData) if (const ImFontConfig* cfg = &font->ConfigData[config_i]) - ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", - config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); + ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)", + config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y); if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) { // Display all glyphs of the fonts in separate pages of 256 characters diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 80d8d617..3f666698 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1891,11 +1891,11 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) if (font_cfg.Name[0] == '\0') ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); font_cfg.EllipsisChar = (ImWchar)0x0085; + font_cfg.GlyphOffset.y = 1.0f * IM_FLOOR(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault(); ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges); - font->DisplayOffset.y = 1.0f; return font; } @@ -2768,7 +2768,6 @@ ImFont::ImFont() FallbackAdvanceX = 0.0f; FallbackChar = (ImWchar)'?'; EllipsisChar = (ImWchar)-1; - DisplayOffset = ImVec2(0.0f, 0.0f); FallbackGlyph = NULL; ContainerAtlas = NULL; ConfigData = NULL; @@ -3163,8 +3162,8 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col if (!glyph || !glyph->Visible) return; float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; - pos.x = IM_FLOOR(pos.x + DisplayOffset.x); - pos.y = IM_FLOOR(pos.y + DisplayOffset.y); + pos.x = IM_FLOOR(pos.x); + pos.y = IM_FLOOR(pos.y); draw_list->PrimReserve(6, 4); draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); } @@ -3175,8 +3174,8 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. // Align to be pixel perfect - pos.x = IM_FLOOR(pos.x + DisplayOffset.x); - pos.y = IM_FLOOR(pos.y + DisplayOffset.y); + pos.x = IM_FLOOR(pos.x); + pos.y = IM_FLOOR(pos.y); float x = pos.x; float y = pos.y; if (y > clip_rect.w) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6894f257..466bc803 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3958,7 +3958,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ ImFont* password_font = &g.InputTextPasswordFont; password_font->FontSize = g.Font->FontSize; password_font->Scale = g.Font->Scale; - password_font->DisplayOffset = g.Font->DisplayOffset; password_font->Ascent = g.Font->Ascent; password_font->Descent = g.Font->Descent; password_font->ContainerAtlas = g.Font->ContainerAtlas; From 8eca736a7a0e42acebc8a1e497c319a351152659 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 18 Sep 2020 10:03:14 +0200 Subject: [PATCH 272/959] Update binary link (contents of 20200412.zip's dx11.exe is flagged by Windows Defender, can't currently repro) --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index 41869257..41279f60 100644 --- a/docs/README.md +++ b/docs/README.md @@ -98,7 +98,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas ![screenshot demo](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png) You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: -- [imgui-demo-binaries-20200412.zip](http://www.dearimgui.org/binaries/imgui-demo-binaries-20200412.zip) (Windows, 1.76, built 2020/04/12, master branch) or [older demo binaries](http://www.dearimgui.org/binaries). +- [imgui-demo-binaries-20200918.zip](https://www.dearimgui.org/binaries/imgui-demo-binaries-20200918.zip) (Windows, 1.78 WIP, built 2020/09/18, master branch) or [older demo binaries](https://www.dearimgui.org/binaries). The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.org/faq)). From ec945f44b5eff1d82129233be5643abbff2845da Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Thu, 17 Sep 2020 11:39:54 +0200 Subject: [PATCH 273/959] InputText: Added support for Page Up/Down in InputTextMultiline. (#3430) + fix stb_textedit.h to build with C language (amend fbf70070) --- docs/CHANGELOG.txt | 6 ++-- imgui_widgets.cpp | 14 +++++++-- imstb_textedit.h | 72 ++++++++++++++++++++++++++++++---------------- 3 files changed, 63 insertions(+), 29 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 94a069f7..f1d78925 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,7 @@ Other Changes: - Nav: Fixed using Alt to toggle the Menu layer when inside a Modal window. (#787) - Scrolling: Fixed SetScrollHere functions edge snapping when called during a frame where ContentSize is changing (issue introduced in 1.78). (#3452). +- InputText: Added support for Page Up/Down in InputTextMultiline(). (#3430) [@Xipiryon] - InputText: Added selection helpers in ImGuiInputTextCallbackData(). - InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the @@ -59,8 +60,9 @@ Other Changes: - InputText: Fixed minor scrolling glitch when erasing trailing lines in InputTextMultiline(). - InputText: Fixed cursor being partially covered after using Ctrl+End key. - InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454) -- InputText: Fixed minor inconsistency when pressing Down on the last line when it doesn't have a carriage - return (it used to move to the end of the line). [@Xipiryon] +- InputText: Made pressing Down arrow on the last line when it doesn't have a carriage return not move to the end + of the line (so it is consistent with Up arrow, and behave same as Notepad and Visual Studio. Note that some + other text editors instead would move the crusor to the end of the line). [@Xipiryon] - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) - SliderInt, SliderScalar: Fixed reaching of maximum value with inverted integer min/max ranges, both diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 466bc803..c7c7d2d3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3590,6 +3590,8 @@ static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const Im #define STB_TEXTEDIT_K_REDO 0x20000B // keyboard input to perform redo #define STB_TEXTEDIT_K_WORDLEFT 0x20000C // keyboard input to move cursor left one word #define STB_TEXTEDIT_K_WORDRIGHT 0x20000D // keyboard input to move cursor right one word +#define STB_TEXTEDIT_K_PGUP 0x20000E // keyboard input to move cursor up a page +#define STB_TEXTEDIT_K_PGDOWN 0x20000F // keyboard input to move cursor down a page #define STB_TEXTEDIT_K_SHIFT 0x400000 #define STB_TEXTEDIT_IMPLEMENTATION @@ -3856,6 +3858,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ bool clear_active_id = false; bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline); + float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX; + const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start); const bool init_state = (init_make_active || user_scroll_active); if (init_state && g.ActiveId != id) @@ -3916,7 +3920,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); g.ActiveIdUsingKeyInputMask |= ((ImU64)1 << ImGuiKey_Home) | ((ImU64)1 << ImGuiKey_End); if (is_multiline) - g.ActiveIdUsingKeyInputMask |= ((ImU64)1 << ImGuiKey_PageUp) | ((ImU64)1 << ImGuiKey_PageDown); // FIXME-NAV: Page up/down actually not supported yet by widget, but claim them ahead. + g.ActiveIdUsingKeyInputMask |= ((ImU64)1 << ImGuiKey_PageUp) | ((ImU64)1 << ImGuiKey_PageDown); if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out as we will use the \t character. g.ActiveIdUsingKeyInputMask |= ((ImU64)1 << ImGuiKey_Tab); } @@ -4055,6 +4059,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(state != NULL); IM_ASSERT(io.KeyMods == GetMergedKeyModFlags() && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); // We rarely do this check, but if anything let's do it here. + const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1); + state->Stb.row_count_per_page = row_count_per_page; + const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_osx = io.ConfigMacOSXBehaviors; const bool is_osx_shift_shortcut = is_osx && (io.KeyMods == (ImGuiKeyModFlags_Super | ImGuiKeyModFlags_Shift)); @@ -4074,6 +4081,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_PageUp) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGUP | k_mask); scroll_y -= row_count_per_page * g.FontSize; } + else if (IsKeyPressedMap(ImGuiKey_PageDown) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGDOWN | k_mask); scroll_y += row_count_per_page * g.FontSize; } else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Delete) && !is_readonly) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } @@ -4443,12 +4452,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_multiline) { // Test if cursor is vertically visible - float scroll_y = draw_window->Scroll.y; - const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); if (cursor_offset.y - g.FontSize < scroll_y) scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - inner_size.y >= scroll_y) scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f; + const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f); scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y); draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; diff --git a/imstb_textedit.h b/imstb_textedit.h index e7205e77..76446709 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -148,6 +148,8 @@ // STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right // STB_TEXTEDIT_K_UP keyboard input to move cursor up // STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page // STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME // STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END // STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME @@ -170,10 +172,6 @@ // 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 // -// Todo: -// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page -// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page -// // 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, @@ -337,6 +335,10 @@ typedef struct // each textfield keeps its own insert mode state. to keep an app-wide // insert mode, copy this value in/out of the app state + int row_count_per_page; + // page size in number of row. + // this value MUST be set to >0 for pageup or pagedown in multilines documents. + ///////////////////// // // private data @@ -855,12 +857,16 @@ retry: break; case STB_TEXTEDIT_K_DOWN: - case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: { + case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGDOWN: + case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: { StbFindState find; StbTexteditRow row; - int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN; + int row_count = is_page ? state->row_count_per_page : 1; - if (state->single_line) { + if (!is_page && state->single_line) { // on windows, up&down in single-line behave like left&right key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); goto retry; @@ -869,23 +875,25 @@ retry: if (sel) stb_textedit_prep_selection_at_cursor(state); else if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_last(str,state); + stb_textedit_move_to_last(str, state); // compute current position of cursor point stb_textedit_clamp(str, state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - // now find character position down a row - if (find.length) { + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; + int start = find.first_char + find.length; + + if (find.length == 0) + break; // [DEAR IMGUI] // going down while being on the last line shouldn't bring us to that line end if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) break; - float goal_x = state->has_preferred_x ? state->preferred_x : find.x; - float x; - int start = find.first_char + find.length; + // now find character position down a row state->cursor = start; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; @@ -907,17 +915,25 @@ retry: if (sel) state->select_end = state->cursor; + + // go to next line + find.first_char = find.first_char + find.length; + find.length = row.num_chars; } break; } case STB_TEXTEDIT_K_UP: - case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: { + case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: + case STB_TEXTEDIT_K_PGUP: + case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: { StbFindState find; StbTexteditRow row; - int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP; + int row_count = is_page ? state->row_count_per_page : 1; - if (state->single_line) { + if (!is_page && state->single_line) { // on windows, up&down become left&right key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); goto retry; @@ -932,11 +948,14 @@ retry: stb_textedit_clamp(str, state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - // can only go up if there's a previous row - if (find.prev_first != find.first_char) { + for (j = 0; j < row_count; ++j) { + float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; + + // can only go up if there's a previous row + if (find.prev_first == find.first_char) + break; + // now find character position up a row - float goal_x = state->has_preferred_x ? state->preferred_x : find.x; - float x; state->cursor = find.prev_first; STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); x = row.x0; @@ -958,6 +977,14 @@ retry: if (sel) state->select_end = state->cursor; + + // 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; + find.first_char = find.prev_first; + find.prev_first = prev_scan; } break; } @@ -1081,10 +1108,6 @@ retry: state->has_preferred_x = 0; break; } - -// @TODO: -// STB_TEXTEDIT_K_PGUP - move cursor up a page -// STB_TEXTEDIT_K_PGDOWN - move cursor down a page } } @@ -1356,6 +1379,7 @@ static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_lin state->initialized = 1; state->single_line = (unsigned char) is_single_line; state->insert_mode = 0; + state->row_count_per_page = 0; } // API initialize From a58a72778179630f29dee5e292f1c5c41a79c91f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2020 12:02:19 +0200 Subject: [PATCH 274/959] Renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting 99ab5210 --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 12 +++++++----- imgui.h | 11 ++++++----- imgui_demo.cpp | 6 +++--- imgui_widgets.cpp | 10 +++++----- 5 files changed, 24 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f1d78925..6f2f1e3d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,8 @@ Breaking Changes: It was also getting in the way of better font scaling, so let's get rid of it now! If you used DisplayOffset it was probably in association to rasterizing a font at a specific size, in which case the corresponding offset may be reported into GlyphOffset. (#1619) +- Renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), REVERTED CHANGE FROM 1.77. + For variety of reason this is more self-explanatory. Other Changes: @@ -210,6 +212,7 @@ Breaking Changes: note that this is a Beta api and will likely be reworked in order to support multi-DPI across multiple monitors. - Renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). + [NOTE: THIS WAS REVERTED IN 1.79] - Removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. Kept inline redirection function (will obsolete). diff --git a/imgui.cpp b/imgui.cpp index a3c7e72a..679a8cde 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. It was also getting in the way of better font scaling, so let's get rid of it now! - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). @@ -384,7 +385,7 @@ CODE for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). + - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79] - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. @@ -7920,8 +7921,9 @@ void ImGui::EndPopup() g.WithinEndChild = false; } -// Open a popup if mouse button is released over the item -bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) +// Helper to open a popup if mouse button is released over the item +// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() +bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); @@ -7938,8 +7940,8 @@ bool ImGui::OpenPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags // This is a helper to handle the simplest case of associating one named popup to one given widget. // - You can pass a NULL str_id to use the identifier of the last item. // - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). -// - This is essentially the same as calling OpenPopupContextItem() + BeginPopup() but written to avoid -// computing the ID twice because BeginPopupContextXXX functions are called very frequently. +// - This is essentially the same as calling OpenPopupOnItemClick() + BeginPopup() but written to avoid +// computing the ID twice because BeginPopupContextXXX functions may be called very frequently. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui.h b/imgui.h index 48889186..1ee54fb9 100644 --- a/imgui.h +++ b/imgui.h @@ -620,13 +620,13 @@ namespace ImGui // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). - IMGUI_API bool OpenPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. // Popups: open+begin combined functions helpers // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. // - They are convenient to easily create context menus, hence the name. // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. - // - We exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter. Passing a mouse button to ImGuiPopupFlags is guaranteed to be legal. + // - IMPORTANT: we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight. IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window. IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows). @@ -1713,7 +1713,9 @@ struct ImGuiPayload #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { - // OBSOLETED in 1.78 (from August 2020) + // OBSOLETED in 1.79 (from August 2020) + static inline bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupOnItemClick(str_id, mb); } // Renamed in 1.77, renamed back in 1.79. Sorry! + // OBSOLETED in 1.78 (from June 2020) // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags. // For shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power); @@ -1729,9 +1731,8 @@ namespace ImGui static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.77 (from June 2020) - static inline bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupContextItem(str_id, mb); } // Passing a mouse button to ImGuiPopupFlags is legal static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } - // OBSOLETED in 1.72 (from July 2019) + // OBSOLETED in 1.72 (from April 2019) static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.71 (from June 2019) static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9099116c..34914e0d 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2977,11 +2977,11 @@ static void ShowDemoWindowPopups() ImGui::EndPopup(); } - // We can also use OpenPopupContextItem() which is the same as BeginPopupContextItem() but without the + // We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the // Begin() call. So here we will make it that clicking on the text field with the right mouse button (1) // will toggle the visibility of the popup above. ImGui::Text("(You can also right-click me to open the same popup as above.)"); - ImGui::OpenPopupContextItem("item context menu", 1); + ImGui::OpenPopupOnItemClick("item context menu", 1); // When used after an item that has an ID (e.g.Button), we can skip providing an ID to BeginPopupContextItem(). // BeginPopupContextItem() will use the last item ID as the popup ID. @@ -5178,7 +5178,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Context menu (under default mouse threshold) ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); if (opt_enable_context_menu && ImGui::IsMouseReleased(ImGuiMouseButton_Right) && drag_delta.x == 0.0f && drag_delta.y == 0.0f) - ImGui::OpenPopupContextItem("context"); + ImGui::OpenPopupOnItemClick("context"); if (ImGui::BeginPopup("context")) { if (adding_line) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c7c7d2d3..12394576 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4699,7 +4699,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupContextItem("context"); + OpenPopupOnItemClick("context"); } } else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) @@ -4724,7 +4724,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupContextItem("context"); + OpenPopupOnItemClick("context"); } ImGuiWindow* picker_active_window = NULL; @@ -4745,7 +4745,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag } } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupContextItem("context"); + OpenPopupOnItemClick("context"); if (BeginPopup("picker")) { @@ -4965,7 +4965,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl } } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupContextItem("context"); + OpenPopupOnItemClick("context"); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { @@ -4978,7 +4978,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl value_changed = value_changed_sv = true; } if (!(flags & ImGuiColorEditFlags_NoOptions)) - OpenPopupContextItem("context"); + OpenPopupOnItemClick("context"); // Hue bar logic SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); From 795cf6fcb5626ddbbf995cf98b016721099ec428 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2020 15:05:04 +0200 Subject: [PATCH 275/959] Removed return value from OpenPopupOnItemClick(). Use IsWindowAppearing() after BeginPopup() for a similar result. --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 5 ++--- imgui.h | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6f2f1e3d..b2e0ccaf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -44,6 +44,9 @@ Breaking Changes: in which case the corresponding offset may be reported into GlyphOffset. (#1619) - Renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), REVERTED CHANGE FROM 1.77. For variety of reason this is more self-explanatory. +- Removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it + is inconsistent with other popups API and makes others misleading. It's also and unnecessary: you can + use IsWindowAppearing() after BeginPopup() for a similar result. Other Changes: diff --git a/imgui.cpp b/imgui.cpp index 679a8cde..4c867579 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -373,6 +373,7 @@ CODE You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. + - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. It was also getting in the way of better font scaling, so let's get rid of it now! - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). @@ -7923,7 +7924,7 @@ void ImGui::EndPopup() // Helper to open a popup if mouse button is released over the item // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() -bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) +void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); @@ -7932,9 +7933,7 @@ bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) OpenPopupEx(id, popup_flags); - return true; } - return false; } // This is a helper to handle the simplest case of associating one named popup to one given widget. diff --git a/imgui.h b/imgui.h index 1ee54fb9..3b003a2b 100644 --- a/imgui.h +++ b/imgui.h @@ -620,7 +620,7 @@ namespace ImGui // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!). - IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) + IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into. // Popups: open+begin combined functions helpers // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. @@ -1714,7 +1714,7 @@ struct ImGuiPayload namespace ImGui { // OBSOLETED in 1.79 (from August 2020) - static inline bool OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { return OpenPopupOnItemClick(str_id, mb); } // Renamed in 1.77, renamed back in 1.79. Sorry! + static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! // OBSOLETED in 1.78 (from June 2020) // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags. // For shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. From afc1099fb50f1ca4fdbf7e508360d4361a896be5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2020 18:52:12 +0200 Subject: [PATCH 276/959] Tab Bar: Fixed a small bug where closing a tab that is not selected would leave a tab hole for a frame. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 17 +++++++++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b2e0ccaf..236d278c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -81,6 +81,7 @@ Other Changes: and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) - Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). +- Tab Bar: Fixed a small bug where closing a tab that is not selected would leave a tab hole for a frame. - Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave tabs reordered in the tab list popup. [@Xipiryon] - Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 12394576..a8cc2316 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7148,17 +7148,22 @@ void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) // Called on manual closure attempt void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { - if ((tab_bar->VisibleTabId == tab->ID) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) + if (!(tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) { // This will remove a frame of lag for selecting another tab on closure. // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure - tab->LastFrameVisible = -1; - tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; + tab->WantClose = true; + if (tab_bar->VisibleTabId == tab->ID) + { + tab->LastFrameVisible = -1; + tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; + } } - else if ((tab_bar->VisibleTabId != tab->ID) && (tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) + else { - // Actually select before expecting closure - tab_bar->NextSelectedTabId = tab->ID; + // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) + if (tab_bar->VisibleTabId != tab->ID) + tab_bar->NextSelectedTabId = tab->ID; } } From 27d0c3afa9327dfdb43c78f02ea3540d5e05dfa3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2020 19:46:44 +0200 Subject: [PATCH 277/959] Tab Bar: Fixed a small bug where scrolling buttons (with ImGuiTabBarFlags_FittingPolicyScroll) would generate an unnecessary extra draw call. --- docs/CHANGELOG.txt | 2 ++ imgui_widgets.cpp | 20 ++++++-------------- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 236d278c..1c81c724 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -82,6 +82,8 @@ Other Changes: (This is also necessary to support full multi/range-select/drag and drop operations.) - Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). - Tab Bar: Fixed a small bug where closing a tab that is not selected would leave a tab hole for a frame. +- Tab Bar: Fixed a small bug where scrolling buttons (with ImGuiTabBarFlags_FittingPolicyScroll) would + generate an unnecessary extra draw call. - Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave tabs reordered in the tab list popup. [@Xipiryon] - Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a8cc2316..4a7f18c6 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7234,13 +7234,6 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) const ImVec2 backup_cursor_pos = window->DC.CursorPos; //window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255)); - const ImRect avail_bar_rect = tab_bar->BarRect; - bool want_clip_rect = !avail_bar_rect.Contains(ImRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(scrolling_buttons_width, 0.0f))); - if (want_clip_rect) - PushClipRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max + ImVec2(g.Style.ItemInnerSpacing.x, 0.0f), true); - - ImGuiTabItem* tab_to_select = NULL; - int select_dir = 0; ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; arrow_col.w *= 0.5f; @@ -7251,30 +7244,29 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) const float backup_repeat_rate = g.IO.KeyRepeatRate; g.IO.KeyRepeatDelay = 0.250f; g.IO.KeyRepeatRate = 0.200f; - window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y); + float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width); + window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y); if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat)) select_dir = -1; - window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width + arrow_button_size.x, tab_bar->BarRect.Min.y); + window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y); if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat)) select_dir = +1; PopStyleColor(2); g.IO.KeyRepeatRate = backup_repeat_rate; g.IO.KeyRepeatDelay = backup_repeat_delay; - if (want_clip_rect) - PopClipRect(); - + ImGuiTabItem* tab_to_scroll_to = NULL; if (select_dir != 0) if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) { int selected_order = tab_bar->GetTabOrder(tab_item); int target_order = selected_order + select_dir; - tab_to_select = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible + tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible } window->DC.CursorPos = backup_cursor_pos; tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f; - return tab_to_select; + return tab_to_scroll_to; } static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) From 29836412e1f78dfda5802115b387a73460cb8563 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Sep 2020 15:49:47 +0200 Subject: [PATCH 278/959] Internals, CollapsingHeader, TabItem: Standardized using a #CLOSE id prefix for TabItem and ColllapsingHeader (same as window) --- imgui.cpp | 14 ++++++++++++++ imgui_internal.h | 1 + imgui_widgets.cpp | 5 +++-- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4c867579..ec107aed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6742,6 +6742,20 @@ void ImGui::PushOverrideID(ImGuiID id) window->IDStack.push_back(id); } +// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call +// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level. +// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) +ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed) +{ + ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); + ImGui::KeepAliveID(id); +#ifdef IMGUI_ENABLE_TEST_ENGINE + ImGuiContext& g = *GImGui; + IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end); +#endif + return id; +} + void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; diff --git a/imgui_internal.h b/imgui_internal.h index ec37b38b..c5b3028b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1847,6 +1847,7 @@ namespace ImGui IMGUI_API void KeepAliveID(ImGuiID id); IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function. IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes) + IMGUI_API ImGuiID GetIDWithSeed(const char* str_id_begin, const char* str_id_end, ImGuiID seed); // Basic Helpers for widget code IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4a7f18c6..abc3f16c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5898,7 +5898,8 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags float button_size = g.FontSize; float button_x = ImMax(window->DC.LastItemRect.Min.x, window->DC.LastItemRect.Max.x - g.Style.FramePadding.x * 2.0f - button_size); float button_y = window->DC.LastItemRect.Min.y; - if (CloseButton(window->GetID((void*)((intptr_t)id + 1)), ImVec2(button_x, button_y))) + ImGuiID close_button_id = GetIDWithSeed("#CLOSE", NULL, id); + if (CloseButton(close_button_id, ImVec2(button_x, button_y))) *p_open = false; last_item_backup.Restore(); } @@ -7539,7 +7540,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; // Render tab label, process close button - const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; + const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, id) : 0; bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); if (just_closed && p_open != NULL) { From 4a57a982bec47910e85594dee2a0dcf061fd65a6 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Mon, 3 Aug 2020 18:55:51 +0200 Subject: [PATCH 279/959] Tab Bar: Added TabItemButton(), ImGuiTabItemFlags_Leading, ImGuiTabItemFlags_Trailing + demo. (#3291) (squashed various commits by 2 authors) --- docs/CHANGELOG.txt | 5 ++ imgui.h | 8 +- imgui_demo.cpp | 85 ++++++++++++++++++ imgui_internal.h | 6 +- imgui_widgets.cpp | 210 +++++++++++++++++++++++++++++++++++---------- 5 files changed, 264 insertions(+), 50 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1c81c724..d1f5fb2a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -86,6 +86,11 @@ Other Changes: generate an unnecessary extra draw call. - Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave tabs reordered in the tab list popup. [@Xipiryon] +- Tab Bar: Added TabItemButton() to submit tab that behave like a button. (#3291) [@Xipiryon] +- Tab Bar: Added ImGuiTabItemFlags_Leading and ImGuiTabItemFlags_Trailing flags to position tabs or button at + either end of the tab bar. Those tabs won't be part of the scrolling region, won't shrink down, and when + reordering cannot be moving outside of their section. Most often used with TabItemButton(). (#3291) [@Xipiryon] +- Tab Bar: Added ImGuiTabItemFlags_NoReorder flag to disable reordering a given tab. - Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of a fully clipped column. (#3475) [@szreder] - Popups, Tooltips: Fix edge cases issues with positionning popups and tooltips when they are larger than diff --git a/imgui.h b/imgui.h index 3b003a2b..91a0b162 100644 --- a/imgui.h +++ b/imgui.h @@ -653,8 +653,9 @@ namespace ImGui // Tab Bars, Tabs IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! - IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0);// create a Tab. Returns true if the Tab is selected. + IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! + IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. // Logging/Capture @@ -954,7 +955,10 @@ enum ImGuiTabItemFlags_ ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() - ImGuiTabItemFlags_NoTooltip = 1 << 4 // Disable tooltip for the given tab + ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab + ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab + ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) and disable resizing down + ImGuiTabItemFlags_Trailing = 1 << 7 // Enforce the tab position to the right of the tab bar (before the scrolling buttons) and disable resizing down }; // Flags for ImGui::IsWindowFocused() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 34914e0d..42a3bf31 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2354,6 +2354,91 @@ static void ShowDemoWindowLayout() ImGui::Separator(); ImGui::TreePop(); } + + if (ImGui::TreeNode("TabItem Button")) + { + static int next_id = 0; + static ImVector tabs_list; + if (next_id == 0) // Initialize with a default tab + for (int i = 0; i < 9; i++) + tabs_list.push_back(next_id++); + + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; + ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); + + static bool show_leading_button = true; + static bool show_trailing_button = true; + ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); + ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); + static bool enable_position = false; + ImGui::Checkbox("Enable Leading/Trailing TabItem()", &enable_position); + + if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) + { + if (show_leading_button) + { + if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) + tabs_list.push_back(next_id++); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Add a new TabItem() in the tab bar"); + + // Popup Context also works with TabItemButton + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("I'm a popup!"); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + } + + bool close_current_tab = false; + if (show_trailing_button) + { + if (ImGui::TabItemButton("X", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) + close_current_tab = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Close the currently selected TabItem()"); + } + + for (int n = 0; n < tabs_list.Size; ) + { + int mod = tabs_list[n] % 3; + ImGuiTabItemFlags flags = mod == 0 ? 0 : mod == 1 ? ImGuiTabItemFlags_Leading : ImGuiTabItemFlags_Trailing; + if (!enable_position) + flags = 0; + + char name[16]; + snprintf(name, IM_ARRAYSIZE(name), "%04d", tabs_list[n]); + bool open = true; + if (ImGui::BeginTabItem(name, &open, flags)) + { + ImGui::Text("This is the %s tab!", name); + ImGui::EndTabItem(); + + if (close_current_tab) + { + open = false; + ImGui::SetTabItemClosed(name); + } + } + + if (!open) + tabs_list.erase(tabs_list.Data + n); + else + ++n; + } + + ImGui::EndTabBar(); + } + ImGui::Separator(); + ImGui::TreePop(); + } ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index c5b3028b..0563e7c5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1703,7 +1703,8 @@ enum ImGuiTabBarFlagsPrivate_ // Extend ImGuiTabItemFlags_ enum ImGuiTabItemFlagsPrivate_ { - ImGuiTabItemFlags_NoCloseButton = 1 << 20 // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + ImGuiTabItemFlags_Button = 1 << 21 // [Internal] Used by TabItemButton, change the tab item behavior to mimic a button }; // Storage for one active tab item (sizeof() 28~32 bytes) @@ -1737,7 +1738,8 @@ struct ImGuiTabBar float LastTabContentHeight; // Record the height of contents submitted below the tab bar float WidthAllTabs; // Actual width of all tabs (locked during layout) float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped - float OffsetNextTab; // Distance from BarRect.Min.x, incremented with each BeginTabItem() call, not used if ImGuiTabBarFlags_Reorderable if set. + float LeadingWidth; // Total width used by leading button + float TrailingWidth; // Total width used by trailing button float ScrollingAnim; float ScrollingTarget; float ScrollingTargetDistToVisibility; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index abc3f16c..79031027 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6814,7 +6814,8 @@ ImGuiTabBar::ImGuiTabBar() SelectedTabId = NextSelectedTabId = VisibleTabId = 0; CurrFrameVisible = PrevFrameVisible = -1; LastTabContentHeight = 0.0f; - WidthAllTabs = WidthAllTabsIdeal = OffsetNextTab = 0.0f; + WidthAllTabs = WidthAllTabsIdeal = 0.0f; + LeadingWidth = TrailingWidth = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; @@ -6824,6 +6825,17 @@ ImGuiTabBar::ImGuiTabBar() LastTabItemIdx = -1; } +static int IMGUI_CDECL TabItemComparerByPositionAndIndex(const void* lhs, const void* rhs) +{ + const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; + const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; + const int a_position = (a->Flags & ImGuiTabItemFlags_Leading) ? 0 : (a->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + const int b_position = (b->Flags & ImGuiTabItemFlags_Leading) ? 0 : (b->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + if (a_position != b_position) + return a_position - b_position; + return (int)(a->IndexDuringLayout - b->IndexDuringLayout); +} + static int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs) { const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; @@ -6950,6 +6962,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Garbage collect by compacting list int tab_dst_n = 0; + bool need_sort_trailing_or_leading = false; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; @@ -6963,11 +6976,21 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) } if (tab_dst_n != tab_src_n) tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n]; + + tab_bar->Tabs[tab_dst_n].IndexDuringLayout = (ImS8)tab_dst_n; + if (tab_dst_n > 0 && (tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Leading) && !(tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Leading)) + need_sort_trailing_or_leading = true; + if (tab_dst_n > 0 && (tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Trailing) && !(tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Trailing)) + need_sort_trailing_or_leading = true; + tab_dst_n++; } if (tab_bar->Tabs.Size != tab_dst_n) tab_bar->Tabs.resize(tab_dst_n); + if (need_sort_trailing_or_leading) + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByPositionAndIndex); + // Setup next selected tab ImGuiID scroll_track_selected_tab_id = 0; if (tab_bar->NextSelectedTabId) @@ -6989,11 +7012,13 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!) const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; if (tab_list_popup_button) - if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! + if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; // Compute ideal widths - g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); + g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); // Reserve for maximum possible number of tabs, + int tab_n_shrinkable = 0; // ..but buttons won't shrink + tab_bar->LeadingWidth = tab_bar->TrailingWidth = 0.0f; float width_total_contents = 0.0f; ImGuiTabItem* most_recently_selected_tab = NULL; bool found_selected_tab_id = false; @@ -7003,7 +7028,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible); if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) - most_recently_selected_tab = tab; + if (!(tab->Flags & ImGuiTabItemFlags_Button)) + most_recently_selected_tab = tab; if (tab->ID == tab_bar->SelectedTabId) found_selected_tab_id = true; @@ -7014,22 +7040,29 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true; tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x; - width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->ContentWidth; - - // Store data so we can build an array sorted by width if we need to shrink tabs down - g.ShrinkWidthBuffer[tab_n].Index = tab_n; - g.ShrinkWidthBuffer[tab_n].Width = tab->ContentWidth; + float width = tab->ContentWidth; + if (tab->Flags & ImGuiTabItemFlags_Leading) + tab_bar->LeadingWidth += width + g.Style.ItemInnerSpacing.x; + else if (tab->Flags & ImGuiTabItemFlags_Trailing) + tab_bar->TrailingWidth += width + g.Style.ItemInnerSpacing.x; + else + { + width_total_contents += width + (tab_n_shrinkable > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); + // Store data so we can build an array sorted by width if we need to shrink tabs down + g.ShrinkWidthBuffer[tab_n_shrinkable].Index = tab_n; + g.ShrinkWidthBuffer[tab_n_shrinkable].Width = tab->ContentWidth; + tab_n_shrinkable++; + } } // Compute width - const float initial_offset_x = 0.0f; // g.Style.ItemInnerSpacing.x; - const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - initial_offset_x, 0.0f); + const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - tab_bar->LeadingWidth - tab_bar->TrailingWidth, 0.0f); float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f; - if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown)) + if (width_excess > 0.0f && !(tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) { // If we don't have enough room, resize down the largest tabs first - ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess); - for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); + for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index].Width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); } else @@ -7044,26 +7077,44 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) } // Layout all active tabs - float offset_x = initial_offset_x; - float offset_x_ideal = offset_x; - tab_bar->OffsetNextTab = offset_x; // This is used by non-reorderable tab bar where the submission order is always honored. + float offset_x_button_leading = 0.0f; + float offset_x_button_trailing = tab_bar->BarRect.GetWidth() - tab_bar->TrailingWidth + g.Style.ItemInnerSpacing.x; + float offset_x_regular = tab_bar->LeadingWidth; + float offset_x_ideal = offset_x_regular; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - tab->Offset = offset_x; - if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID) - scroll_track_selected_tab_id = tab->ID; - offset_x += tab->Width + g.Style.ItemInnerSpacing.x; - offset_x_ideal += tab->ContentWidth + g.Style.ItemInnerSpacing.x; + float width = tab->Width + g.Style.ItemInnerSpacing.x; + if (tab->Flags & ImGuiTabItemFlags_Leading) + { + tab->Offset = offset_x_button_leading; + offset_x_button_leading += width; + } + else if (tab->Flags & ImGuiTabItemFlags_Trailing) + { + tab->Offset = offset_x_button_trailing; + offset_x_button_trailing += width; + } + else + { + tab->Offset = offset_x_regular; + if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID) + scroll_track_selected_tab_id = tab->ID; + offset_x_regular += width; + offset_x_ideal += tab->ContentWidth + g.Style.ItemInnerSpacing.x; + } } - tab_bar->WidthAllTabs = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); - tab_bar->WidthAllTabsIdeal = ImMax(offset_x_ideal - g.Style.ItemInnerSpacing.x, 0.0f); + tab_bar->WidthAllTabs = ImMax(offset_x_regular - g.Style.ItemInnerSpacing.x + tab_bar->TrailingWidth, 0.0f); + tab_bar->WidthAllTabsIdeal = ImMax(offset_x_ideal - g.Style.ItemInnerSpacing.x + tab_bar->TrailingWidth, 0.0f); // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->WidthAllTabs > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) - if (ImGuiTabItem* tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x! - scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; + if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x and each trailing tab->Offset + if (scroll_track_selected_tab->Flags & ImGuiTabItemFlags_Button) + scroll_track_selected_tab_id = scroll_track_selected_tab->ID; + else + scroll_track_selected_tab_id = tab_bar->SelectedTabId = scroll_track_selected_tab->ID; // If we have lost the selected tab, select the next most recently active one if (found_selected_tab_id == false) @@ -7103,6 +7154,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos = tab_bar->BarRect.Min; ItemSize(ImVec2(tab_bar->WidthAllTabsIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); + + window->DrawList->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Min + ImVec2(tab_bar->LeadingWidth, tab_bar->BarRect.GetHeight()), IM_COL32(255, 0, 0, 255)); + window->DrawList->AddRect(tab_bar->BarRect.Max - ImVec2(tab_bar->TrailingWidth, tab_bar->BarRect.GetHeight()), tab_bar->BarRect.Max, IM_COL32(0, 255, 0, 255)); } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. @@ -7149,6 +7203,7 @@ void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) // Called on manual closure attempt void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { + IM_ASSERT(!(tab->Flags & ImGuiTabItemFlags_Button)); if (!(tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) { // This will remove a frame of lag for selecting another tab on closure. @@ -7176,9 +7231,13 @@ static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling) static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { + if (tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) + return; + ImGuiContext& g = *GImGui; float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) int order = tab_bar->GetTabOrder(tab); + float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f); float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; @@ -7205,7 +7264,7 @@ void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, in bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar) { ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId); - if (!tab1) + if (tab1 == NULL || (tab1->Flags & ImGuiTabItemFlags_NoReorder)) return false; //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools @@ -7213,11 +7272,16 @@ bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar) if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size) return false; + // Reordered TabItem must share the same position flags than target ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order]; + if (tab2->Flags & ImGuiTabItemFlags_NoReorder) + return false; + if ((tab1->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (tab2->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing))) + return false; + ImGuiTabItem item_tmp = *tab1; *tab1 = *tab2; *tab2 = item_tmp; - tab1 = tab2 = NULL; if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings) MarkIniSettingsDirty(); @@ -7262,10 +7326,32 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) { int selected_order = tab_bar->GetTabOrder(tab_item); int target_order = selected_order + select_dir; - tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible + + // Skip tab item buttons until another tab item is found or end is reached + while (tab_to_scroll_to == NULL) + { + // If we are at the end of the list, still scroll to make our tab visible + tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; + + // Cross through buttons + // (even if first/last item is a button, return it so we can update the scroll) + if (tab_to_scroll_to->Flags & ImGuiTabItemFlags_Button) + { + target_order += select_dir; + selected_order += select_dir; + tab_to_scroll_to = (target_order <= 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL; + } + } } window->DC.CursorPos = backup_cursor_pos; + tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f; + for (int i = 0; i < tab_bar->Tabs.Size; ++i) + { + ImGuiTabItem* tab = &tab_bar->Tabs[i]; + if (tab->Flags & ImGuiTabItemFlags_Trailing) + tab->Offset -= scrolling_buttons_width + 1.0f; + } return tab_to_scroll_to; } @@ -7294,6 +7380,9 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + if (tab->Flags & ImGuiTabItemFlags_Button) + continue; + const char* tab_name = tab_bar->GetTabName(tab); if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID)) tab_to_select = tab; @@ -7310,6 +7399,7 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) //------------------------------------------------------------------------- // - BeginTabItem() // - EndTabItem() +// - TabItemButton() // - TabItemEx() [Internal] // - SetTabItemClosed() // - TabItemCalcSize() [Internal] @@ -7330,6 +7420,8 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; } + IM_ASSERT_USER_ERROR(!(flags & ImGuiTabItemFlags_Button), "BeginTabItem() Can't be used with button flags, use TabItemButton() instead!"); + bool ret = TabItemEx(tab_bar, label, p_open, flags); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) { @@ -7358,6 +7450,22 @@ void ImGui::EndTabItem() window->IDStack.pop_back(); } +bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return false; + + ImGuiTabBar* tab_bar = g.CurrentTabBar; + if (tab_bar == NULL) + { + IM_ASSERT_USER_ERROR(tab_bar, "TabItemButton() needs to be called between BeginTabBar() and EndTabBar()!"); + return false; + } + return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder); +} + bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags) { // Layout whole tab bar if not already done @@ -7383,6 +7491,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, return false; } + IM_ASSERT(!p_open || (p_open && !(flags & ImGuiTabItemFlags_Button))); // TabItemButton should not have visible content + // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented) if (flags & ImGuiTabItemFlags_NoCloseButton) p_open = NULL; @@ -7410,6 +7520,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0; const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount); + const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0; tab->LastFrameVisible = g.FrameCount; tab->Flags = flags; @@ -7417,20 +7528,14 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab->NameOffset = (ImS16)tab_bar->TabsNames.size(); tab_bar->TabsNames.append(label, label + strlen(label) + 1); - // If we are not reorderable, always reset offset based on submission order. - // (We already handled layout and sizing using the previous known order, but sizing is not affected by order!) - if (!tab_appearing && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) - { - tab->Offset = tab_bar->OffsetNextTab; - tab_bar->OffsetNextTab += tab->Width + g.Style.ItemInnerSpacing.x; - } - // Update selected tab if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0) if (!tab_bar_appearing || tab_bar->SelectedTabId == 0) - tab_bar->NextSelectedTabId = id; // New tabs gets activated + if (!is_tab_button) + tab_bar->NextSelectedTabId = id; // New tabs gets activated if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar - tab_bar->NextSelectedTabId = id; + if (!is_tab_button) + tab_bar->NextSelectedTabId = id; // Lock visibility // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!) @@ -7450,6 +7555,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true); ItemAdd(ImRect(), id); PopItemFlag(); + if (is_tab_button) + return false; return tab_contents_visible; } @@ -7461,14 +7568,21 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Layout size.x = tab->Width; - window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_FLOOR(tab->Offset - tab_bar->ScrollingAnim), 0.0f); + //if (is_tab_button && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown)) + if (tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) + window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f); + else + window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_FLOOR(tab->Offset - tab_bar->ScrollingAnim), 0.0f); ImVec2 pos = window->DC.CursorPos; ImRect bb(pos, pos + size); // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) - bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x) || (bb.Max.x > tab_bar->BarRect.Max.x); + // If TabBar fitting policy is scroll, then just clip through the BarRect + float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->LeadingWidth; + float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->TrailingWidth; // Leading buttons will be clipped by BarRect.Max.x, trailing buttons will be clipped at BarRect.Minx + LeadingsWidth + bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x + offset_leading) || (bb.Max.x + offset_trailing > tab_bar->BarRect.Max.x); if (want_clip_rect) - PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x, bb.Max.y), true); + PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x + offset_leading), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x - offset_trailing, bb.Max.y), true); ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; ItemSize(bb.GetSize(), style.FramePadding.y); @@ -7483,12 +7597,12 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } // Click to Select a tab - ImGuiButtonFlags button_flags = (ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_AllowItemOverlap); + ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowItemOverlap); if (g.DragDropActive) button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); - if (pressed) + if (pressed && !is_tab_button) tab_bar->NextSelectedTabId = id; hovered |= (g.HoveredId == id); @@ -7534,7 +7648,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1))) - tab_bar->NextSelectedTabId = id; + if (!is_tab_button) + tab_bar->NextSelectedTabId = id; if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; @@ -7559,6 +7674,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip)) SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); + IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected + if (is_tab_button) + return pressed; return tab_contents_visible; } @@ -7597,7 +7715,7 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI const float width = bb.GetWidth(); IM_UNUSED(flags); IM_ASSERT(width > 0.0f); - const float rounding = ImMax(0.0f, ImMin(g.Style.TabRounding, width * 0.5f - 1.0f)); + const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f)); const float y1 = bb.Min.y + 1.0f; const float y2 = bb.Max.y - 1.0f; draw_list->PathLineTo(ImVec2(bb.Min.x, y2)); From f23c39c395e4412f6f83786f591bdc4e727af203 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 27 Aug 2020 15:16:16 +0200 Subject: [PATCH 280/959] Tab Bar: Fixed handling of scrolling policy with leading/trailing tabs. + warning fixes + bunch of renaming. (#3291) Demo tweaks. --- imgui.cpp | 11 ++++- imgui_demo.cpp | 72 ++++++++++------------------ imgui_internal.h | 7 +-- imgui_widgets.cpp | 120 +++++++++++++++++++++++++++------------------- 4 files changed, 109 insertions(+), 101 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ec107aed..427fffc9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10559,6 +10559,15 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } bool open = ImGui::TreeNode(tab_bar, "%s", buf); if (!is_active) { PopStyleColor(); } + if (is_active && ImGui::IsItemHovered()) + { + ImDrawList* draw_list = ImGui::GetForegroundDrawList(); + draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); + if (tab_bar->WidthLeading > 0.0f) + draw_list->AddLine(ImVec2(tab_bar->BarRect.Min.x + tab_bar->WidthLeading, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Min.x + tab_bar->WidthLeading, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + if (tab_bar->WidthTrailing > 0.0f) + draw_list->AddLine(ImVec2(tab_bar->BarRect.Max.x - tab_bar->WidthTrailing, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x - tab_bar->WidthTrailing, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + } if (open) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) @@ -10567,7 +10576,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::PushID(tab); if (ImGui::SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); if (ImGui::SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } ImGui::SameLine(); - ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : ""); + ImGui::Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "", tab->Offset, tab->Width, tab->ContentWidth); ImGui::PopID(); } ImGui::TreePop(); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 42a3bf31..3cc153cb 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2355,16 +2355,15 @@ static void ShowDemoWindowLayout() ImGui::TreePop(); } - if (ImGui::TreeNode("TabItem Button")) + if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags")) { - static int next_id = 0; - static ImVector tabs_list; - if (next_id == 0) // Initialize with a default tab - for (int i = 0; i < 9; i++) - tabs_list.push_back(next_id++); + static ImVector active_tabs; + static int next_tab_id = 0; + if (next_tab_id == 0) // Initialize with some default tabs + for (int i = 0; i < 3; i++) + active_tabs.push_back(next_tab_id++); static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; - ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_Reorderable); ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); @@ -2375,63 +2374,40 @@ static void ShowDemoWindowLayout() static bool show_trailing_button = true; ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); - static bool enable_position = false; - ImGui::Checkbox("Enable Leading/Trailing TabItem()", &enable_position); if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { - if (show_leading_button) + // Demo Leading Tabs: click the "?" button to open a menu + // Note that it is possible to submit regular non-button tabs with Leading/Trailing flags, + // or Button without Leading/Trailing flags... but they tend to make more sense together. + if (show_leading_button && ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) + ImGui::OpenPopup("MyHelpMenu"); + if (ImGui::BeginPopup("MyHelpMenu")) { - if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) - tabs_list.push_back(next_id++); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Add a new TabItem() in the tab bar"); - - // Popup Context also works with TabItemButton - if (ImGui::BeginPopupContextItem()) - { - ImGui::Text("I'm a popup!"); - if (ImGui::Button("Close")) - ImGui::CloseCurrentPopup(); - ImGui::EndPopup(); - } + ImGui::Selectable("Hello!"); + ImGui::EndPopup(); } - bool close_current_tab = false; - if (show_trailing_button) - { - if (ImGui::TabItemButton("X", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) - close_current_tab = true; - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Close the currently selected TabItem()"); - } + // Demo Trailing Tabs: click the "+" button to add a new tab (in your app you may want to use a font icon instead of the "+") + if (show_trailing_button && ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) + active_tabs.push_back(next_tab_id++); - for (int n = 0; n < tabs_list.Size; ) + // Submit our regular tabs + for (int n = 0; n < active_tabs.Size; ) { - int mod = tabs_list[n] % 3; - ImGuiTabItemFlags flags = mod == 0 ? 0 : mod == 1 ? ImGuiTabItemFlags_Leading : ImGuiTabItemFlags_Trailing; - if (!enable_position) - flags = 0; - - char name[16]; - snprintf(name, IM_ARRAYSIZE(name), "%04d", tabs_list[n]); bool open = true; - if (ImGui::BeginTabItem(name, &open, flags)) + char name[16]; + snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]); + if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None)) { ImGui::Text("This is the %s tab!", name); ImGui::EndTabItem(); - - if (close_current_tab) - { - open = false; - ImGui::SetTabItemClosed(name); - } } if (!open) - tabs_list.erase(tabs_list.Data + n); + active_tabs.erase(active_tabs.Data + n); else - ++n; + n++; } ImGui::EndTabBar(); diff --git a/imgui_internal.h b/imgui_internal.h index 0563e7c5..5a3d468b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1719,9 +1719,10 @@ struct ImGuiTabItem float ContentWidth; // Width of actual contents, stored during BeginTabItem() call ImS16 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames ImS8 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable + ImS8 IndexDuringLayout; // Index only used during TabBarLayout() bool WantClose; // Marked as closed by SetTabItemClosed() - ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; WantClose = false; } + ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; IndexDuringLayout = -1; WantClose = false; } }; // Storage for a tab bar (sizeof() 92~96 bytes) @@ -1738,8 +1739,8 @@ struct ImGuiTabBar float LastTabContentHeight; // Record the height of contents submitted below the tab bar float WidthAllTabs; // Actual width of all tabs (locked during layout) float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped - float LeadingWidth; // Total width used by leading button - float TrailingWidth; // Total width used by trailing button + float WidthLeading; // Total width used by leading button + float WidthTrailing; // Total width used by trailing button float ScrollingAnim; float ScrollingTarget; float ScrollingTargetDistToVisibility; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 79031027..35c47793 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6815,7 +6815,7 @@ ImGuiTabBar::ImGuiTabBar() CurrFrameVisible = PrevFrameVisible = -1; LastTabContentHeight = 0.0f; WidthAllTabs = WidthAllTabsIdeal = 0.0f; - LeadingWidth = TrailingWidth = 0.0f; + WidthLeading = WidthTrailing = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; @@ -7015,11 +7015,15 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; + // Reserve shrink buffer for maximum possible number of tabs (but tabs with Trailing/Leading won't shrink) + int tab_n_shrinkable = 0; + g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); + // Compute ideal widths - g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); // Reserve for maximum possible number of tabs, - int tab_n_shrinkable = 0; // ..but buttons won't shrink - tab_bar->LeadingWidth = tab_bar->TrailingWidth = 0.0f; - float width_total_contents = 0.0f; + float width_central = 0.0f; + tab_bar->WidthLeading = tab_bar->WidthTrailing = 0.0f; + const float tab_max_width = TabBarCalcMaxTabWidth(); + ImGuiTabItem* most_recently_selected_tab = NULL; bool found_selected_tab_id = false; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) @@ -7027,9 +7031,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible); - if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) - if (!(tab->Flags & ImGuiTabItemFlags_Button)) - most_recently_selected_tab = tab; + if ((most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) && !(tab->Flags & ImGuiTabItemFlags_Button)) + most_recently_selected_tab = tab; if (tab->ID == tab_bar->SelectedTabId) found_selected_tab_id = true; @@ -7042,79 +7045,95 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) float width = tab->ContentWidth; if (tab->Flags & ImGuiTabItemFlags_Leading) - tab_bar->LeadingWidth += width + g.Style.ItemInnerSpacing.x; + { + tab_bar->WidthLeading += width + g.Style.ItemInnerSpacing.x; + } else if (tab->Flags & ImGuiTabItemFlags_Trailing) - tab_bar->TrailingWidth += width + g.Style.ItemInnerSpacing.x; + { + tab_bar->WidthTrailing += width + g.Style.ItemInnerSpacing.x; + } else { - width_total_contents += width + (tab_n_shrinkable > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); - // Store data so we can build an array sorted by width if we need to shrink tabs down - g.ShrinkWidthBuffer[tab_n_shrinkable].Index = tab_n; + width = ImMin(tab->ContentWidth, tab_max_width); + width_central += width + (tab_n_shrinkable > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); + g.ShrinkWidthBuffer[tab_n_shrinkable].Index = tab_n; // Store data so we can build an array sorted by width if we need to shrink tabs down g.ShrinkWidthBuffer[tab_n_shrinkable].Width = tab->ContentWidth; tab_n_shrinkable++; } + + IM_ASSERT(width > 0.0f); + tab->Width = width; } // Compute width - const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - tab_bar->LeadingWidth - tab_bar->TrailingWidth, 0.0f); - float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f; + const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - tab_bar->WidthLeading - tab_bar->WidthTrailing, 0.0f); + float width_excess = (width_avail < width_central) ? (width_central - width_avail) : 0.0f; if (width_excess > 0.0f && !(tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) { // If we don't have enough room, resize down the largest tabs first ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index].Width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); - } - else - { - const float tab_max_width = TabBarCalcMaxTabWidth(); + width_central -= width_excess; +#if 0 + width_central = (tab_bar->WidthLeading > 0.0f) ? -g.Style.ItemInnerSpacing.x : 0.0f; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - tab->Width = ImMin(tab->ContentWidth, tab_max_width); - IM_ASSERT(tab->Width > 0.0f); + if ((tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) == 0) + width_central += tab->Width + g.Style.ItemInnerSpacing.x; } +#endif } // Layout all active tabs - float offset_x_button_leading = 0.0f; - float offset_x_button_trailing = tab_bar->BarRect.GetWidth() - tab_bar->TrailingWidth + g.Style.ItemInnerSpacing.x; - float offset_x_regular = tab_bar->LeadingWidth; - float offset_x_ideal = offset_x_regular; + float offset_x_pos_leading = 0.0f; + float offset_x_pos_central = tab_bar->WidthLeading; +#if 0 + float offset_x_pos_trailing = tab_bar->BarRect.GetWidth() - tab_bar->WidthTrailing + g.Style.ItemInnerSpacing.x; // Right-most layout +#else + float offset_x_pos_trailing = tab_bar->WidthLeading + width_central; // Trailing layout + if (offset_x_pos_trailing > 0.0f) + offset_x_pos_trailing += g.Style.ItemInnerSpacing.x; +#endif + + float width_ideal = tab_bar->WidthLeading; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; float width = tab->Width + g.Style.ItemInnerSpacing.x; if (tab->Flags & ImGuiTabItemFlags_Leading) { - tab->Offset = offset_x_button_leading; - offset_x_button_leading += width; + tab->Offset = offset_x_pos_leading; + offset_x_pos_leading += width; } else if (tab->Flags & ImGuiTabItemFlags_Trailing) { - tab->Offset = offset_x_button_trailing; - offset_x_button_trailing += width; + tab->Offset = offset_x_pos_trailing; + offset_x_pos_trailing += width; } else { - tab->Offset = offset_x_regular; + tab->Offset = offset_x_pos_central; if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID) scroll_track_selected_tab_id = tab->ID; - offset_x_regular += width; - offset_x_ideal += tab->ContentWidth + g.Style.ItemInnerSpacing.x; + offset_x_pos_central += width; + width_ideal += tab->ContentWidth + g.Style.ItemInnerSpacing.x; } } - tab_bar->WidthAllTabs = ImMax(offset_x_regular - g.Style.ItemInnerSpacing.x + tab_bar->TrailingWidth, 0.0f); - tab_bar->WidthAllTabsIdeal = ImMax(offset_x_ideal - g.Style.ItemInnerSpacing.x + tab_bar->TrailingWidth, 0.0f); + tab_bar->WidthAllTabs = ImMax(offset_x_pos_central - g.Style.ItemInnerSpacing.x + tab_bar->WidthTrailing, 0.0f); + tab_bar->WidthAllTabsIdeal = ImMax(width_ideal - g.Style.ItemInnerSpacing.x + tab_bar->WidthTrailing, 0.0f); // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->WidthAllTabs > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x and each trailing tab->Offset + { if (scroll_track_selected_tab->Flags & ImGuiTabItemFlags_Button) scroll_track_selected_tab_id = scroll_track_selected_tab->ID; else scroll_track_selected_tab_id = tab_bar->SelectedTabId = scroll_track_selected_tab->ID; + } // If we have lost the selected tab, select the next most recently active one if (found_selected_tab_id == false) @@ -7154,9 +7173,6 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos = tab_bar->BarRect.Min; ItemSize(ImVec2(tab_bar->WidthAllTabsIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); - - window->DrawList->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Min + ImVec2(tab_bar->LeadingWidth, tab_bar->BarRect.GetHeight()), IM_COL32(255, 0, 0, 255)); - window->DrawList->AddRect(tab_bar->BarRect.Max - ImVec2(tab_bar->TrailingWidth, tab_bar->BarRect.GetHeight()), tab_bar->BarRect.Max, IM_COL32(0, 255, 0, 255)); } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. @@ -7238,18 +7254,24 @@ static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) int order = tab_bar->GetTabOrder(tab); - float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f); - float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); + // Scrolling happens only in the central section (leading/trailing sections are not scrolling) + float scrollable_width = tab_bar->BarRect.GetWidth() - tab_bar->WidthLeading - tab_bar->WidthTrailing; + + // We make all tabs positions all relative WidthLeading to make code simpler + float tab_x1 = tab->Offset - tab_bar->WidthLeading + (order > 0 ? -margin : 0.0f); + float tab_x2 = tab->Offset - tab_bar->WidthLeading + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; - if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= tab_bar->BarRect.GetWidth())) + if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width)) { + // Scroll to the left tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f); tab_bar->ScrollingTarget = tab_x1; } - else if (tab_bar->ScrollingTarget < tab_x2 - tab_bar->BarRect.GetWidth()) + else if (tab_bar->ScrollingTarget < tab_x2 - scrollable_width) { - tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - tab_bar->BarRect.GetWidth()) - tab_bar->ScrollingAnim, 0.0f); - tab_bar->ScrollingTarget = tab_x2 - tab_bar->BarRect.GetWidth(); + // Scroll to the right + tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar->ScrollingAnim, 0.0f); + tab_bar->ScrollingTarget = tab_x2 - scrollable_width; } } @@ -7420,7 +7442,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; } - IM_ASSERT_USER_ERROR(!(flags & ImGuiTabItemFlags_Button), "BeginTabItem() Can't be used with button flags, use TabItemButton() instead!"); + IM_ASSERT(!(flags & ImGuiTabItemFlags_Button)); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! bool ret = TabItemEx(tab_bar, label, p_open, flags); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) @@ -7460,7 +7482,7 @@ bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) ImGuiTabBar* tab_bar = g.CurrentTabBar; if (tab_bar == NULL) { - IM_ASSERT_USER_ERROR(tab_bar, "TabItemButton() needs to be called between BeginTabBar() and EndTabBar()!"); + IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; } return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder); @@ -7491,7 +7513,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, return false; } - IM_ASSERT(!p_open || (p_open && !(flags & ImGuiTabItemFlags_Button))); // TabItemButton should not have visible content + IM_ASSERT(!p_open || !(flags & ImGuiTabItemFlags_Button)); + IM_ASSERT((flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)); // Can't use both Leading and Trailing // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented) if (flags & ImGuiTabItemFlags_NoCloseButton) @@ -7568,7 +7591,6 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Layout size.x = tab->Width; - //if (is_tab_button && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown)) if (tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f); else @@ -7578,8 +7600,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) // If TabBar fitting policy is scroll, then just clip through the BarRect - float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->LeadingWidth; - float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->TrailingWidth; // Leading buttons will be clipped by BarRect.Max.x, trailing buttons will be clipped at BarRect.Minx + LeadingsWidth + float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->WidthLeading; + float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->WidthTrailing; // Leading buttons will be clipped by BarRect.Max.x, trailing buttons will be clipped at BarRect.Minx + LeadingsWidth bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x + offset_leading) || (bb.Max.x + offset_trailing > tab_bar->BarRect.Max.x); if (want_clip_rect) PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x + offset_leading), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x - offset_trailing, bb.Max.y), true); From 7ac16c02cc1e1c6bcbdecdd5ac0746b157395084 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Thu, 27 Aug 2020 16:18:25 +0200 Subject: [PATCH 281/959] Tab Bar: Fix multiple width and position computation issue. (#3291) --- imgui.cpp | 8 +- imgui_internal.h | 15 ++- imgui_widgets.cpp | 234 ++++++++++++++++++++++++++++------------------ 3 files changed, 159 insertions(+), 98 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 427fffc9..4518cd80 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10563,10 +10563,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) { ImDrawList* draw_list = ImGui::GetForegroundDrawList(); draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); - if (tab_bar->WidthLeading > 0.0f) - draw_list->AddLine(ImVec2(tab_bar->BarRect.Min.x + tab_bar->WidthLeading, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Min.x + tab_bar->WidthLeading, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); - if (tab_bar->WidthTrailing > 0.0f) - draw_list->AddLine(ImVec2(tab_bar->BarRect.Max.x - tab_bar->WidthTrailing, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x - tab_bar->WidthTrailing, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + if (tab_bar->LeadingSection.Width > 0.0f) + draw_list->AddLine(ImVec2(tab_bar->BarRect.Min.x + tab_bar->LeadingSection.Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Min.x + tab_bar->LeadingSection.Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + if (tab_bar->TrailingSection.Width > 0.0f) + draw_list->AddLine(ImVec2(tab_bar->BarRect.Max.x - tab_bar->TrailingSection.Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x - tab_bar->TrailingSection.Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); } if (open) { diff --git a/imgui_internal.h b/imgui_internal.h index 5a3d468b..bb633253 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1725,6 +1725,16 @@ struct ImGuiTabItem ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; IndexDuringLayout = -1; WantClose = false; } }; +struct TabBarLayoutSection +{ + ImGuiTabItem* Tabs; // Pointer to the first tab_bar->Tabs matching the section + int TabCount; + float Width; + float WidthIdeal; + float InnerSpacing; // Horizontal ItemInnerSpacing, used by Leading/Trailing section, to correctly offset from Central section + TabBarLayoutSection() { Tabs = NULL; TabCount = 0; Width = 0.0f; WidthIdeal = 0.0f; InnerSpacing = 0.0f; } +}; + // Storage for a tab bar (sizeof() 92~96 bytes) struct ImGuiTabBar { @@ -1739,8 +1749,6 @@ struct ImGuiTabBar float LastTabContentHeight; // Record the height of contents submitted below the tab bar float WidthAllTabs; // Actual width of all tabs (locked during layout) float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped - float WidthLeading; // Total width used by leading button - float WidthTrailing; // Total width used by trailing button float ScrollingAnim; float ScrollingTarget; float ScrollingTargetDistToVisibility; @@ -1749,6 +1757,9 @@ struct ImGuiTabBar ImGuiID ReorderRequestTabId; ImS8 ReorderRequestDir; ImS8 TabsActiveCount; // Number of tabs submitted this frame. + TabBarLayoutSection LeadingSection; + TabBarLayoutSection CentralSection; + TabBarLayoutSection TrailingSection; bool WantLayout; bool VisibleTabWasSubmitted; short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 35c47793..0c81dd0b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6785,6 +6785,8 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, // - BeginTabBarEx() [Internal] // - EndTabBar() // - TabBarLayout() [Internal] +// - TabBarLayoutComputeTabsWidth() [Internal] +// - TabBarLayoutActiveTabsForSection() [Internal] // - TabBarCalcTabID() [Internal] // - TabBarCalcMaxTabWidth() [Internal] // - TabBarFindTabById() [Internal] @@ -6800,6 +6802,8 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, namespace ImGui { static void TabBarLayout(ImGuiTabBar* tab_bar); + static void TabBarLayoutComputeTabsWidth(ImGuiTabBar* tab_bar, bool scrolling_buttons, float scrolling_buttons_width); + static float TabBarLayoutActiveTabsForSection(ImGuiTabBar* tab_bar, TabBarLayoutSection* section, float next_tab_offset); static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label); static float TabBarCalcMaxTabWidth(); static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); @@ -6815,7 +6819,6 @@ ImGuiTabBar::ImGuiTabBar() CurrFrameVisible = PrevFrameVisible = -1; LastTabContentHeight = 0.0f; WidthAllTabs = WidthAllTabsIdeal = 0.0f; - WidthLeading = WidthTrailing = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; @@ -6857,6 +6860,12 @@ static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) return ImGuiPtrOrIndex(tab_bar); } +static ImVec2 GetTabBarScrollingButtonSize() +{ + ImGuiContext& g = *GImGui; + return ImVec2(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f); +} + bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) { ImGuiContext& g = *GImGui; @@ -6963,6 +6972,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Garbage collect by compacting list int tab_dst_n = 0; bool need_sort_trailing_or_leading = false; + tab_bar->LeadingSection.TabCount = tab_bar->CentralSection.TabCount = tab_bar->TrailingSection.TabCount = 0; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; @@ -6978,11 +6988,20 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n]; tab_bar->Tabs[tab_dst_n].IndexDuringLayout = (ImS8)tab_dst_n; - if (tab_dst_n > 0 && (tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Leading) && !(tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Leading)) + bool is_leading = (tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Leading) != 0; + bool is_trailing = (tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Trailing) != 0; + if (tab_dst_n > 0 && is_leading && !(tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Leading)) need_sort_trailing_or_leading = true; - if (tab_dst_n > 0 && (tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Trailing) && !(tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Trailing)) + if (tab_dst_n > 0 && (tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Trailing) && !is_trailing) need_sort_trailing_or_leading = true; + if (is_leading) + tab_bar->LeadingSection.TabCount++; + else if (is_trailing) + tab_bar->TrailingSection.TabCount++; + else + tab_bar->CentralSection.TabCount++; + tab_dst_n++; } if (tab_bar->Tabs.Size != tab_dst_n) @@ -6991,6 +7010,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (need_sort_trailing_or_leading) ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByPositionAndIndex); + tab_bar->LeadingSection.Tabs = tab_bar->Tabs.Data; + tab_bar->CentralSection.Tabs = tab_bar->Tabs.Data + tab_bar->LeadingSection.TabCount; + tab_bar->TrailingSection.Tabs = tab_bar->Tabs.Data + tab_bar->LeadingSection.TabCount + tab_bar->CentralSection.TabCount; + // Setup next selected tab ImGuiID scroll_track_selected_tab_id = 0; if (tab_bar->NextSelectedTabId) @@ -7015,13 +7038,11 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; - // Reserve shrink buffer for maximum possible number of tabs (but tabs with Trailing/Leading won't shrink) - int tab_n_shrinkable = 0; + // Reserve shrink buffer for maximum possible number of tabs g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); // Compute ideal widths - float width_central = 0.0f; - tab_bar->WidthLeading = tab_bar->WidthTrailing = 0.0f; + tab_bar->LeadingSection.Width = tab_bar->CentralSection.Width = tab_bar->TrailingSection.Width = 0.0f; const float tab_max_width = TabBarCalcMaxTabWidth(); ImGuiTabItem* most_recently_selected_tab = NULL; @@ -7035,6 +7056,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) most_recently_selected_tab = tab; if (tab->ID == tab_bar->SelectedTabId) found_selected_tab_id = true; + if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID) + scroll_track_selected_tab_id = tab->ID; // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, @@ -7043,91 +7066,44 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true; tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x; - float width = tab->ContentWidth; + float width = ImMin(tab->ContentWidth, tab_max_width); if (tab->Flags & ImGuiTabItemFlags_Leading) - { - tab_bar->WidthLeading += width + g.Style.ItemInnerSpacing.x; - } + tab_bar->LeadingSection.Width += width + (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); else if (tab->Flags & ImGuiTabItemFlags_Trailing) - { - tab_bar->WidthTrailing += width + g.Style.ItemInnerSpacing.x; - } + tab_bar->TrailingSection.Width += width + (tab_n > tab_bar->LeadingSection.TabCount + tab_bar->CentralSection.TabCount ? g.Style.ItemInnerSpacing.x : 0.0f); else - { - width = ImMin(tab->ContentWidth, tab_max_width); - width_central += width + (tab_n_shrinkable > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); - g.ShrinkWidthBuffer[tab_n_shrinkable].Index = tab_n; // Store data so we can build an array sorted by width if we need to shrink tabs down - g.ShrinkWidthBuffer[tab_n_shrinkable].Width = tab->ContentWidth; - tab_n_shrinkable++; - } + tab_bar->CentralSection.Width += width + (tab_n > tab_bar->LeadingSection.TabCount ? g.Style.ItemInnerSpacing.x : 0.0f); + + g.ShrinkWidthBuffer[tab_n].Index = tab_n; // Store data so we can build an array sorted by width if we need to shrink tabs down + g.ShrinkWidthBuffer[tab_n].Width = tab->ContentWidth; IM_ASSERT(width > 0.0f); tab->Width = width; } + tab_bar->LeadingSection.WidthIdeal = tab_bar->LeadingSection.Width; + tab_bar->CentralSection.WidthIdeal = tab_bar->CentralSection.Width; + tab_bar->TrailingSection.WidthIdeal = tab_bar->TrailingSection.Width; - // Compute width - const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - tab_bar->WidthLeading - tab_bar->WidthTrailing, 0.0f); - float width_excess = (width_avail < width_central) ? (width_central - width_avail) : 0.0f; - if (width_excess > 0.0f && !(tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) - { - // If we don't have enough room, resize down the largest tabs first - ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); - for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) - tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index].Width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); - width_central -= width_excess; -#if 0 - width_central = (tab_bar->WidthLeading > 0.0f) ? -g.Style.ItemInnerSpacing.x : 0.0f; - for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) - { - ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - if ((tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) == 0) - width_central += tab->Width + g.Style.ItemInnerSpacing.x; - } -#endif - } + // We want to know here if we'll need the scrolling buttons, to adjust available width with resizable leading/trailing + bool scrolling_buttons = (tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); + float scrolling_buttons_width = GetTabBarScrollingButtonSize().x * 2.0f; + TabBarLayoutComputeTabsWidth(tab_bar, scrolling_buttons, scrolling_buttons_width); // Layout all active tabs - float offset_x_pos_leading = 0.0f; - float offset_x_pos_central = tab_bar->WidthLeading; -#if 0 - float offset_x_pos_trailing = tab_bar->BarRect.GetWidth() - tab_bar->WidthTrailing + g.Style.ItemInnerSpacing.x; // Right-most layout -#else - float offset_x_pos_trailing = tab_bar->WidthLeading + width_central; // Trailing layout - if (offset_x_pos_trailing > 0.0f) - offset_x_pos_trailing += g.Style.ItemInnerSpacing.x; -#endif + tab_bar->WidthAllTabs = tab_bar->WidthAllTabsIdeal = 0.0f; + float next_tab_offset = 0.0f; - float width_ideal = tab_bar->WidthLeading; - for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) - { - ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - float width = tab->Width + g.Style.ItemInnerSpacing.x; - if (tab->Flags & ImGuiTabItemFlags_Leading) - { - tab->Offset = offset_x_pos_leading; - offset_x_pos_leading += width; - } - else if (tab->Flags & ImGuiTabItemFlags_Trailing) - { - tab->Offset = offset_x_pos_trailing; - offset_x_pos_trailing += width; - } - else - { - tab->Offset = offset_x_pos_central; - if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID) - scroll_track_selected_tab_id = tab->ID; - offset_x_pos_central += width; - width_ideal += tab->ContentWidth + g.Style.ItemInnerSpacing.x; - } - } - tab_bar->WidthAllTabs = ImMax(offset_x_pos_central - g.Style.ItemInnerSpacing.x + tab_bar->WidthTrailing, 0.0f); - tab_bar->WidthAllTabsIdeal = ImMax(width_ideal - g.Style.ItemInnerSpacing.x + tab_bar->WidthTrailing, 0.0f); + // TabBarLayoutActiveTabsForSection will also alter tab_bar->WidthAllTabs and WidthAllTabsIdeal + next_tab_offset = TabBarLayoutActiveTabsForSection(tab_bar, &tab_bar->LeadingSection, next_tab_offset); // Leading Section + next_tab_offset = TabBarLayoutActiveTabsForSection(tab_bar, &tab_bar->CentralSection, next_tab_offset); // Central Section + + // TabBarScrollingButtons will alter BarRect.Max.x, so we need to anticipate BarRect width reduction + next_tab_offset = ImMin(tab_bar->BarRect.GetWidth() - tab_bar->TrailingSection.Width - (scrolling_buttons ? scrolling_buttons_width + 1.0f : 0.0f), next_tab_offset); + TabBarLayoutActiveTabsForSection(tab_bar, &tab_bar->TrailingSection, next_tab_offset); // Trailing Section // Horizontal scrolling buttons - const bool scrolling_buttons = (tab_bar->WidthAllTabs > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) - if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x and each trailing tab->Offset + if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x { if (scroll_track_selected_tab->Flags & ImGuiTabItemFlags_Button) scroll_track_selected_tab_id = scroll_track_selected_tab->ID; @@ -7173,6 +7149,86 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos = tab_bar->BarRect.Min; ItemSize(ImVec2(tab_bar->WidthAllTabsIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); + +#ifdef IMGUI_ENABLE_TEST_ENGINE + if (g.IO.KeyAlt) + { + window->DrawList->AddRect(tab_bar->BarRect.Min, ImVec2(tab_bar->BarRect.Min.x + tab_bar->LeadingSection.Width, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255)); + window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - tab_bar->TrailingSection.Width, tab_bar->BarRect.Min.y), tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); + } +#endif +} + +static void ImGui::TabBarLayoutComputeTabsWidth(ImGuiTabBar* tab_bar, bool scrolling_buttons, float scrolling_buttons_width) +{ + ImGuiContext& g = *GImGui; + + // Compute Leading/Trailing relative additional horizontal inner spacing + float leading_trailing_common_inner_space = (tab_bar->LeadingSection.TabCount > 0 && tab_bar->TrailingSection.TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); + bool resizing_leading_trailing_only = (tab_bar->LeadingSection.Width + tab_bar->TrailingSection.Width + leading_trailing_common_inner_space) > (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)); + + tab_bar->LeadingSection.InnerSpacing = tab_bar->LeadingSection.TabCount > 0 && (tab_bar->CentralSection.TabCount + tab_bar->TrailingSection.TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + tab_bar->CentralSection.InnerSpacing = tab_bar->CentralSection.TabCount > 0 && tab_bar->TrailingSection.TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + tab_bar->TrailingSection.InnerSpacing = 0.0f; + + // Compute width + float width_excess = resizing_leading_trailing_only + ? (tab_bar->LeadingSection.Width + tab_bar->TrailingSection.Width + leading_trailing_common_inner_space) - (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)) + : ImMax(tab_bar->CentralSection.Width + tab_bar->CentralSection.InnerSpacing - (tab_bar->BarRect.GetWidth() - tab_bar->LeadingSection.Width - tab_bar->LeadingSection.InnerSpacing - tab_bar->TrailingSection.Width - tab_bar->TrailingSection.InnerSpacing), 0.0f); + + if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || resizing_leading_trailing_only) + { + // All tabs are in the ShrinkWidthBuffer, but we will only resize leading/trailing or central tabs, so rearrange internal data + if (resizing_leading_trailing_only) + memmove(g.ShrinkWidthBuffer.Data + tab_bar->LeadingSection.TabCount, g.ShrinkWidthBuffer.Data + tab_bar->LeadingSection.TabCount + tab_bar->CentralSection.TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->TrailingSection.TabCount); + else + memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + tab_bar->LeadingSection.TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->CentralSection.TabCount); + int tab_n_shrinkable = (resizing_leading_trailing_only ? tab_bar->LeadingSection.TabCount + tab_bar->TrailingSection.TabCount : tab_bar->CentralSection.TabCount); + + ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); + + // Total Leading and Trailing shrink values can be different, we need to keep track of how much each section was shrinked + float leading_excess = 0.0f; + float trailing_excess = 0.0f; + for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) + { + float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); + ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index]; + + if (tab->Flags & ImGuiTabItemFlags_Leading) + leading_excess += (tab->Width - shrinked_width); + else if (tab->Flags & ImGuiTabItemFlags_Trailing) + trailing_excess += (tab->Width - shrinked_width); + + tab->Width = shrinked_width; + } + + if (resizing_leading_trailing_only) + { + tab_bar->LeadingSection.Width -= leading_excess; + tab_bar->TrailingSection.Width -= trailing_excess; + } + else + { + tab_bar->CentralSection.Width -= width_excess; + } + } +} + +static float ImGui::TabBarLayoutActiveTabsForSection(ImGuiTabBar* tab_bar, TabBarLayoutSection* section, float next_tab_offset) +{ + ImGuiContext& g = *GImGui; + + for(int i = 0; i < section->TabCount; ++i) + { + ImGuiTabItem* tab = section->Tabs + i; + tab->Offset = next_tab_offset; + next_tab_offset += tab->Width + (i < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); + } + tab_bar->WidthAllTabs += ImMax(section->Width + section->InnerSpacing, 0.0f); + tab_bar->WidthAllTabsIdeal += ImMax(section->WidthIdeal + section->InnerSpacing, 0.0f); + + return next_tab_offset + section->InnerSpacing; } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. @@ -7255,11 +7311,11 @@ static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) int order = tab_bar->GetTabOrder(tab); // Scrolling happens only in the central section (leading/trailing sections are not scrolling) - float scrollable_width = tab_bar->BarRect.GetWidth() - tab_bar->WidthLeading - tab_bar->WidthTrailing; + float scrollable_width = tab_bar->BarRect.GetWidth() - tab_bar->LeadingSection.Width - tab_bar->TrailingSection.Width - tab_bar->CentralSection.InnerSpacing; - // We make all tabs positions all relative WidthLeading to make code simpler - float tab_x1 = tab->Offset - tab_bar->WidthLeading + (order > 0 ? -margin : 0.0f); - float tab_x2 = tab->Offset - tab_bar->WidthLeading + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); + // We make all tabs positions all relative LeadingSection.Width to make code simpler + float tab_x1 = tab->Offset - tab_bar->LeadingSection.Width + (order > tab_bar->LeadingSection.TabCount - 1 ? -margin : 0.0f); + float tab_x2 = tab->Offset - tab_bar->LeadingSection.Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - tab_bar->TrailingSection.TabCount ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width)) { @@ -7315,7 +7371,7 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f); + const ImVec2 arrow_button_size = GetTabBarScrollingButtonSize(); const float scrolling_buttons_width = arrow_button_size.x * 2.0f; const ImVec2 backup_cursor_pos = window->DC.CursorPos; @@ -7368,12 +7424,6 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) window->DC.CursorPos = backup_cursor_pos; tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f; - for (int i = 0; i < tab_bar->Tabs.Size; ++i) - { - ImGuiTabItem* tab = &tab_bar->Tabs[i]; - if (tab->Flags & ImGuiTabItemFlags_Trailing) - tab->Offset -= scrolling_buttons_width + 1.0f; - } return tab_to_scroll_to; } @@ -7599,9 +7649,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImRect bb(pos, pos + size); // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) - // If TabBar fitting policy is scroll, then just clip through the BarRect - float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->WidthLeading; - float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->WidthTrailing; // Leading buttons will be clipped by BarRect.Max.x, trailing buttons will be clipped at BarRect.Minx + LeadingsWidth + // Leading buttons will be clipped by BarRect.Max.x, Trailing buttons will be clipped at BarRect.Min.x + LeadingsWidth (+ spacing if there are some buttons), and central tabs will be clipped inbetween + float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->TrailingSection.Width + tab_bar->CentralSection.InnerSpacing; + float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->LeadingSection.Width + tab_bar->LeadingSection.InnerSpacing; bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x + offset_leading) || (bb.Max.x + offset_trailing > tab_bar->BarRect.Max.x); if (want_clip_rect) PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x + offset_leading), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x - offset_trailing, bb.Max.y), true); From 5e5f25e2dd2aa278ce799e7c012017643c6fcd61 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 3 Sep 2020 12:49:00 +0200 Subject: [PATCH 282/959] Tab Bar: Rename named sections members into array. Various tidying up. (#3291) --- imgui.cpp | 8 +-- imgui_demo.cpp | 2 +- imgui_internal.h | 18 +++--- imgui_widgets.cpp | 147 +++++++++++++++++++++------------------------- 4 files changed, 79 insertions(+), 96 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4518cd80..1d65396a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10563,10 +10563,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) { ImDrawList* draw_list = ImGui::GetForegroundDrawList(); draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); - if (tab_bar->LeadingSection.Width > 0.0f) - draw_list->AddLine(ImVec2(tab_bar->BarRect.Min.x + tab_bar->LeadingSection.Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Min.x + tab_bar->LeadingSection.Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); - if (tab_bar->TrailingSection.Width > 0.0f) - draw_list->AddLine(ImVec2(tab_bar->BarRect.Max.x - tab_bar->TrailingSection.Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x - tab_bar->TrailingSection.Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + if (tab_bar->Sections[0].Width > 0.0f) + draw_list->AddLine(ImVec2(tab_bar->BarRect.Min.x + tab_bar->Sections[0].Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Min.x + tab_bar->Sections[0].Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + if (tab_bar->Sections[2].Width > 0.0f) + draw_list->AddLine(ImVec2(tab_bar->BarRect.Max.x - tab_bar->Sections[2].Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x - tab_bar->Sections[2].Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); } if (open) { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3cc153cb..e1d31063 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2363,7 +2363,7 @@ static void ShowDemoWindowLayout() for (int i = 0; i < 3; i++) active_tabs.push_back(next_tab_id++); - static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; + static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); diff --git a/imgui_internal.h b/imgui_internal.h index bb633253..e61fbed7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1725,14 +1725,14 @@ struct ImGuiTabItem ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; IndexDuringLayout = -1; WantClose = false; } }; -struct TabBarLayoutSection +struct ImGuiTabBarSection { - ImGuiTabItem* Tabs; // Pointer to the first tab_bar->Tabs matching the section - int TabCount; - float Width; - float WidthIdeal; - float InnerSpacing; // Horizontal ItemInnerSpacing, used by Leading/Trailing section, to correctly offset from Central section - TabBarLayoutSection() { Tabs = NULL; TabCount = 0; Width = 0.0f; WidthIdeal = 0.0f; InnerSpacing = 0.0f; } + int TabStartIndex; + int TabCount; + float Width; + float WidthIdeal; + float InnerSpacing; // Horizontal ItemInnerSpacing, used by Leading/Trailing section, to correctly offset from Central section + ImGuiTabBarSection(){ memset(this, 0, sizeof(*this)); } }; // Storage for a tab bar (sizeof() 92~96 bytes) @@ -1757,9 +1757,7 @@ struct ImGuiTabBar ImGuiID ReorderRequestTabId; ImS8 ReorderRequestDir; ImS8 TabsActiveCount; // Number of tabs submitted this frame. - TabBarLayoutSection LeadingSection; - TabBarLayoutSection CentralSection; - TabBarLayoutSection TrailingSection; + ImGuiTabBarSection Sections[3]; bool WantLayout; bool VisibleTabWasSubmitted; short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 0c81dd0b..3628b161 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6786,7 +6786,6 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, // - EndTabBar() // - TabBarLayout() [Internal] // - TabBarLayoutComputeTabsWidth() [Internal] -// - TabBarLayoutActiveTabsForSection() [Internal] // - TabBarCalcTabID() [Internal] // - TabBarCalcMaxTabWidth() [Internal] // - TabBarFindTabById() [Internal] @@ -6803,7 +6802,6 @@ namespace ImGui { static void TabBarLayout(ImGuiTabBar* tab_bar); static void TabBarLayoutComputeTabsWidth(ImGuiTabBar* tab_bar, bool scrolling_buttons, float scrolling_buttons_width); - static float TabBarLayoutActiveTabsForSection(ImGuiTabBar* tab_bar, TabBarLayoutSection* section, float next_tab_offset); static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label); static float TabBarCalcMaxTabWidth(); static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); @@ -6828,14 +6826,14 @@ ImGuiTabBar::ImGuiTabBar() LastTabItemIdx = -1; } -static int IMGUI_CDECL TabItemComparerByPositionAndIndex(const void* lhs, const void* rhs) +static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs) { const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; - const int a_position = (a->Flags & ImGuiTabItemFlags_Leading) ? 0 : (a->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; - const int b_position = (b->Flags & ImGuiTabItemFlags_Leading) ? 0 : (b->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; - if (a_position != b_position) - return a_position - b_position; + const int a_section = (a->Flags & ImGuiTabItemFlags_Leading) ? 0 : (a->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + const int b_section = (b->Flags & ImGuiTabItemFlags_Leading) ? 0 : (b->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + if (a_section != b_section) + return a_section - b_section; return (int)(a->IndexDuringLayout - b->IndexDuringLayout); } @@ -6972,7 +6970,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Garbage collect by compacting list int tab_dst_n = 0; bool need_sort_trailing_or_leading = false; - tab_bar->LeadingSection.TabCount = tab_bar->CentralSection.TabCount = tab_bar->TrailingSection.TabCount = 0; + tab_bar->Sections[0].TabCount = tab_bar->Sections[1].TabCount = tab_bar->Sections[2].TabCount = 0; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; @@ -6987,20 +6985,19 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (tab_dst_n != tab_src_n) tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n]; - tab_bar->Tabs[tab_dst_n].IndexDuringLayout = (ImS8)tab_dst_n; - bool is_leading = (tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Leading) != 0; - bool is_trailing = (tab_bar->Tabs[tab_dst_n].Flags & ImGuiTabItemFlags_Trailing) != 0; - if (tab_dst_n > 0 && is_leading && !(tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Leading)) + tab = &tab_bar->Tabs[tab_dst_n]; + tab->IndexDuringLayout = (ImS8)tab_dst_n; + + ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1]; + int curr_tab_section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + int prev_tab_section_n = (prev_tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (prev_tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + + if (tab_dst_n > 0 && curr_tab_section_n == 0 && prev_tab_section_n != 0) need_sort_trailing_or_leading = true; - if (tab_dst_n > 0 && (tab_bar->Tabs[tab_dst_n - 1].Flags & ImGuiTabItemFlags_Trailing) && !is_trailing) + if (tab_dst_n > 0 && prev_tab_section_n == 2 && curr_tab_section_n != 2) need_sort_trailing_or_leading = true; - if (is_leading) - tab_bar->LeadingSection.TabCount++; - else if (is_trailing) - tab_bar->TrailingSection.TabCount++; - else - tab_bar->CentralSection.TabCount++; + tab_bar->Sections[curr_tab_section_n].TabCount++; tab_dst_n++; } @@ -7008,11 +7005,11 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->Tabs.resize(tab_dst_n); if (need_sort_trailing_or_leading) - ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByPositionAndIndex); + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection); - tab_bar->LeadingSection.Tabs = tab_bar->Tabs.Data; - tab_bar->CentralSection.Tabs = tab_bar->Tabs.Data + tab_bar->LeadingSection.TabCount; - tab_bar->TrailingSection.Tabs = tab_bar->Tabs.Data + tab_bar->LeadingSection.TabCount + tab_bar->CentralSection.TabCount; + tab_bar->Sections[0].TabStartIndex = 0; + tab_bar->Sections[1].TabStartIndex = tab_bar->Sections[0].TabStartIndex + tab_bar->Sections[0].TabCount; + tab_bar->Sections[2].TabStartIndex = tab_bar->Sections[1].TabStartIndex + tab_bar->Sections[1].TabCount; // Setup next selected tab ImGuiID scroll_track_selected_tab_id = 0; @@ -7042,7 +7039,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); // Compute ideal widths - tab_bar->LeadingSection.Width = tab_bar->CentralSection.Width = tab_bar->TrailingSection.Width = 0.0f; + tab_bar->Sections[0].Width = tab_bar->Sections[1].Width = tab_bar->Sections[2].Width = 0.0f; const float tab_max_width = TabBarCalcMaxTabWidth(); ImGuiTabItem* most_recently_selected_tab = NULL; @@ -7066,23 +7063,18 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true; tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x; - float width = ImMin(tab->ContentWidth, tab_max_width); - if (tab->Flags & ImGuiTabItemFlags_Leading) - tab_bar->LeadingSection.Width += width + (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); - else if (tab->Flags & ImGuiTabItemFlags_Trailing) - tab_bar->TrailingSection.Width += width + (tab_n > tab_bar->LeadingSection.TabCount + tab_bar->CentralSection.TabCount ? g.Style.ItemInnerSpacing.x : 0.0f); - else - tab_bar->CentralSection.Width += width + (tab_n > tab_bar->LeadingSection.TabCount ? g.Style.ItemInnerSpacing.x : 0.0f); + int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + ImGuiTabBarSection* section = &tab_bar->Sections[section_n]; + float width = ImMin(tab->ContentWidth, tab_max_width) + (tab_n > section->TabStartIndex) ? g.Style.ItemInnerSpacing.x : 0.0f; + section->Width = section->WidthIdeal = section->Width + width; - g.ShrinkWidthBuffer[tab_n].Index = tab_n; // Store data so we can build an array sorted by width if we need to shrink tabs down + // Store data so we can build an array sorted by width if we need to shrink tabs down + g.ShrinkWidthBuffer[tab_n].Index = tab_n; g.ShrinkWidthBuffer[tab_n].Width = tab->ContentWidth; IM_ASSERT(width > 0.0f); tab->Width = width; } - tab_bar->LeadingSection.WidthIdeal = tab_bar->LeadingSection.Width; - tab_bar->CentralSection.WidthIdeal = tab_bar->CentralSection.Width; - tab_bar->TrailingSection.WidthIdeal = tab_bar->TrailingSection.Width; // We want to know here if we'll need the scrolling buttons, to adjust available width with resizable leading/trailing bool scrolling_buttons = (tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); @@ -7090,16 +7082,25 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) TabBarLayoutComputeTabsWidth(tab_bar, scrolling_buttons, scrolling_buttons_width); // Layout all active tabs - tab_bar->WidthAllTabs = tab_bar->WidthAllTabsIdeal = 0.0f; float next_tab_offset = 0.0f; + tab_bar->WidthAllTabs = tab_bar->WidthAllTabsIdeal = 0.0f; + for (int section_n = 0; section_n < 3; section_n++) + { + // TabBarScrollingButtons will alter BarRect.Max.x, so we need to anticipate BarRect width reduction + ImGuiTabBarSection* section = &tab_bar->Sections[section_n]; + if (section_n == 2) + next_tab_offset = ImMin(tab_bar->BarRect.GetWidth() - section->Width - (scrolling_buttons ? scrolling_buttons_width + 1.0f : 0.0f), next_tab_offset); - // TabBarLayoutActiveTabsForSection will also alter tab_bar->WidthAllTabs and WidthAllTabsIdeal - next_tab_offset = TabBarLayoutActiveTabsForSection(tab_bar, &tab_bar->LeadingSection, next_tab_offset); // Leading Section - next_tab_offset = TabBarLayoutActiveTabsForSection(tab_bar, &tab_bar->CentralSection, next_tab_offset); // Central Section - - // TabBarScrollingButtons will alter BarRect.Max.x, so we need to anticipate BarRect width reduction - next_tab_offset = ImMin(tab_bar->BarRect.GetWidth() - tab_bar->TrailingSection.Width - (scrolling_buttons ? scrolling_buttons_width + 1.0f : 0.0f), next_tab_offset); - TabBarLayoutActiveTabsForSection(tab_bar, &tab_bar->TrailingSection, next_tab_offset); // Trailing Section + for (int tab_n = 0; tab_n < section->TabCount; tab_n++) + { + ImGuiTabItem* tab = &tab_bar->Tabs[section->TabStartIndex + tab_n]; + tab->Offset = next_tab_offset; + next_tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); + } + tab_bar->WidthAllTabs += ImMax(section->Width + section->InnerSpacing, 0.0f); + tab_bar->WidthAllTabsIdeal += ImMax(section->WidthIdeal + section->InnerSpacing, 0.0f); + next_tab_offset += section->InnerSpacing; + } // Horizontal scrolling buttons if (scrolling_buttons) @@ -7153,8 +7154,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) #ifdef IMGUI_ENABLE_TEST_ENGINE if (g.IO.KeyAlt) { - window->DrawList->AddRect(tab_bar->BarRect.Min, ImVec2(tab_bar->BarRect.Min.x + tab_bar->LeadingSection.Width, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255)); - window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - tab_bar->TrailingSection.Width, tab_bar->BarRect.Min.y), tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); + window->DrawList->AddRect(tab_bar->BarRect.Min, ImVec2(tab_bar->BarRect.Min.x + tab_bar->Sections[0].Width, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255)); + window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - tab_bar->Sections[2].Width, tab_bar->BarRect.Min.y), tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); } #endif } @@ -7164,26 +7165,26 @@ static void ImGui::TabBarLayoutComputeTabsWidth(ImGuiTabBar* tab_bar, bool scrol ImGuiContext& g = *GImGui; // Compute Leading/Trailing relative additional horizontal inner spacing - float leading_trailing_common_inner_space = (tab_bar->LeadingSection.TabCount > 0 && tab_bar->TrailingSection.TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); - bool resizing_leading_trailing_only = (tab_bar->LeadingSection.Width + tab_bar->TrailingSection.Width + leading_trailing_common_inner_space) > (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)); + float leading_trailing_common_inner_space = (tab_bar->Sections[0].TabCount > 0 && tab_bar->Sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); + bool resizing_leading_trailing_only = (tab_bar->Sections[0].Width + tab_bar->Sections[2].Width + leading_trailing_common_inner_space) > (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)); - tab_bar->LeadingSection.InnerSpacing = tab_bar->LeadingSection.TabCount > 0 && (tab_bar->CentralSection.TabCount + tab_bar->TrailingSection.TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - tab_bar->CentralSection.InnerSpacing = tab_bar->CentralSection.TabCount > 0 && tab_bar->TrailingSection.TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - tab_bar->TrailingSection.InnerSpacing = 0.0f; + tab_bar->Sections[0].InnerSpacing = tab_bar->Sections[0].TabCount > 0 && (tab_bar->Sections[1].TabCount + tab_bar->Sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + tab_bar->Sections[1].InnerSpacing = tab_bar->Sections[1].TabCount > 0 && tab_bar->Sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + tab_bar->Sections[2].InnerSpacing = 0.0f; // Compute width float width_excess = resizing_leading_trailing_only - ? (tab_bar->LeadingSection.Width + tab_bar->TrailingSection.Width + leading_trailing_common_inner_space) - (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)) - : ImMax(tab_bar->CentralSection.Width + tab_bar->CentralSection.InnerSpacing - (tab_bar->BarRect.GetWidth() - tab_bar->LeadingSection.Width - tab_bar->LeadingSection.InnerSpacing - tab_bar->TrailingSection.Width - tab_bar->TrailingSection.InnerSpacing), 0.0f); + ? (tab_bar->Sections[0].Width + tab_bar->Sections[2].Width + leading_trailing_common_inner_space) - (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)) + : ImMax(tab_bar->Sections[1].Width + tab_bar->Sections[1].InnerSpacing - (tab_bar->BarRect.GetWidth() - tab_bar->Sections[0].Width - tab_bar->Sections[0].InnerSpacing - tab_bar->Sections[2].Width - tab_bar->Sections[2].InnerSpacing), 0.0f); if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || resizing_leading_trailing_only) { // All tabs are in the ShrinkWidthBuffer, but we will only resize leading/trailing or central tabs, so rearrange internal data if (resizing_leading_trailing_only) - memmove(g.ShrinkWidthBuffer.Data + tab_bar->LeadingSection.TabCount, g.ShrinkWidthBuffer.Data + tab_bar->LeadingSection.TabCount + tab_bar->CentralSection.TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->TrailingSection.TabCount); + memmove(g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount + tab_bar->Sections[1].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[2].TabCount); else - memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + tab_bar->LeadingSection.TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->CentralSection.TabCount); - int tab_n_shrinkable = (resizing_leading_trailing_only ? tab_bar->LeadingSection.TabCount + tab_bar->TrailingSection.TabCount : tab_bar->CentralSection.TabCount); + memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[1].TabCount); + int tab_n_shrinkable = (resizing_leading_trailing_only ? tab_bar->Sections[0].TabCount + tab_bar->Sections[2].TabCount : tab_bar->Sections[1].TabCount); ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); @@ -7205,32 +7206,16 @@ static void ImGui::TabBarLayoutComputeTabsWidth(ImGuiTabBar* tab_bar, bool scrol if (resizing_leading_trailing_only) { - tab_bar->LeadingSection.Width -= leading_excess; - tab_bar->TrailingSection.Width -= trailing_excess; + tab_bar->Sections[0].Width -= leading_excess; + tab_bar->Sections[2].Width -= trailing_excess; } else { - tab_bar->CentralSection.Width -= width_excess; + tab_bar->Sections[1].Width -= width_excess; } } } -static float ImGui::TabBarLayoutActiveTabsForSection(ImGuiTabBar* tab_bar, TabBarLayoutSection* section, float next_tab_offset) -{ - ImGuiContext& g = *GImGui; - - for(int i = 0; i < section->TabCount; ++i) - { - ImGuiTabItem* tab = section->Tabs + i; - tab->Offset = next_tab_offset; - next_tab_offset += tab->Width + (i < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); - } - tab_bar->WidthAllTabs += ImMax(section->Width + section->InnerSpacing, 0.0f); - tab_bar->WidthAllTabsIdeal += ImMax(section->WidthIdeal + section->InnerSpacing, 0.0f); - - return next_tab_offset + section->InnerSpacing; -} - // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label) { @@ -7311,11 +7296,11 @@ static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) int order = tab_bar->GetTabOrder(tab); // Scrolling happens only in the central section (leading/trailing sections are not scrolling) - float scrollable_width = tab_bar->BarRect.GetWidth() - tab_bar->LeadingSection.Width - tab_bar->TrailingSection.Width - tab_bar->CentralSection.InnerSpacing; + float scrollable_width = tab_bar->BarRect.GetWidth() - tab_bar->Sections[0].Width - tab_bar->Sections[2].Width - tab_bar->Sections[1].InnerSpacing; - // We make all tabs positions all relative LeadingSection.Width to make code simpler - float tab_x1 = tab->Offset - tab_bar->LeadingSection.Width + (order > tab_bar->LeadingSection.TabCount - 1 ? -margin : 0.0f); - float tab_x2 = tab->Offset - tab_bar->LeadingSection.Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - tab_bar->TrailingSection.TabCount ? margin : 1.0f); + // We make all tabs positions all relative Sections[0].Width to make code simpler + float tab_x1 = tab->Offset - tab_bar->Sections[0].Width + (order > tab_bar->Sections[0].TabCount - 1 ? -margin : 0.0f); + float tab_x2 = tab->Offset - tab_bar->Sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - tab_bar->Sections[2].TabCount ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width)) { @@ -7650,9 +7635,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) // Leading buttons will be clipped by BarRect.Max.x, Trailing buttons will be clipped at BarRect.Min.x + LeadingsWidth (+ spacing if there are some buttons), and central tabs will be clipped inbetween - float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->TrailingSection.Width + tab_bar->CentralSection.InnerSpacing; - float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->LeadingSection.Width + tab_bar->LeadingSection.InnerSpacing; - bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x + offset_leading) || (bb.Max.x + offset_trailing > tab_bar->BarRect.Max.x); + float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->Sections[2].Width + tab_bar->Sections[1].InnerSpacing; + float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->Sections[0].Width + tab_bar->Sections[0].InnerSpacing; + bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x + offset_leading) || (bb.Max.x > tab_bar->BarRect.Max.x - offset_trailing); if (want_clip_rect) PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x + offset_leading), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x - offset_trailing, bb.Max.y), true); From 3422cb1308e70347f04b59e79b93e9cad7cd81b6 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Fri, 4 Sep 2020 11:13:46 +0200 Subject: [PATCH 283/959] Tab Bar: Various fixes. Tried to reduce code complexity. (#3291) --- docs/CHANGELOG.txt | 16 +++--- imgui.h | 4 +- imgui_internal.h | 4 +- imgui_widgets.cpp | 128 ++++++++++++++++++--------------------------- 4 files changed, 64 insertions(+), 88 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d1f5fb2a..4be7d31d 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -65,9 +65,9 @@ Other Changes: - InputText: Fixed minor scrolling glitch when erasing trailing lines in InputTextMultiline(). - InputText: Fixed cursor being partially covered after using Ctrl+End key. - InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454) -- InputText: Made pressing Down arrow on the last line when it doesn't have a carriage return not move to the end - of the line (so it is consistent with Up arrow, and behave same as Notepad and Visual Studio. Note that some - other text editors instead would move the crusor to the end of the line). [@Xipiryon] +- InputText: Made pressing Down arrow on the last line when it doesn't have a carriage return not move to + the end of the line (so it is consistent with Up arrow, and behave same as Notepad and Visual Studio. + Note that some other text editors instead would move the crusor to the end of the line). [@Xipiryon] - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) - SliderInt, SliderScalar: Fixed reaching of maximum value with inverted integer min/max ranges, both @@ -80,17 +80,17 @@ Other Changes: rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) +- Tab Bar: Added TabItemButton() to submit tab that behave like a button. (#3291) [@Xipiryon] +- Tab Bar: Added ImGuiTabItemFlags_Leading and ImGuiTabItemFlags_Trailing flags to position tabs or button + at either end of the tab bar. Those tabs won't be part of the scrolling region, and when reordering cannot + be moving outside of their section. Most often used with TabItemButton(). (#3291) [@Xipiryon] +- Tab Bar: Added ImGuiTabItemFlags_NoReorder flag to disable reordering a given tab. - Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). - Tab Bar: Fixed a small bug where closing a tab that is not selected would leave a tab hole for a frame. - Tab Bar: Fixed a small bug where scrolling buttons (with ImGuiTabBarFlags_FittingPolicyScroll) would generate an unnecessary extra draw call. - Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave tabs reordered in the tab list popup. [@Xipiryon] -- Tab Bar: Added TabItemButton() to submit tab that behave like a button. (#3291) [@Xipiryon] -- Tab Bar: Added ImGuiTabItemFlags_Leading and ImGuiTabItemFlags_Trailing flags to position tabs or button at - either end of the tab bar. Those tabs won't be part of the scrolling region, won't shrink down, and when - reordering cannot be moving outside of their section. Most often used with TabItemButton(). (#3291) [@Xipiryon] -- Tab Bar: Added ImGuiTabItemFlags_NoReorder flag to disable reordering a given tab. - Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of a fully clipped column. (#3475) [@szreder] - Popups, Tooltips: Fix edge cases issues with positionning popups and tooltips when they are larger than diff --git a/imgui.h b/imgui.h index 91a0b162..c7234346 100644 --- a/imgui.h +++ b/imgui.h @@ -957,8 +957,8 @@ enum ImGuiTabItemFlags_ ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab - ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) and disable resizing down - ImGuiTabItemFlags_Trailing = 1 << 7 // Enforce the tab position to the right of the tab bar (before the scrolling buttons) and disable resizing down + ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) + ImGuiTabItemFlags_Trailing = 1 << 7 // Enforce the tab position to the right of the tab bar (before the scrolling buttons) }; // Flags for ImGui::IsWindowFocused() diff --git a/imgui_internal.h b/imgui_internal.h index e61fbed7..796e03e5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1704,7 +1704,7 @@ enum ImGuiTabBarFlagsPrivate_ enum ImGuiTabItemFlagsPrivate_ { ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) - ImGuiTabItemFlags_Button = 1 << 21 // [Internal] Used by TabItemButton, change the tab item behavior to mimic a button + ImGuiTabItemFlags_Button = 1 << 21 // Used by TabItemButton, change the tab item behavior to mimic a button }; // Storage for one active tab item (sizeof() 28~32 bytes) @@ -1732,6 +1732,7 @@ struct ImGuiTabBarSection float Width; float WidthIdeal; float InnerSpacing; // Horizontal ItemInnerSpacing, used by Leading/Trailing section, to correctly offset from Central section + float WidthWithSpacing() const { return Width + InnerSpacing; } ImGuiTabBarSection(){ memset(this, 0, sizeof(*this)); } }; @@ -1761,6 +1762,7 @@ struct ImGuiTabBar bool WantLayout; bool VisibleTabWasSubmitted; short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() + bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3628b161..2ddbbb88 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6785,7 +6785,6 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, // - BeginTabBarEx() [Internal] // - EndTabBar() // - TabBarLayout() [Internal] -// - TabBarLayoutComputeTabsWidth() [Internal] // - TabBarCalcTabID() [Internal] // - TabBarCalcMaxTabWidth() [Internal] // - TabBarFindTabById() [Internal] @@ -6801,7 +6800,6 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, namespace ImGui { static void TabBarLayout(ImGuiTabBar* tab_bar); - static void TabBarLayoutComputeTabsWidth(ImGuiTabBar* tab_bar, bool scrolling_buttons, float scrolling_buttons_width); static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label); static float TabBarCalcMaxTabWidth(); static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); @@ -6824,6 +6822,7 @@ ImGuiTabBar::ImGuiTabBar() TabsActiveCount = 0; WantLayout = VisibleTabWasSubmitted = false; LastTabItemIdx = -1; + TabsAddedNew = false; } static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs) @@ -6899,9 +6898,11 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG return true; } - // When toggling ImGuiTabBarFlags_Reorderable flag, ensure tabs are ordered based on their submission order. - if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1) - ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); + // When toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable, ensure tabs are ordered based on their submission order. + if (((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) || tab_bar->TabsAddedNew) + if (tab_bar->Tabs.Size > 1) + ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); + tab_bar->TabsAddedNew = false; // Flags if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) @@ -6992,6 +6993,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) int curr_tab_section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; int prev_tab_section_n = (prev_tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (prev_tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + // We will need sorting if either current tab is leading (section_n == 0), but not the previous one, + // or if the current is not trailing (section_n == 2), but the previous one is. if (tab_dst_n > 0 && curr_tab_section_n == 0 && prev_tab_section_n != 0) need_sort_trailing_or_leading = true; if (tab_dst_n > 0 && prev_tab_section_n == 2 && curr_tab_section_n != 2) @@ -7011,6 +7014,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->Sections[1].TabStartIndex = tab_bar->Sections[0].TabStartIndex + tab_bar->Sections[0].TabCount; tab_bar->Sections[2].TabStartIndex = tab_bar->Sections[1].TabStartIndex + tab_bar->Sections[1].TabCount; + tab_bar->Sections[0].InnerSpacing = tab_bar->Sections[0].TabCount > 0 && (tab_bar->Sections[1].TabCount + tab_bar->Sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + tab_bar->Sections[1].InnerSpacing = tab_bar->Sections[1].TabCount > 0 && tab_bar->Sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + tab_bar->Sections[2].InnerSpacing = 0.0f; + // Setup next selected tab ImGuiID scroll_track_selected_tab_id = 0; if (tab_bar->NextSelectedTabId) @@ -7040,6 +7047,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Compute ideal widths tab_bar->Sections[0].Width = tab_bar->Sections[1].Width = tab_bar->Sections[2].Width = 0.0f; + tab_bar->Sections[0].WidthIdeal = tab_bar->Sections[1].WidthIdeal = tab_bar->Sections[2].WidthIdeal = 0.0f; const float tab_max_width = TabBarCalcMaxTabWidth(); ImGuiTabItem* most_recently_selected_tab = NULL; @@ -7065,8 +7073,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; ImGuiTabBarSection* section = &tab_bar->Sections[section_n]; - float width = ImMin(tab->ContentWidth, tab_max_width) + (tab_n > section->TabStartIndex) ? g.Style.ItemInnerSpacing.x : 0.0f; - section->Width = section->WidthIdeal = section->Width + width; + float width = ImMin(tab->ContentWidth, tab_max_width); + section->Width = section->WidthIdeal = section->Width + width + (tab_n > section->TabStartIndex ? g.Style.ItemInnerSpacing.x : 0.0f); // Store data so we can build an array sorted by width if we need to shrink tabs down g.ShrinkWidthBuffer[tab_n].Index = tab_n; @@ -7076,14 +7084,46 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab->Width = width; } + tab_bar->WidthAllTabsIdeal = 0.0f; + for (int section_n = 0; section_n < 3; section_n++) + tab_bar->WidthAllTabsIdeal += tab_bar->Sections[section_n].WidthIdeal + tab_bar->Sections[section_n].InnerSpacing; + // We want to know here if we'll need the scrolling buttons, to adjust available width with resizable leading/trailing bool scrolling_buttons = (tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); float scrolling_buttons_width = GetTabBarScrollingButtonSize().x * 2.0f; - TabBarLayoutComputeTabsWidth(tab_bar, scrolling_buttons, scrolling_buttons_width); + + // Compute width + bool central_section_is_visible = tab_bar->Sections[0].WidthWithSpacing() + tab_bar->Sections[2].WidthWithSpacing() < tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f); + float width_excess = central_section_is_visible + ? ImMax(tab_bar->Sections[1].WidthWithSpacing() - (tab_bar->BarRect.GetWidth() - tab_bar->Sections[0].WidthWithSpacing() - tab_bar->Sections[2].WidthWithSpacing()), 0.0f) + : (tab_bar->Sections[0].WidthWithSpacing() + tab_bar->Sections[2].WidthWithSpacing()) - (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)); + + if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown || !central_section_is_visible)) + { + // All tabs are in the ShrinkWidthBuffer, but we will only resize leading/trailing or central tabs, so rearrange internal data + if (central_section_is_visible) + memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[1].TabCount); // Move central section tabs + else + memmove(g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount + tab_bar->Sections[1].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[2].TabCount); // Replace central section tabs with trailing + int tab_n_shrinkable = (central_section_is_visible ? tab_bar->Sections[1].TabCount : tab_bar->Sections[0].TabCount + tab_bar->Sections[2].TabCount); + + ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); + + // Update each section width with shrink values + for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) + { + float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); + ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index]; + int section_n = tab->Flags & ImGuiTabItemFlags_Leading ? 0 : tab->Flags & ImGuiTabItemFlags_Trailing ? 2 : 1; + + tab_bar->Sections[section_n].Width -= (tab->Width - shrinked_width); + tab->Width = shrinked_width; + } + } // Layout all active tabs float next_tab_offset = 0.0f; - tab_bar->WidthAllTabs = tab_bar->WidthAllTabsIdeal = 0.0f; + tab_bar->WidthAllTabs = 0.0f; for (int section_n = 0; section_n < 3; section_n++) { // TabBarScrollingButtons will alter BarRect.Max.x, so we need to anticipate BarRect width reduction @@ -7097,8 +7137,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab->Offset = next_tab_offset; next_tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); } - tab_bar->WidthAllTabs += ImMax(section->Width + section->InnerSpacing, 0.0f); - tab_bar->WidthAllTabsIdeal += ImMax(section->WidthIdeal + section->InnerSpacing, 0.0f); + tab_bar->WidthAllTabs += ImMax(section->WidthWithSpacing(), 0.0f); next_tab_offset += section->InnerSpacing; } @@ -7150,70 +7189,6 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos = tab_bar->BarRect.Min; ItemSize(ImVec2(tab_bar->WidthAllTabsIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); - -#ifdef IMGUI_ENABLE_TEST_ENGINE - if (g.IO.KeyAlt) - { - window->DrawList->AddRect(tab_bar->BarRect.Min, ImVec2(tab_bar->BarRect.Min.x + tab_bar->Sections[0].Width, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255)); - window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - tab_bar->Sections[2].Width, tab_bar->BarRect.Min.y), tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); - } -#endif -} - -static void ImGui::TabBarLayoutComputeTabsWidth(ImGuiTabBar* tab_bar, bool scrolling_buttons, float scrolling_buttons_width) -{ - ImGuiContext& g = *GImGui; - - // Compute Leading/Trailing relative additional horizontal inner spacing - float leading_trailing_common_inner_space = (tab_bar->Sections[0].TabCount > 0 && tab_bar->Sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f); - bool resizing_leading_trailing_only = (tab_bar->Sections[0].Width + tab_bar->Sections[2].Width + leading_trailing_common_inner_space) > (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)); - - tab_bar->Sections[0].InnerSpacing = tab_bar->Sections[0].TabCount > 0 && (tab_bar->Sections[1].TabCount + tab_bar->Sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - tab_bar->Sections[1].InnerSpacing = tab_bar->Sections[1].TabCount > 0 && tab_bar->Sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - tab_bar->Sections[2].InnerSpacing = 0.0f; - - // Compute width - float width_excess = resizing_leading_trailing_only - ? (tab_bar->Sections[0].Width + tab_bar->Sections[2].Width + leading_trailing_common_inner_space) - (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)) - : ImMax(tab_bar->Sections[1].Width + tab_bar->Sections[1].InnerSpacing - (tab_bar->BarRect.GetWidth() - tab_bar->Sections[0].Width - tab_bar->Sections[0].InnerSpacing - tab_bar->Sections[2].Width - tab_bar->Sections[2].InnerSpacing), 0.0f); - - if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || resizing_leading_trailing_only) - { - // All tabs are in the ShrinkWidthBuffer, but we will only resize leading/trailing or central tabs, so rearrange internal data - if (resizing_leading_trailing_only) - memmove(g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount + tab_bar->Sections[1].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[2].TabCount); - else - memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[1].TabCount); - int tab_n_shrinkable = (resizing_leading_trailing_only ? tab_bar->Sections[0].TabCount + tab_bar->Sections[2].TabCount : tab_bar->Sections[1].TabCount); - - ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); - - // Total Leading and Trailing shrink values can be different, we need to keep track of how much each section was shrinked - float leading_excess = 0.0f; - float trailing_excess = 0.0f; - for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) - { - float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); - ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index]; - - if (tab->Flags & ImGuiTabItemFlags_Leading) - leading_excess += (tab->Width - shrinked_width); - else if (tab->Flags & ImGuiTabItemFlags_Trailing) - trailing_excess += (tab->Width - shrinked_width); - - tab->Width = shrinked_width; - } - - if (resizing_leading_trailing_only) - { - tab_bar->Sections[0].Width -= leading_excess; - tab_bar->Sections[2].Width -= trailing_excess; - } - else - { - tab_bar->Sections[1].Width -= width_excess; - } - } } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. @@ -7407,7 +7382,6 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) } } window->DC.CursorPos = backup_cursor_pos; - tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f; return tab_to_scroll_to; @@ -7569,7 +7543,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab = &tab_bar->Tabs.back(); tab->ID = id; tab->Width = size.x; - tab_is_new = true; + tab_bar->TabsAddedNew = tab_is_new = true; } tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab); tab->ContentWidth = size.x; From 205874f5b15a3689d253c6c149c62ad704dae0ab Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 21 Sep 2020 18:40:18 +0200 Subject: [PATCH 284/959] Tab Bar: Fix reorderable tab bars. Fix misleading use of tab_max_width in TabBarLayout(). Misc amends, shortening. (#3291) --- imgui.h | 2 +- imgui_demo.cpp | 31 +++++++------ imgui_internal.h | 18 ++++---- imgui_widgets.cpp | 113 +++++++++++++++++++++++----------------------- 4 files changed, 84 insertions(+), 80 deletions(-) diff --git a/imgui.h b/imgui.h index c7234346..4fc23e83 100644 --- a/imgui.h +++ b/imgui.h @@ -655,7 +655,7 @@ namespace ImGui IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected. IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! - IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button + IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. // Logging/Capture diff --git a/imgui_demo.cpp b/imgui_demo.cpp index e1d31063..c728bbe1 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -2363,6 +2363,15 @@ static void ShowDemoWindowLayout() for (int i = 0; i < 3; i++) active_tabs.push_back(next_tab_id++); + // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. + // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... + // but they tend to make more sense together) + static bool show_leading_button = true; + static bool show_trailing_button = true; + ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); + ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); + + // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) @@ -2370,18 +2379,12 @@ static void ShowDemoWindowLayout() if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); - static bool show_leading_button = true; - static bool show_trailing_button = true; - ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button); - ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button); - if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { - // Demo Leading Tabs: click the "?" button to open a menu - // Note that it is possible to submit regular non-button tabs with Leading/Trailing flags, - // or Button without Leading/Trailing flags... but they tend to make more sense together. - if (show_leading_button && ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) - ImGui::OpenPopup("MyHelpMenu"); + // Demo a Leading TabItemButton(): click the "?" button to open a menu + if (show_leading_button) + if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip)) + ImGui::OpenPopup("MyHelpMenu"); if (ImGui::BeginPopup("MyHelpMenu")) { ImGui::Selectable("Hello!"); @@ -2389,8 +2392,10 @@ static void ShowDemoWindowLayout() } // Demo Trailing Tabs: click the "+" button to add a new tab (in your app you may want to use a font icon instead of the "+") - if (show_trailing_button && ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) - active_tabs.push_back(next_tab_id++); + // Note that we submit it before the regular tabs, but because of the ImGuiTabItemFlags_Trailing flag it will always appear at the end. + if (show_trailing_button) + if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip)) + active_tabs.push_back(next_tab_id++); // Add new tab // Submit our regular tabs for (int n = 0; n < active_tabs.Size; ) @@ -2411,7 +2416,7 @@ static void ShowDemoWindowLayout() } ImGui::EndTabBar(); - } + } ImGui::Separator(); ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index 796e03e5..b48e2cc4 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1716,7 +1716,7 @@ struct ImGuiTabItem int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance float Offset; // Position relative to beginning of tab float Width; // Width currently displayed - float ContentWidth; // Width of actual contents, stored during BeginTabItem() call + float ContentWidth; // Width of label, stored during BeginTabItem() call ImS16 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames ImS8 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable ImS8 IndexDuringLayout; // Index only used during TabBarLayout() @@ -1727,13 +1727,13 @@ struct ImGuiTabItem struct ImGuiTabBarSection { - int TabStartIndex; - int TabCount; - float Width; - float WidthIdeal; - float InnerSpacing; // Horizontal ItemInnerSpacing, used by Leading/Trailing section, to correctly offset from Central section - float WidthWithSpacing() const { return Width + InnerSpacing; } + int TabStartIndex; // Index of first tab in this section. + int TabCount; // Number of tabs in this section. + float Width; // Width of this section (after shrinking down) + float Spacing; // Horizontal spacing at the end of the section. + ImGuiTabBarSection(){ memset(this, 0, sizeof(*this)); } + float WidthWithSpacing() const { return Width + Spacing; } }; // Storage for a tab bar (sizeof() 92~96 bytes) @@ -1758,12 +1758,12 @@ struct ImGuiTabBar ImGuiID ReorderRequestTabId; ImS8 ReorderRequestDir; ImS8 TabsActiveCount; // Number of tabs submitted this frame. - ImGuiTabBarSection Sections[3]; bool WantLayout; bool VisibleTabWasSubmitted; - short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame + short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() + ImGuiTabBarSection Sections[3]; // Layout sections: Leading, Central, Trailing ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ddbbb88..e224859a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6820,9 +6820,8 @@ ImGuiTabBar::ImGuiTabBar() ReorderRequestTabId = 0; ReorderRequestDir = 0; TabsActiveCount = 0; - WantLayout = VisibleTabWasSubmitted = false; + WantLayout = VisibleTabWasSubmitted = TabsAddedNew = false; LastTabItemIdx = -1; - TabsAddedNew = false; } static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs) @@ -6898,8 +6897,8 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG return true; } - // When toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable, ensure tabs are ordered based on their submission order. - if (((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) || tab_bar->TabsAddedNew) + // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable + if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable))) if (tab_bar->Tabs.Size > 1) ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); tab_bar->TabsAddedNew = false; @@ -6966,12 +6965,14 @@ void ImGui::EndTabBar() static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; + ImGuiTabBarSection* sections = tab_bar->Sections; tab_bar->WantLayout = false; // Garbage collect by compacting list + // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section) int tab_dst_n = 0; - bool need_sort_trailing_or_leading = false; - tab_bar->Sections[0].TabCount = tab_bar->Sections[1].TabCount = tab_bar->Sections[2].TabCount = 0; + bool need_sort_by_section = false; + sections[0].TabCount = sections[1].TabCount = sections[2].TabCount = 0; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; @@ -6989,34 +6990,34 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab = &tab_bar->Tabs[tab_dst_n]; tab->IndexDuringLayout = (ImS8)tab_dst_n; + // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1]; int curr_tab_section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; int prev_tab_section_n = (prev_tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (prev_tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; - - // We will need sorting if either current tab is leading (section_n == 0), but not the previous one, - // or if the current is not trailing (section_n == 2), but the previous one is. if (tab_dst_n > 0 && curr_tab_section_n == 0 && prev_tab_section_n != 0) - need_sort_trailing_or_leading = true; + need_sort_by_section = true; if (tab_dst_n > 0 && prev_tab_section_n == 2 && curr_tab_section_n != 2) - need_sort_trailing_or_leading = true; - - tab_bar->Sections[curr_tab_section_n].TabCount++; + need_sort_by_section = true; + sections[curr_tab_section_n].TabCount++; tab_dst_n++; } if (tab_bar->Tabs.Size != tab_dst_n) tab_bar->Tabs.resize(tab_dst_n); - if (need_sort_trailing_or_leading) + if (need_sort_by_section) ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection); - tab_bar->Sections[0].TabStartIndex = 0; - tab_bar->Sections[1].TabStartIndex = tab_bar->Sections[0].TabStartIndex + tab_bar->Sections[0].TabCount; - tab_bar->Sections[2].TabStartIndex = tab_bar->Sections[1].TabStartIndex + tab_bar->Sections[1].TabCount; - - tab_bar->Sections[0].InnerSpacing = tab_bar->Sections[0].TabCount > 0 && (tab_bar->Sections[1].TabCount + tab_bar->Sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - tab_bar->Sections[1].InnerSpacing = tab_bar->Sections[1].TabCount > 0 && tab_bar->Sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - tab_bar->Sections[2].InnerSpacing = 0.0f; + // Calculate spacing between sections + sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; + sections[2].Spacing = 0.0f; + sections[0].TabStartIndex = 0; + sections[1].TabStartIndex = sections[0].TabStartIndex + sections[0].TabCount; + sections[2].TabStartIndex = sections[1].TabStartIndex + sections[1].TabCount; + sections[0].Width = 0.0f; + sections[1].Width = 0.0f; + sections[2].Width = 0.0f; // Setup next selected tab ImGuiID scroll_track_selected_tab_id = 0; @@ -7042,16 +7043,10 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; - // Reserve shrink buffer for maximum possible number of tabs - g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); - // Compute ideal widths - tab_bar->Sections[0].Width = tab_bar->Sections[1].Width = tab_bar->Sections[2].Width = 0.0f; - tab_bar->Sections[0].WidthIdeal = tab_bar->Sections[1].WidthIdeal = tab_bar->Sections[2].WidthIdeal = 0.0f; - const float tab_max_width = TabBarCalcMaxTabWidth(); - ImGuiTabItem* most_recently_selected_tab = NULL; bool found_selected_tab_id = false; + g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; @@ -7072,51 +7067,52 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x; int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; - ImGuiTabBarSection* section = &tab_bar->Sections[section_n]; - float width = ImMin(tab->ContentWidth, tab_max_width); - section->Width = section->WidthIdeal = section->Width + width + (tab_n > section->TabStartIndex ? g.Style.ItemInnerSpacing.x : 0.0f); + ImGuiTabBarSection* section = §ions[section_n]; + section->Width += tab->ContentWidth + (tab_n > section->TabStartIndex ? g.Style.ItemInnerSpacing.x : 0.0f); // Store data so we can build an array sorted by width if we need to shrink tabs down g.ShrinkWidthBuffer[tab_n].Index = tab_n; g.ShrinkWidthBuffer[tab_n].Width = tab->ContentWidth; - IM_ASSERT(width > 0.0f); - tab->Width = width; + IM_ASSERT(tab->ContentWidth > 0.0f); + tab->Width = tab->ContentWidth; } tab_bar->WidthAllTabsIdeal = 0.0f; for (int section_n = 0; section_n < 3; section_n++) - tab_bar->WidthAllTabsIdeal += tab_bar->Sections[section_n].WidthIdeal + tab_bar->Sections[section_n].InnerSpacing; + tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing; // We want to know here if we'll need the scrolling buttons, to adjust available width with resizable leading/trailing bool scrolling_buttons = (tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); - float scrolling_buttons_width = GetTabBarScrollingButtonSize().x * 2.0f; + float scrolling_buttons_width = scrolling_buttons ? GetTabBarScrollingButtonSize().x * 2.0f : 0.0f; // Compute width - bool central_section_is_visible = tab_bar->Sections[0].WidthWithSpacing() + tab_bar->Sections[2].WidthWithSpacing() < tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f); + // FIXME: This is a mess, couldn't TabBarScrollingButtons() just be called earlier? + bool central_section_is_visible = (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) < (tab_bar->BarRect.GetWidth() - scrolling_buttons_width); float width_excess = central_section_is_visible - ? ImMax(tab_bar->Sections[1].WidthWithSpacing() - (tab_bar->BarRect.GetWidth() - tab_bar->Sections[0].WidthWithSpacing() - tab_bar->Sections[2].WidthWithSpacing()), 0.0f) - : (tab_bar->Sections[0].WidthWithSpacing() + tab_bar->Sections[2].WidthWithSpacing()) - (tab_bar->BarRect.GetWidth() - (scrolling_buttons ? scrolling_buttons_width : 0.0f)); + ? ImMax(sections[1].WidthWithSpacing() - (tab_bar->BarRect.GetWidth() - sections[0].WidthWithSpacing() - sections[2].WidthWithSpacing()), 0.0f) + : (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) - (tab_bar->BarRect.GetWidth() - scrolling_buttons_width); if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown || !central_section_is_visible)) { // All tabs are in the ShrinkWidthBuffer, but we will only resize leading/trailing or central tabs, so rearrange internal data + // FIXME: Why copying data, shouldn't we be able to call ShrinkWidths with the right offset and then use that in the loop below? if (central_section_is_visible) - memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[1].TabCount); // Move central section tabs + memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + sections[0].TabCount, sizeof(ImGuiShrinkWidthItem) * sections[1].TabCount); // Move central section tabs else - memmove(g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount, g.ShrinkWidthBuffer.Data + tab_bar->Sections[0].TabCount + tab_bar->Sections[1].TabCount, sizeof(ImGuiShrinkWidthItem) * tab_bar->Sections[2].TabCount); // Replace central section tabs with trailing - int tab_n_shrinkable = (central_section_is_visible ? tab_bar->Sections[1].TabCount : tab_bar->Sections[0].TabCount + tab_bar->Sections[2].TabCount); + memmove(g.ShrinkWidthBuffer.Data + sections[0].TabCount, g.ShrinkWidthBuffer.Data + sections[0].TabCount + sections[1].TabCount, sizeof(ImGuiShrinkWidthItem) * sections[2].TabCount); // Replace central section tabs with trailing + int tab_n_shrinkable = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount); ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); - // Update each section width with shrink values + // Update each section width with shrunk values for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) { float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index]; - int section_n = tab->Flags & ImGuiTabItemFlags_Leading ? 0 : tab->Flags & ImGuiTabItemFlags_Trailing ? 2 : 1; + int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; - tab_bar->Sections[section_n].Width -= (tab->Width - shrinked_width); + sections[section_n].Width -= (tab->Width - shrinked_width); tab->Width = shrinked_width; } } @@ -7126,8 +7122,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->WidthAllTabs = 0.0f; for (int section_n = 0; section_n < 3; section_n++) { - // TabBarScrollingButtons will alter BarRect.Max.x, so we need to anticipate BarRect width reduction - ImGuiTabBarSection* section = &tab_bar->Sections[section_n]; + // TabBarScrollingButtons() will alter BarRect.Max.x, so we need to anticipate BarRect width reduction + // FIXME: The +1.0f is in TabBarScrollingButtons() + ImGuiTabBarSection* section = §ions[section_n]; if (section_n == 2) next_tab_offset = ImMin(tab_bar->BarRect.GetWidth() - section->Width - (scrolling_buttons ? scrolling_buttons_width + 1.0f : 0.0f), next_tab_offset); @@ -7138,17 +7135,16 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) next_tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); } tab_bar->WidthAllTabs += ImMax(section->WidthWithSpacing(), 0.0f); - next_tab_offset += section->InnerSpacing; + next_tab_offset += section->Spacing; } // Horizontal scrolling buttons if (scrolling_buttons) if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x { - if (scroll_track_selected_tab->Flags & ImGuiTabItemFlags_Button) - scroll_track_selected_tab_id = scroll_track_selected_tab->ID; - else - scroll_track_selected_tab_id = tab_bar->SelectedTabId = scroll_track_selected_tab->ID; + scroll_track_selected_tab_id = scroll_track_selected_tab->ID; + if (!(scroll_track_selected_tab->Flags & ImGuiTabItemFlags_Button)) + tab_bar->SelectedTabId = scroll_track_selected_tab_id; } // If we have lost the selected tab, select the next most recently active one @@ -7267,15 +7263,17 @@ static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) return; ImGuiContext& g = *GImGui; + ImGuiTabBarSection* sections = tab_bar->Sections; float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) int order = tab_bar->GetTabOrder(tab); // Scrolling happens only in the central section (leading/trailing sections are not scrolling) - float scrollable_width = tab_bar->BarRect.GetWidth() - tab_bar->Sections[0].Width - tab_bar->Sections[2].Width - tab_bar->Sections[1].InnerSpacing; + // FIXME: This is all confusing. + float scrollable_width = tab_bar->BarRect.GetWidth() - sections[0].Width - sections[2].Width - sections[1].Spacing; // We make all tabs positions all relative Sections[0].Width to make code simpler - float tab_x1 = tab->Offset - tab_bar->Sections[0].Width + (order > tab_bar->Sections[0].TabCount - 1 ? -margin : 0.0f); - float tab_x2 = tab->Offset - tab_bar->Sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - tab_bar->Sections[2].TabCount ? margin : 1.0f); + float tab_x1 = tab->Offset - sections[0].Width + (order > sections[0].TabCount - 1 ? -margin : 0.0f); + float tab_x2 = tab->Offset - sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - sections[2].TabCount ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width)) { @@ -7543,7 +7541,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab = &tab_bar->Tabs.back(); tab->ID = id; tab->Width = size.x; - tab_bar->TabsAddedNew = tab_is_new = true; + tab_bar->TabsAddedNew = true; + tab_is_new = true; } tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab); tab->ContentWidth = size.x; @@ -7609,8 +7608,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) // Leading buttons will be clipped by BarRect.Max.x, Trailing buttons will be clipped at BarRect.Min.x + LeadingsWidth (+ spacing if there are some buttons), and central tabs will be clipped inbetween - float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->Sections[2].Width + tab_bar->Sections[1].InnerSpacing; - float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->Sections[0].Width + tab_bar->Sections[0].InnerSpacing; + float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->Sections[2].Width + tab_bar->Sections[1].Spacing; + float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->Sections[0].Width + tab_bar->Sections[0].Spacing; bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x + offset_leading) || (bb.Max.x > tab_bar->BarRect.Max.x - offset_trailing); if (want_clip_rect) PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x + offset_leading), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x - offset_trailing, bb.Max.y), true); From 99f69eb1859bfdf84e4dd4338ab63362a48a51d9 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Tue, 22 Sep 2020 10:58:10 +0200 Subject: [PATCH 285/959] Tab Bar: Moved up TabBarScrollingButtons function call. (#3291) --- imgui_widgets.cpp | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index e224859a..d60223a2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7082,16 +7082,22 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) for (int section_n = 0; section_n < 3; section_n++) tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing; - // We want to know here if we'll need the scrolling buttons, to adjust available width with resizable leading/trailing - bool scrolling_buttons = (tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); - float scrolling_buttons_width = scrolling_buttons ? GetTabBarScrollingButtonSize().x * 2.0f : 0.0f; + // Horizontal scrolling buttons + // (Note that TabBarScrollButtons() will alter BarRect.Max.x) + if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) + if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) + { + scroll_track_selected_tab_id = scroll_track_selected_tab->ID; + if (!(scroll_track_selected_tab->Flags & ImGuiTabItemFlags_Button)) + tab_bar->SelectedTabId = scroll_track_selected_tab_id; + } // Compute width - // FIXME: This is a mess, couldn't TabBarScrollingButtons() just be called earlier? - bool central_section_is_visible = (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) < (tab_bar->BarRect.GetWidth() - scrolling_buttons_width); + // FIXME: This is a mess + bool central_section_is_visible = (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) < tab_bar->BarRect.GetWidth(); float width_excess = central_section_is_visible ? ImMax(sections[1].WidthWithSpacing() - (tab_bar->BarRect.GetWidth() - sections[0].WidthWithSpacing() - sections[2].WidthWithSpacing()), 0.0f) - : (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) - (tab_bar->BarRect.GetWidth() - scrolling_buttons_width); + : (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) - tab_bar->BarRect.GetWidth(); if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown || !central_section_is_visible)) { @@ -7126,7 +7132,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // FIXME: The +1.0f is in TabBarScrollingButtons() ImGuiTabBarSection* section = §ions[section_n]; if (section_n == 2) - next_tab_offset = ImMin(tab_bar->BarRect.GetWidth() - section->Width - (scrolling_buttons ? scrolling_buttons_width + 1.0f : 0.0f), next_tab_offset); + next_tab_offset = ImMin(tab_bar->BarRect.GetWidth() - section->Width, next_tab_offset); for (int tab_n = 0; tab_n < section->TabCount; tab_n++) { @@ -7138,15 +7144,6 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) next_tab_offset += section->Spacing; } - // Horizontal scrolling buttons - if (scrolling_buttons) - if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x - { - scroll_track_selected_tab_id = scroll_track_selected_tab->ID; - if (!(scroll_track_selected_tab->Flags & ImGuiTabItemFlags_Button)) - tab_bar->SelectedTabId = scroll_track_selected_tab_id; - } - // If we have lost the selected tab, select the next most recently active one if (found_selected_tab_id == false) tab_bar->SelectedTabId = 0; From 6b76781c66403457e870e8de3943063acb2546ee Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Sep 2020 11:18:22 +0200 Subject: [PATCH 286/959] Tab Bar: Tidying up. Rework ShrinkWidths to allow marking tabs as not shrinkable (unused yet) + don't unnecessarily move data within ShrinkWidthBuffer. (#3291) --- imgui_internal.h | 3 +-- imgui_widgets.cpp | 68 +++++++++++++++++++++++++++-------------------- 2 files changed, 40 insertions(+), 31 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b48e2cc4..7aa47618 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1729,11 +1729,10 @@ struct ImGuiTabBarSection { int TabStartIndex; // Index of first tab in this section. int TabCount; // Number of tabs in this section. - float Width; // Width of this section (after shrinking down) + float Width; // Sum of width of tabs in this section (after shrinking down) float Spacing; // Horizontal spacing at the end of the section. ImGuiTabBarSection(){ memset(this, 0, sizeof(*this)); } - float WidthWithSpacing() const { return Width + Spacing; } }; // Storage for a tab bar (sizeof() 92~96 bytes) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d60223a2..c551c314 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1426,11 +1426,13 @@ static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) } // Shrink excess width from a set of item, by removing width from the larger items first. +// Set items Width to -1.0f to disable shrinking this item. void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess) { if (count == 1) { - items[0].Width = ImMax(items[0].Width - width_excess, 1.0f); + if (items[0].Width >= 0.0f) + items[0].Width = ImMax(items[0].Width - width_excess, 1.0f); return; } ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); @@ -1439,7 +1441,9 @@ void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_exc { while (count_same_width < count && items[0].Width <= items[count_same_width].Width) count_same_width++; - float max_width_to_remove_per_item = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + float max_width_to_remove_per_item = (count_same_width < count && items[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + if (max_width_to_remove_per_item <= 0.0f) + break; float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); for (int item_n = 0; item_n < count_same_width; item_n++) items[item_n].Width -= width_to_remove_per_item; @@ -7043,10 +7047,14 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; - // Compute ideal widths + // Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central + // (whereas our tabs are stored as: leading, central, trailing) + int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount }; + g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); + + // Compute ideal tabs widths + store them into shrink buffer ImGuiTabItem* most_recently_selected_tab = NULL; bool found_selected_tab_id = false; - g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; @@ -7071,19 +7079,21 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) section->Width += tab->ContentWidth + (tab_n > section->TabStartIndex ? g.Style.ItemInnerSpacing.x : 0.0f); // Store data so we can build an array sorted by width if we need to shrink tabs down - g.ShrinkWidthBuffer[tab_n].Index = tab_n; - g.ShrinkWidthBuffer[tab_n].Width = tab->ContentWidth; + int shrink_buffer_index = shrink_buffer_indexes[section_n]++; + g.ShrinkWidthBuffer[shrink_buffer_index].Index = tab_n; + g.ShrinkWidthBuffer[shrink_buffer_index].Width = tab->ContentWidth; IM_ASSERT(tab->ContentWidth > 0.0f); tab->Width = tab->ContentWidth; } + // Compute total ideal width (used for e.g. auto-resizing a window) tab_bar->WidthAllTabsIdeal = 0.0f; for (int section_n = 0; section_n < 3; section_n++) tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing; // Horizontal scrolling buttons - // (Note that TabBarScrollButtons() will alter BarRect.Max.x) + // (note that TabBarScrollButtons() will alter BarRect.Max.x) if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll)) if (ImGuiTabItem* scroll_track_selected_tab = TabBarScrollingButtons(tab_bar)) { @@ -7092,32 +7102,33 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->SelectedTabId = scroll_track_selected_tab_id; } - // Compute width - // FIXME: This is a mess - bool central_section_is_visible = (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) < tab_bar->BarRect.GetWidth(); - float width_excess = central_section_is_visible - ? ImMax(sections[1].WidthWithSpacing() - (tab_bar->BarRect.GetWidth() - sections[0].WidthWithSpacing() - sections[2].WidthWithSpacing()), 0.0f) - : (sections[0].WidthWithSpacing() + sections[2].WidthWithSpacing()) - tab_bar->BarRect.GetWidth(); + // Shrink widths if full tabs don't fit in their allocated space + float section_0_w = sections[0].Width + sections[0].Spacing; + float section_1_w = sections[1].Width + sections[1].Spacing; + float section_2_w = sections[2].Width + sections[2].Spacing; + bool central_section_is_visible = (section_0_w + section_2_w) < tab_bar->BarRect.GetWidth(); + float width_excess; + if (central_section_is_visible) + width_excess = ImMax(section_1_w - (tab_bar->BarRect.GetWidth() - section_0_w - section_2_w), 0.0f); // Excess used to shrink central section + else + width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section - if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown || !central_section_is_visible)) + // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore + if (width_excess > 0.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || !central_section_is_visible)) { - // All tabs are in the ShrinkWidthBuffer, but we will only resize leading/trailing or central tabs, so rearrange internal data - // FIXME: Why copying data, shouldn't we be able to call ShrinkWidths with the right offset and then use that in the loop below? - if (central_section_is_visible) - memmove(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Data + sections[0].TabCount, sizeof(ImGuiShrinkWidthItem) * sections[1].TabCount); // Move central section tabs - else - memmove(g.ShrinkWidthBuffer.Data + sections[0].TabCount, g.ShrinkWidthBuffer.Data + sections[0].TabCount + sections[1].TabCount, sizeof(ImGuiShrinkWidthItem) * sections[2].TabCount); // Replace central section tabs with trailing - int tab_n_shrinkable = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount); + int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount); + int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0); + ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess); - ShrinkWidths(g.ShrinkWidthBuffer.Data, tab_n_shrinkable, width_excess); - - // Update each section width with shrunk values - for (int tab_n = 0; tab_n < tab_n_shrinkable; tab_n++) + // Apply shrunk values into tabs and sections + for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++) { - float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index]; - int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width); + if (shrinked_width < 0.0f) + continue; + int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; sections[section_n].Width -= (tab->Width - shrinked_width); tab->Width = shrinked_width; } @@ -7128,7 +7139,6 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->WidthAllTabs = 0.0f; for (int section_n = 0; section_n < 3; section_n++) { - // TabBarScrollingButtons() will alter BarRect.Max.x, so we need to anticipate BarRect width reduction // FIXME: The +1.0f is in TabBarScrollingButtons() ImGuiTabBarSection* section = §ions[section_n]; if (section_n == 2) @@ -7140,7 +7150,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab->Offset = next_tab_offset; next_tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); } - tab_bar->WidthAllTabs += ImMax(section->WidthWithSpacing(), 0.0f); + tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f); next_tab_offset += section->Spacing; } From 1ec464eb9aa077b7eae81e50fce8844a85625cc7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 22 Sep 2020 16:14:04 +0200 Subject: [PATCH 287/959] Tab Bar: Further simplification of section/clip rect handling. (#3291) --- imgui.cpp | 6 ++-- imgui_internal.h | 13 ++------- imgui_widgets.cpp | 70 +++++++++++++++++++++++------------------------ 3 files changed, 38 insertions(+), 51 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1d65396a..f66cd751 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10563,10 +10563,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) { ImDrawList* draw_list = ImGui::GetForegroundDrawList(); draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); - if (tab_bar->Sections[0].Width > 0.0f) - draw_list->AddLine(ImVec2(tab_bar->BarRect.Min.x + tab_bar->Sections[0].Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Min.x + tab_bar->Sections[0].Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); - if (tab_bar->Sections[2].Width > 0.0f) - draw_list->AddLine(ImVec2(tab_bar->BarRect.Max.x - tab_bar->Sections[2].Width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x - tab_bar->Sections[2].Width, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); } if (open) { diff --git a/imgui_internal.h b/imgui_internal.h index 7aa47618..856b2a63 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1725,16 +1725,6 @@ struct ImGuiTabItem ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; IndexDuringLayout = -1; WantClose = false; } }; -struct ImGuiTabBarSection -{ - int TabStartIndex; // Index of first tab in this section. - int TabCount; // Number of tabs in this section. - float Width; // Sum of width of tabs in this section (after shrinking down) - float Spacing; // Horizontal spacing at the end of the section. - - ImGuiTabBarSection(){ memset(this, 0, sizeof(*this)); } -}; - // Storage for a tab bar (sizeof() 92~96 bytes) struct ImGuiTabBar { @@ -1753,6 +1743,8 @@ struct ImGuiTabBar float ScrollingTarget; float ScrollingTargetDistToVisibility; float ScrollingSpeed; + float ScrollingRectMinX; + float ScrollingRectMaxX; ImGuiTabBarFlags Flags; ImGuiID ReorderRequestTabId; ImS8 ReorderRequestDir; @@ -1762,7 +1754,6 @@ struct ImGuiTabBar bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() - ImGuiTabBarSection Sections[3]; // Layout sections: Leading, Central, Trailing ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c551c314..2fef410d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6801,13 +6801,22 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, // - TabBarTabListPopupButton() [Internal] //------------------------------------------------------------------------- +struct ImGuiTabBarSection +{ + int TabCount; // Number of tabs in this section. + float Width; // Sum of width of tabs in this section (after shrinking down) + float Spacing; // Horizontal spacing at the end of the section. + + ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); } +}; + namespace ImGui { static void TabBarLayout(ImGuiTabBar* tab_bar); static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label); static float TabBarCalcMaxTabWidth(); static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); - static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); + static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImGuiTabBarSection* sections); static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar); static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar); } @@ -6820,6 +6829,7 @@ ImGuiTabBar::ImGuiTabBar() LastTabContentHeight = 0.0f; WidthAllTabs = WidthAllTabsIdeal = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; + ScrollingRectMinX = ScrollingRectMaxX = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; ReorderRequestDir = 0; @@ -6860,12 +6870,6 @@ static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) return ImGuiPtrOrIndex(tab_bar); } -static ImVec2 GetTabBarScrollingButtonSize() -{ - ImGuiContext& g = *GImGui; - return ImVec2(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f); -} - bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) { ImGuiContext& g = *GImGui; @@ -6969,14 +6973,13 @@ void ImGui::EndTabBar() static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; - ImGuiTabBarSection* sections = tab_bar->Sections; tab_bar->WantLayout = false; // Garbage collect by compacting list // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section) int tab_dst_n = 0; bool need_sort_by_section = false; - sections[0].TabCount = sections[1].TabCount = sections[2].TabCount = 0; + ImGuiTabBarSection sections[3]; // Layout sections: Leading, Central, Trailing for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; @@ -7015,13 +7018,6 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Calculate spacing between sections sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f; - sections[2].Spacing = 0.0f; - sections[0].TabStartIndex = 0; - sections[1].TabStartIndex = sections[0].TabStartIndex + sections[0].TabCount; - sections[2].TabStartIndex = sections[1].TabStartIndex + sections[1].TabCount; - sections[0].Width = 0.0f; - sections[1].Width = 0.0f; - sections[2].Width = 0.0f; // Setup next selected tab ImGuiID scroll_track_selected_tab_id = 0; @@ -7054,6 +7050,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Compute ideal tabs widths + store them into shrink buffer ImGuiTabItem* most_recently_selected_tab = NULL; + int curr_section_n = -1; bool found_selected_tab_id = false; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { @@ -7076,7 +7073,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; ImGuiTabBarSection* section = §ions[section_n]; - section->Width += tab->ContentWidth + (tab_n > section->TabStartIndex ? g.Style.ItemInnerSpacing.x : 0.0f); + section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f); + curr_section_n = section_n; // Store data so we can build an array sorted by width if we need to shrink tabs down int shrink_buffer_index = shrink_buffer_indexes[section_n]++; @@ -7135,23 +7133,24 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) } // Layout all active tabs - float next_tab_offset = 0.0f; + int section_tab_index = 0; + float tab_offset = 0.0f; tab_bar->WidthAllTabs = 0.0f; for (int section_n = 0; section_n < 3; section_n++) { - // FIXME: The +1.0f is in TabBarScrollingButtons() ImGuiTabBarSection* section = §ions[section_n]; if (section_n == 2) - next_tab_offset = ImMin(tab_bar->BarRect.GetWidth() - section->Width, next_tab_offset); + tab_offset = ImMin(ImMax(0.0f, tab_bar->BarRect.GetWidth() - section->Width), tab_offset); for (int tab_n = 0; tab_n < section->TabCount; tab_n++) { - ImGuiTabItem* tab = &tab_bar->Tabs[section->TabStartIndex + tab_n]; - tab->Offset = next_tab_offset; - next_tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); + ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n]; + tab->Offset = tab_offset; + tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); } tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f); - next_tab_offset += section->Spacing; + tab_offset += section->Spacing; + section_tab_index += section->TabCount; } // If we have lost the selected tab, select the next most recently active one @@ -7167,7 +7166,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Update scrolling if (scroll_track_selected_tab_id) if (ImGuiTabItem* scroll_track_selected_tab = TabBarFindTabByID(tab_bar, scroll_track_selected_tab_id)) - TabBarScrollToTab(tab_bar, scroll_track_selected_tab); + TabBarScrollToTab(tab_bar, scroll_track_selected_tab, sections); tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim); tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget); if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget) @@ -7183,6 +7182,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) { tab_bar->ScrollingSpeed = 0.0f; } + tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing; + tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing; // Clear name buffers if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) @@ -7264,13 +7265,12 @@ static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling) return ImMax(scrolling, 0.0f); } -static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) +static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImGuiTabBarSection* sections) { if (tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) return; ImGuiContext& g = *GImGui; - ImGuiTabBarSection* sections = tab_bar->Sections; float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) int order = tab_bar->GetTabOrder(tab); @@ -7336,7 +7336,7 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - const ImVec2 arrow_button_size = GetTabBarScrollingButtonSize(); + const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f); const float scrolling_buttons_width = arrow_button_size.x * 2.0f; const ImVec2 backup_cursor_pos = window->DC.CursorPos; @@ -7605,21 +7605,19 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, const ImVec2 backup_main_cursor_pos = window->DC.CursorPos; // Layout + const bool is_central_section = (tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) == 0; size.x = tab->Width; - if (tab->Flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) - window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f); - else + if (is_central_section) window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_FLOOR(tab->Offset - tab_bar->ScrollingAnim), 0.0f); + else + window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f); ImVec2 pos = window->DC.CursorPos; ImRect bb(pos, pos + size); // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) - // Leading buttons will be clipped by BarRect.Max.x, Trailing buttons will be clipped at BarRect.Min.x + LeadingsWidth (+ spacing if there are some buttons), and central tabs will be clipped inbetween - float offset_trailing = (flags & (ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_Leading)) ? 0.0f : tab_bar->Sections[2].Width + tab_bar->Sections[1].Spacing; - float offset_leading = (flags & ImGuiTabItemFlags_Leading) ? 0.0f : tab_bar->Sections[0].Width + tab_bar->Sections[0].Spacing; - bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x + offset_leading) || (bb.Max.x > tab_bar->BarRect.Max.x - offset_trailing); + const bool want_clip_rect = is_central_section && (bb.Min.x < tab_bar->ScrollingRectMinX || bb.Max.x > tab_bar->ScrollingRectMaxX); if (want_clip_rect) - PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x + offset_leading), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x - offset_trailing, bb.Max.y), true); + PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->ScrollingRectMinX), bb.Min.y - 1), ImVec2(tab_bar->ScrollingRectMaxX, bb.Max.y), true); ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; ItemSize(bb.GetSize(), style.FramePadding.y); From fbabf651f4285b9b46428f7d9accb21cedbf9624 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 25 Sep 2020 13:20:57 +0200 Subject: [PATCH 288/959] Style: Renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. Fixed README links. --- docs/CHANGELOG.txt | 1 + docs/README.md | 4 ++-- imgui.cpp | 6 +++--- imgui.h | 2 +- imgui_widgets.cpp | 3 ++- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4be7d31d..1a3980cb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,6 +42,7 @@ Breaking Changes: It was also getting in the way of better font scaling, so let's get rid of it now! If you used DisplayOffset it was probably in association to rasterizing a font at a specific size, in which case the corresponding offset may be reported into GlyphOffset. (#1619) +- Style: Renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - Renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), REVERTED CHANGE FROM 1.77. For variety of reason this is more self-explanatory. - Removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it diff --git a/docs/README.md b/docs/README.md index 41279f60..f696b274 100644 --- a/docs/README.md +++ b/docs/README.md @@ -85,7 +85,7 @@ Dear ImGui allows you to **create elaborate tools** as well as very short-lived ### How it works -Check out the Wiki's [About the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#About-the-IMGUI-paradigm) section if you want to understand the core principles behind the IMGUI paradigm. An IMGUI tries to minimize superfluous state duplication, state synchronization and state retention from the user's point of view. It is less error prone (less code and less bugs) than traditional retained-mode interfaces, and lends itself to create dynamic user interfaces. +Check out the Wiki's [About the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#about-the-imgui-paradigm) section if you want to understand the core principles behind the IMGUI paradigm. An IMGUI tries to minimize superfluous state duplication, state synchronization and state retention from the user's point of view. It is less error prone (less code and less bugs) than traditional retained-mode interfaces, and lends itself to create dynamic user interfaces. Dear ImGui outputs vertex buffers and command lists that you can easily render in your application. The number of draw calls and state changes required to render them is fairly small. Because Dear ImGui doesn't know or touch graphics state directly, you can call its functions anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate Dear ImGui with your existing codebase. @@ -149,7 +149,7 @@ See: [Frequently Asked Questions (FAQ)](https://github.com/ocornut/imgui/blob/ma See: [Wiki](https://github.com/ocornut/imgui/wiki) for many links, references, articles. -See: [Articles about the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#Articles-about-the-IMGUI-paradigm) to read/learn about the Immediate Mode GUI paradigm. +See: [Articles about the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#about-the-imgui-paradigm) to read/learn about the Immediate Mode GUI paradigm. If you are new to Dear ImGui and have issues with: compiling, linking, adding fonts, wiring inputs, running or displaying Dear ImGui: you can use [Discord server](http://discord.dearimgui.org). diff --git a/imgui.cpp b/imgui.cpp index f66cd751..9b337556 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. It was also getting in the way of better font scaling, so let's get rid of it now! @@ -942,7 +943,7 @@ ImGuiStyle::ImGuiStyle() LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. - TabMinWidthForUnselectedCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. 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. @@ -981,8 +982,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) GrabRounding = ImFloor(GrabRounding * scale_factor); LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor); TabRounding = ImFloor(TabRounding * scale_factor); - if (TabMinWidthForUnselectedCloseButton != FLT_MAX) - TabMinWidthForUnselectedCloseButton = ImFloor(TabMinWidthForUnselectedCloseButton * scale_factor); + TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); diff --git a/imgui.h b/imgui.h index 4fc23e83..439429cc 100644 --- a/imgui.h +++ b/imgui.h @@ -1474,7 +1474,7 @@ struct ImGuiStyle float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. - float TabMinWidthForUnselectedCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. + float TabMinWidthForCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. 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. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2fef410d..a3630747 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5943,6 +5943,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ItemSize(size, 0.0f); // Fill horizontal space + // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitely right-aligned sizes not visibly match other widgets. const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x; const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) @@ -7804,7 +7805,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, bool close_button_pressed = false; bool close_button_visible = false; if (close_button_id != 0) - if (is_contents_visible || bb.GetWidth() >= g.Style.TabMinWidthForUnselectedCloseButton) + if (is_contents_visible || bb.GetWidth() >= g.Style.TabMinWidthForCloseButton) if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id) close_button_visible = true; if (close_button_visible) From 324e0310ad39f7467184631493eccfd11d161ddd Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 25 Sep 2020 13:34:31 +0200 Subject: [PATCH 289/959] Renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. (#1829, #3209, #946, #413) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui.h | 7 ++++++- imgui_demo.cpp | 10 +++++----- imgui_widgets.cpp | 15 +++++++-------- 5 files changed, 21 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1a3980cb..d3dad8a0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -43,6 +43,7 @@ Breaking Changes: If you used DisplayOffset it was probably in association to rasterizing a font at a specific size, in which case the corresponding offset may be reported into GlyphOffset. (#1619) - Style: Renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. +- Renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete). - Renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), REVERTED CHANGE FROM 1.77. For variety of reason this is more self-explanatory. - Removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it @@ -161,6 +162,7 @@ Other Changes: which was obsoleted. (#1823, #1316, #642) [@Shironekoben, @AndrewBelt] - Added ImGuiSliderFlags_ClampOnInput flag to force clamping value when using CTRL+Click to type in a value manually. (#1829, #3209, #946, #413). + [note: RENAMED to ImGuiSliderFlags_AlwaysClamp in 1.79]. - Added ImGuiSliderFlags_NoRoundToFormat flag to disable rounding underlying value to match precision of the display format string. (#642) - Added ImGuiSliderFlags_NoInput flag to disable turning widget into a text input diff --git a/imgui.cpp b/imgui.cpp index 9b337556..b1a04674 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently). - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. diff --git a/imgui.h b/imgui.h index 439429cc..8d0ca495 100644 --- a/imgui.h +++ b/imgui.h @@ -1302,11 +1302,16 @@ enum ImGuiColorEditFlags_ enum ImGuiSliderFlags_ { ImGuiSliderFlags_None = 0, - ImGuiSliderFlags_ClampOnInput = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. + ImGuiSliderFlags_AlwaysClamp = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. ImGuiSliderFlags_Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. ImGuiSliderFlags_NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits) ImGuiSliderFlags_NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget ImGuiSliderFlags_InvalidMask_ = 0x7000000F // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp, // [renamed in 1.79] +#endif }; // Identify a mouse button. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index c728bbe1..749d1160 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -617,7 +617,7 @@ static void ShowDemoWindowWidgets() "Hold SHIFT/ALT for faster/slower edit.\n" "Double-click or CTRL+click to input value."); - ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_ClampOnInput); + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); static float f1 = 1.00f, f2 = 0.0067f; ImGui::DragFloat("drag float", &f1, 0.005f); @@ -1558,7 +1558,7 @@ static void ShowDemoWindowWidgets() { // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! static ImGuiSliderFlags flags = ImGuiSliderFlags_None; - ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", (unsigned int*)&flags, ImGuiSliderFlags_ClampOnInput); + ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", (unsigned int*)&flags, ImGuiSliderFlags_AlwaysClamp); ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&flags, ImGuiSliderFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); @@ -1591,7 +1591,7 @@ static void ShowDemoWindowWidgets() { static float begin = 10, end = 90; static int begin_i = 100, end_i = 1000; - ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_ClampOnInput); + ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp); ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units"); ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units"); ImGui::TreePop(); @@ -4029,9 +4029,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "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; - if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_ClampOnInput)) // Scale only this window + 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_ClampOnInput); // Scale everything + ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything ImGui::PopItemWidth(); ImGui::EndTabItem(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a3630747..fd802737 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -2242,8 +2242,8 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (temp_input_is_active) { - // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set - const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); + // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0); return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } @@ -2324,7 +2324,7 @@ bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags); } -// NB: You likely want to specify the ImGuiSliderFlags_ClampOnInput when using this. +// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); @@ -2377,7 +2377,7 @@ bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags); } -// NB: You likely want to specify the ImGuiSliderFlags_ClampOnInput when using this. +// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags) { ImGuiWindow* window = GetCurrentWindow(); @@ -2849,8 +2849,8 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat if (temp_input_is_active) { - // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampInput is set - const bool is_clamp_input = (flags & ImGuiSliderFlags_ClampOnInput) != 0; + // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set + const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0; return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL); } @@ -3178,8 +3178,7 @@ bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* return value_changed; } -// Note that Drag/Slider functions are only forwarding the min/max values clamping values if the -// ImGuiSliderFlags_ClampOnInput / ImGuiSliderFlags_ClampOnInput flag is set! +// Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set! // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility. // However this may not be ideal for all uses, as some user code may break on out of bound values. bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max) From 52c0b1a3406abcbbb9df593b88bb2dd6ffe0290c Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 24 Sep 2020 18:08:01 +0200 Subject: [PATCH 290/959] ImGuiListClipper: internal rework and tidying up to facilitate supporting frozen rows in tables + stop promoting using constructors parameters. --- imgui.cpp | 114 +++++++++++++++++++++++++++++++--------------- imgui.h | 9 ++-- imgui_demo.cpp | 9 ++-- imgui_widgets.cpp | 3 +- 4 files changed, 91 insertions(+), 44 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b1a04674..dac97c99 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2192,35 +2192,44 @@ static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height) columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } -// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 +ImGuiListClipper::ImGuiListClipper(int items_count, float items_height) +{ + DisplayStart = DisplayEnd = 0; + ItemsCount = -1; + StepNo = 0; + ItemsHeight = StartPosY = 0.0f; + Begin(items_count, items_height); +} + +ImGuiListClipper::~ImGuiListClipper() +{ + IM_ASSERT(ItemsCount == -1 && "Forgot to call End(), or to Step() until false?"); +} + +// Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1 // Use case B: Begin() called from constructor with items_height>0 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. -void ImGuiListClipper::Begin(int count, float items_height) +void ImGuiListClipper::Begin(int items_count, float items_height) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; StartPosY = window->DC.CursorPos.y; ItemsHeight = items_height; - ItemsCount = count; + ItemsCount = items_count; StepNo = 0; - DisplayEnd = DisplayStart = -1; - if (ItemsHeight > 0.0f) - { - ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display - if (DisplayStart > 0) - SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor - StepNo = 2; - } + DisplayStart = -1; + DisplayEnd = 0; } void ImGuiListClipper::End() { - if (ItemsCount < 0) + if (ItemsCount < 0) // Already ended return; + // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. - if (ItemsCount < INT_MAX) - SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + if (ItemsCount < INT_MAX && DisplayStart >= 0) + SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); ItemsCount = -1; StepNo = 3; } @@ -2230,38 +2239,70 @@ bool ImGuiListClipper::Step() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - if (ItemsCount == 0 || window->SkipItems) + // Reached end of list + if (DisplayEnd >= ItemsCount || window->SkipItems) { - ItemsCount = -1; + End(); return false; } - if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. + + // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) + if (StepNo == 0) { - DisplayStart = 0; - DisplayEnd = 1; StartPosY = window->DC.CursorPos.y; - StepNo = 1; - return true; + if (ItemsHeight <= 0.0f) + { + // Submit the first item so we can measure its height (generally it is 0..1) + DisplayStart = 0; + DisplayEnd = 1; + StepNo = 1; + return true; + } + + // Already has item height (given by user in Begin): skip to calculating step + DisplayStart = DisplayEnd; + StepNo = 2; } - if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. + + // Step 1: the clipper infer height from first element + if (StepNo == 1) { - if (ItemsCount == 1) { ItemsCount = -1; return false; } - float items_height = window->DC.CursorPos.y - StartPosY; - IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically - Begin(ItemsCount - 1, items_height); - DisplayStart++; - DisplayEnd++; - StepNo = 3; - return true; + IM_ASSERT(ItemsHeight <= 0.0f); + ItemsHeight = window->DC.CursorPos.y - StartPosY; + IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); + StepNo = 2; } - if (StepNo == 2) // Step 2: empty step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + + // Step 2: calculate the actual range of elements to display, and position the cursor before the first element + if (StepNo == 2) { - IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); + IM_ASSERT(ItemsHeight > 0.0f); + + int already_submitted = DisplayEnd; + ImGui::CalcListClipping(ItemsCount - already_submitted, ItemsHeight, &DisplayStart, &DisplayEnd); + DisplayStart += already_submitted; + DisplayEnd += already_submitted; + + // Seek cursor + if (DisplayStart > already_submitted) + SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); + StepNo = 3; return true; } - if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. - End(); + + // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), + // Advance the cursor to the end of the list and then returns 'false' to end the loop. + if (StepNo == 3) + { + // Seek cursor + if (ItemsCount < INT_MAX) + SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + ItemsCount = -1; + return false; + } + + IM_ASSERT(0); return false; } @@ -8062,7 +8103,7 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. if (policy == ImGuiPopupPositionPolicy_Tooltip) - return ref_pos + ImVec2(2, 2); + return ref_pos + ImVec2(2, 2); // Otherwise try to keep within display ImVec2 pos = ref_pos; @@ -10439,7 +10480,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, true, false); // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. - ImGuiListClipper clipper(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + ImGuiListClipper clipper; + clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) { diff --git a/imgui.h b/imgui.h index 8d0ca495..67516adc 100644 --- a/imgui.h +++ b/imgui.h @@ -1900,7 +1900,8 @@ struct ImGuiStorage // - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. struct ImGuiListClipper { - int DisplayStart, DisplayEnd; + int DisplayStart; + int DisplayEnd; int ItemsCount; // [Internal] @@ -1911,12 +1912,12 @@ struct ImGuiListClipper // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). - ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). - ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. + ImGuiListClipper(int items_count = -1, float items_height = -1.0f); + ~ImGuiListClipper(); - IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. }; // Helpers macros to generate 32-bit encoded colors diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 749d1160..96c0034e 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3340,7 +3340,8 @@ static void ShowDemoWindowColumns() ImGui::BeginChild("##ScrollingRegion", child_size, false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::Columns(10); int ITEMS_COUNT = 2000; - ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list + ImGuiListClipper clipper; // Also demonstrate using the clipper for large list + clipper.Begin(ITEMS_COUNT); while (clipper.Step()) { for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) @@ -4330,7 +4331,8 @@ struct ExampleAppConsole // To use the clipper we can replace your standard loop: // for (int i = 0; i < Items.Size; i++) // With: - // ImGuiListClipper clipper(Items.Size); + // ImGuiListClipper clipper; + // clipper.Begin(Items.Size); // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) // - That your items are evenly spaced (same height) @@ -4897,7 +4899,8 @@ static void ShowExampleAppLongText(bool* p_open) { // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); - ImGuiListClipper clipper(lines); + ImGuiListClipper clipper; + clipper.Begin(lines); while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fd802737..c5b44f80 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6154,7 +6154,8 @@ bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(v // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. ImGuiContext& g = *GImGui; bool value_changed = false; - ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. + ImGuiListClipper clipper; + clipper.Begin(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { From c49330fc521134651d3a7ea4c6524474e9b0861c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2020 14:11:22 +0200 Subject: [PATCH 291/959] Docking: Fix handling of WindowMenuButtonPosition == ImGuiDir_None in Docking Nodes. (#3499) --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 05969a5f..a83a947a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -13254,7 +13254,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w node->IsFocused = is_focused; const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); - const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; + const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None); const bool has_close_button = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0; // In a dock node, the Collapse Button turns into the Window Menu button. From 179dc04d8a3969654def9c60c7db31864b07580c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2020 14:22:36 +0200 Subject: [PATCH 292/959] Examples: Added missing comments in example_apple_metal. (#3400) --- examples/example_apple_metal/README.md | 4 ++- .../example_apple_metal/Shared/Renderer.mm | 35 ++++++++++++++++--- examples/example_apple_opengl2/main.mm | 4 ++- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/examples/example_apple_metal/README.md b/examples/example_apple_metal/README.md index 4f620327..c13df2f1 100644 --- a/examples/example_apple_metal/README.md +++ b/examples/example_apple_metal/README.md @@ -4,5 +4,7 @@ This example shows how to integrate Dear ImGui with Metal. It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. -(NB: you may still want to use GLFW or SDL which will also support Windows, Linux along with OSX.) +Consider basing your work off the example_glfw_metal/ or example_sdl_metal/ examples. They are better supported and will be portable unlike this one. + + diff --git a/examples/example_apple_metal/Shared/Renderer.mm b/examples/example_apple_metal/Shared/Renderer.mm index efc3332b..3f7e32d1 100644 --- a/examples/example_apple_metal/Shared/Renderer.mm +++ b/examples/example_apple_metal/Shared/Renderer.mm @@ -15,7 +15,7 @@ @implementation Renderer --(nonnull instancetype)initWithView:(nonnull MTKView *)view; +-(nonnull instancetype)initWithView:(nonnull MTKView*)view; { self = [super init]; if(self) @@ -23,17 +23,41 @@ _device = view.device; _commandQueue = [_device newCommandQueue]; + // Setup Dear ImGui context + // FIXME: This example doesn't have proper cleanup... IMGUI_CHECKVERSION(); ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + // Setup Renderer bindings ImGui_ImplMetal_Init(_device); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Read 'docs/FONTS.txt' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != NULL); } return self; } -- (void)drawInMTKView:(MTKView *)view +- (void)drawInMTKView:(MTKView*)view { ImGuiIO &io = ImGui::GetIO(); io.DisplaySize.x = view.bounds.size.width; @@ -50,11 +74,12 @@ id commandBuffer = [self.commandQueue commandBuffer]; + // Our state (make them static = more or less global) as a convenience to keep the example terse. static bool show_demo_window = true; static bool show_another_window = false; static float clear_color[4] = { 0.28f, 0.36f, 0.5f, 1.0f }; - MTLRenderPassDescriptor *renderPassDescriptor = view.currentRenderPassDescriptor; + MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor; if (renderPassDescriptor != nil) { renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0], clear_color[1], clear_color[2], clear_color[3]); @@ -110,7 +135,7 @@ // Rendering ImGui::Render(); - ImDrawData *drawData = ImGui::GetDrawData(); + ImDrawData* drawData = ImGui::GetDrawData(); ImGui_ImplMetal_RenderDrawData(drawData, commandBuffer, renderEncoder); [renderEncoder popDebugGroup]; @@ -122,7 +147,7 @@ [commandBuffer commit]; } -- (void)mtkView:(MTKView *)view drawableSizeWillChange:(CGSize)size +- (void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size { } diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 7cbf3409..133f928a 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -45,7 +45,7 @@ ImGui_ImplOSX_NewFrame(self); ImGui::NewFrame(); - // Global data for the demo + // Our state (make them static = more or less global) as a convenience to keep the example terse. static bool show_demo_window = true; static bool show_another_window = false; static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); @@ -243,10 +243,12 @@ NSLog(@"No OpenGL Context!"); // Setup Dear ImGui context + // FIXME: This example doesn't have proper cleanup... IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); From 3be352fc80d38da2cb72e54fc76439c2a8d72720 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 28 Sep 2020 12:29:54 +0300 Subject: [PATCH 293/959] CI: Add discord notifications. --- .github/workflows/build.yml | 40 +++++++++++++++++++++++++++ .github/workflows/static-analysis.yml | 8 ++++++ 2 files changed, 48 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index eea8eaa3..83c862da 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -179,6 +179,14 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' + - uses: sarisia/actions-status-discord@v1 + if: failure() + with: + webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + username: GitHub Actions + color: 0xFF0000 + title: ${{ github.job }} + Linux: runs-on: ubuntu-20.04 steps: @@ -310,6 +318,14 @@ jobs: - name: Build example_sdl_opengl3 run: make -C examples/example_sdl_opengl3 + - uses: sarisia/actions-status-discord@v1 + if: failure() + with: + webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + username: GitHub Actions + color: 0xFF0000 + title: ${{ github.job }} + MacOS: runs-on: macOS-latest steps: @@ -365,6 +381,14 @@ jobs: - name: Build example_apple_opengl2 run: xcodebuild -project examples/example_apple_opengl2/example_apple_opengl2.xcodeproj -target example_osx_opengl2 + - uses: sarisia/actions-status-discord@v1 + if: failure() + with: + webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + username: GitHub Actions + color: 0xFF0000 + title: ${{ github.job }} + iOS: runs-on: macOS-latest steps: @@ -377,6 +401,14 @@ jobs: # Code signing is required, but we disable it because it is irrelevant for CI builds. xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_ios CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO + - uses: sarisia/actions-status-discord@v1 + if: failure() + with: + webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + username: GitHub Actions + color: 0xFF0000 + title: ${{ github.job }} + Emscripten: runs-on: ubuntu-18.04 steps: @@ -398,3 +430,11 @@ jobs: source ./emsdk_env.sh popd make -C examples/example_emscripten + + - uses: sarisia/actions-status-discord@v1 + if: failure() + with: + webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + username: GitHub Actions + color: 0xFF0000 + title: ${{ github.job }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 7967d532..3681ecb2 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -41,3 +41,11 @@ jobs: pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log plog-converter -a 'GA:1,2;OP:1' -t errorfile -w pvs-studio.log + + - uses: sarisia/actions-status-discord@v1 + if: failure() + with: + webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + username: GitHub Actions + color: 0xFF0000 + title: ${{ github.job }} From 5f336ce8f83ff6924fa264b74b5405353f4cecb3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Oct 2020 13:27:24 +0200 Subject: [PATCH 294/959] Tab Bar: Fixed buffer underflow in TabBarLayout, introduced by 4a57a982b (#3501, #3291) + Link to CI actions added in 3be352f --- .github/workflows/build.yml | 4 ++++ imgui_widgets.cpp | 15 +++++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 83c862da..a15d5e23 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -318,6 +318,7 @@ jobs: - name: Build example_sdl_opengl3 run: make -C examples/example_sdl_opengl3 + # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - uses: sarisia/actions-status-discord@v1 if: failure() with: @@ -381,6 +382,7 @@ jobs: - name: Build example_apple_opengl2 run: xcodebuild -project examples/example_apple_opengl2/example_apple_opengl2.xcodeproj -target example_osx_opengl2 + # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - uses: sarisia/actions-status-discord@v1 if: failure() with: @@ -401,6 +403,7 @@ jobs: # Code signing is required, but we disable it because it is irrelevant for CI builds. xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_ios CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO + # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - uses: sarisia/actions-status-discord@v1 if: failure() with: @@ -431,6 +434,7 @@ jobs: popd make -C examples/example_emscripten + # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - uses: sarisia/actions-status-discord@v1 if: failure() with: diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index c5b44f80..33ddb376 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6999,13 +6999,16 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab->IndexDuringLayout = (ImS8)tab_dst_n; // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) - ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1]; int curr_tab_section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; - int prev_tab_section_n = (prev_tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (prev_tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; - if (tab_dst_n > 0 && curr_tab_section_n == 0 && prev_tab_section_n != 0) - need_sort_by_section = true; - if (tab_dst_n > 0 && prev_tab_section_n == 2 && curr_tab_section_n != 2) - need_sort_by_section = true; + if (tab_dst_n > 0) + { + ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1]; + int prev_tab_section_n = (prev_tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (prev_tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; + if (curr_tab_section_n == 0 && prev_tab_section_n != 0) + need_sort_by_section = true; + if (prev_tab_section_n == 2 && curr_tab_section_n != 2) + need_sort_by_section = true; + } sections[curr_tab_section_n].TabCount++; tab_dst_n++; From 7b1ab5b27586a3b297aac336d6a97873b11d4078 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Oct 2020 14:07:20 +0200 Subject: [PATCH 295/959] ImVector: Stricter bound-checking asserts. Fix warnings: trailing comma (old compilers), zealous preprocessor warnings. --- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_sdl_opengl3/main.cpp | 2 +- imgui.h | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 30943301..aa43471a 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -56,7 +56,7 @@ int main(int, char**) return 1; // Decide GL+GLSL versions -#if __APPLE__ +#ifdef __APPLE__ // GL 3.2 + GLSL 150 const char* glsl_version = "#version 150"; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 92d03138..c61bc544 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -48,7 +48,7 @@ int main(int, char**) } // Decide GL+GLSL versions -#if __APPLE__ +#ifdef __APPLE__ // GL 3.2 Core + GLSL 150 const char* glsl_version = "#version 150"; SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac diff --git a/imgui.h b/imgui.h index 67516adc..9bf7ff35 100644 --- a/imgui.h +++ b/imgui.h @@ -1310,7 +1310,7 @@ enum ImGuiSliderFlags_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp, // [renamed in 1.79] + , ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp // [renamed in 1.79] #endif }; @@ -1408,8 +1408,8 @@ struct ImVector inline int size_in_bytes() const { return Size * (int)sizeof(T); } inline int max_size() const { return 0x7FFFFFFF / (int)sizeof(T); } inline int capacity() const { return Capacity; } - inline T& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } - inline const T& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } + inline T& operator[](int i) { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } + inline const T& operator[](int i) const { IM_ASSERT(i >= 0 && i < Size); return Data[i]; } inline void clear() { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } } inline T* begin() { return Data; } From 6469b94304e5c6e521054a654d3172f47b2d0019 Mon Sep 17 00:00:00 2001 From: Bartosz Taudul Date: Fri, 2 Oct 2020 19:12:53 +0200 Subject: [PATCH 296/959] Silence memset warning. (#3505) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Compiling the code as-is results in the following warning: -->8-- imgui_freetype.cpp:341:72: warning: ‘void* memset(void*, int, size_t)’ clearing an object of type ‘struct ImFontBuildSrcDataFT’ with no trivial copy-assignment; use assignment or value-initialization instead [-Wclass-memaccess] 341 | memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes()); | ^ imgui_freetype.cpp:302:8: note: ‘struct ImFontBuildSrcDataFT’ declared here 302 | struct ImFontBuildSrcDataFT | ^~~~~~~~~~~~~~~~~~~~ --8<-- This is caused by presence of ImVector<> directly in ImFontBuildSrcDataFT data structure, as well as in the child ImBitVector. Since ImVector<> has a constructor, the compiler infers that initialization by memset is not valid. Such initialization is not a bug, however, as the default ImVector<> ctor just sets the structure data members to 0, which is exactly what the memset does. Casting the data structure address to void* pointer silences this warning. --- misc/freetype/imgui_freetype.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index 3d62dc4b..412411a9 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -338,8 +338,8 @@ bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, uns ImVector dst_tmp_array; src_tmp_array.resize(atlas->ConfigData.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()); + 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->ConfigData.Size; src_i++) From 01cc6660395032714e7a991eba679a9c69b00c5b Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Oct 2020 12:28:28 +0200 Subject: [PATCH 297/959] ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases. --- docs/CHANGELOG.txt | 6 +++++- imgui.cpp | 8 +++----- imgui.h | 39 +++++++++++++++++++++++---------------- 3 files changed, 31 insertions(+), 22 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d3dad8a0..633293f7 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -42,10 +42,14 @@ Breaking Changes: It was also getting in the way of better font scaling, so let's get rid of it now! If you used DisplayOffset it was probably in association to rasterizing a font at a specific size, in which case the corresponding offset may be reported into GlyphOffset. (#1619) +- ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using + the ImGuiListClipper::Begin() function, with misleading edge cases. Always use ImGuiListClipper::Begin()! + Kept inline redirection function (will obsolete). + (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). - Style: Renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - Renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete). - Renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), REVERTED CHANGE FROM 1.77. - For variety of reason this is more self-explanatory. + For variety of reason this is more self-explanatory. Kept inline redirection function. - Removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popups API and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. diff --git a/imgui.cpp b/imgui.cpp index dac97c99..429dbb1a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -372,6 +372,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently). - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. @@ -2192,13 +2193,10 @@ static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height) columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } -ImGuiListClipper::ImGuiListClipper(int items_count, float items_height) +ImGuiListClipper::ImGuiListClipper() { - DisplayStart = DisplayEnd = 0; + memset(this, 0, sizeof(*this)); ItemsCount = -1; - StepNo = 0; - ItemsHeight = StartPosY = 0.0f; - Begin(items_count, items_height); } ImGuiListClipper::~ImGuiListClipper() diff --git a/imgui.h b/imgui.h index 9bf7ff35..d72243e4 100644 --- a/imgui.h +++ b/imgui.h @@ -1886,38 +1886,45 @@ struct ImGuiStorage }; // Helper: Manually clip large list of items. -// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. +// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse +// clipping based on visibility to save yourself from processing those items at all. // The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. -// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. +// (Dear ImGui already clip items based on their bounds but it needs to measure text size to do so, whereas manual coarse clipping before submission makes this cost and your own data fetching/submission cost almost null) // Usage: -// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. -// while (clipper.Step()) -// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) -// ImGui::Text("line number %d", i); -// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). -// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. -// - (Step 2: empty step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) -// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. +// ImGuiListClipper clipper; +// clipper.Begin(1000); // We have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// Generally what happens is: +// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. +// - User code submit one element. +// - Clipper can measure the height of the first element +// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. +// - User code submit visible elements. struct ImGuiListClipper { int DisplayStart; int DisplayEnd; - int ItemsCount; // [Internal] + int ItemsCount; int StepNo; float ItemsHeight; float StartPosY; - // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). - // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). - // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). - ImGuiListClipper(int items_count = -1, float items_height = -1.0f); - ~ImGuiListClipper(); + IMGUI_API ImGuiListClipper(); + IMGUI_API ~ImGuiListClipper(); + // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step) + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + 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 }; // Helpers macros to generate 32-bit encoded colors From 014e5078a86a18ad91ef852d22a294a57e4ef6a3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Oct 2020 12:57:05 +0200 Subject: [PATCH 298/959] Demo: add a small easter egg when the 4x4 board of Selectable is filled + tweaked the demo. --- imgui_demo.cpp | 45 ++++++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 96c0034e..eb7e24b9 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1088,27 +1088,34 @@ static void ShowDemoWindowWidgets() } if (ImGui::TreeNode("Grid")) { - static int selected[4 * 4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; - for (int i = 0; i < 4 * 4; i++) - { - ImGui::PushID(i); - if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50, 50))) + static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; + + // Add in a bit of silly fun... + const float time = (float)ImGui::GetTime(); + const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected... + if (winning_state) + ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f))); + + for (int y = 0; y < 4; y++) + for (int x = 0; x < 4; x++) { - // Toggle - selected[i] = !selected[i]; - - // Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer. - // The second part of each test is unnecessary. - int x = i % 4; - int y = i / 4; - if (x > 0) { selected[i - 1] ^= 1; } - if (x < 3 && i < 15) { selected[i + 1] ^= 1; } - if (y > 0 && i > 3) { selected[i - 4] ^= 1; } - if (y < 3 && i < 12) { selected[i + 4] ^= 1; } + if (x > 0) + ImGui::SameLine(); + ImGui::PushID(y * 4 + x); + if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50))) + { + // Toggle clicked cell + toggle neighbors + selected[y][x] ^= 1; + if (x > 0) { selected[y][x - 1] ^= 1; } + if (x < 3) { selected[y][x + 1] ^= 1; } + if (y > 0) { selected[y - 1][x] ^= 1; } + if (y < 3) { selected[y + 1][x] ^= 1; } + } + ImGui::PopID(); } - if ((i % 4) < 3) ImGui::SameLine(); - ImGui::PopID(); - } + + if (winning_state) + ImGui::PopStyleVar(); ImGui::TreePop(); } if (ImGui::TreeNode("Alignment")) From 4fd43a8b64155d9c01c615afd5b0831a60b47c0f Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Oct 2020 14:52:18 +0200 Subject: [PATCH 299/959] Internals: removed NavLayerCurrentMask (redundant, add extra shift in ItemAdd(). --- imgui.cpp | 7 +------ imgui_internal.h | 6 ++---- imgui_widgets.cpp | 4 +--- 3 files changed, 4 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 429dbb1a..c825d16e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5142,7 +5142,6 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Resize grips and borders are on layer 1 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); // Manual resize grips PushID("#RESIZE"); @@ -5211,7 +5210,6 @@ static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& s // Restore nav layer window->DC.NavLayerCurrent = ImGuiNavLayer_Main; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); // Navigation resize (keyboard/gamepad) if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window) @@ -5382,7 +5380,6 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); // Layout buttons // FIXME: Would be nice to generalize the subtleties expressed here into reusable code. @@ -5418,7 +5415,6 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl *p_open = false; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->DC.ItemFlags = item_flags_backup; // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) @@ -5994,7 +5990,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // -V595 @@ -7035,7 +7030,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null. // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere. - window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask; + window->DC.NavLayerActiveMaskNext |= (1 << window->DC.NavLayerCurrent); if (g.NavId == id || g.NavAnyRequest) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) diff --git a/imgui_internal.h b/imgui_internal.h index 856b2a63..896a8ae5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1497,9 +1497,8 @@ struct IMGUI_API ImGuiWindowTempData // Keyboard/Gamepad navigation ImGuiNavLayer NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1) - int NavLayerCurrentMask; // = (1 << NavLayerCurrent) used by ItemAdd prior to clipping. - int NavLayerActiveMask; // Which layer have been written to (result from previous frame) - int NavLayerActiveMaskNext; // Which layer have been written to (buffer for current frame) + int NavLayerActiveMask; // Which layers have been written to (result from previous frame) + int NavLayerActiveMaskNext; // Which layers have been written to (accumulator for current frame) ImGuiID NavFocusScopeIdCurrent; // Current focus scope ID while appending bool NavHideHighlightOneFrame; bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f) @@ -1544,7 +1543,6 @@ struct IMGUI_API ImGuiWindowTempData NavLayerActiveMask = NavLayerActiveMaskNext = 0x00; NavLayerCurrent = ImGuiNavLayer_Main; - NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); NavFocusScopeIdCurrent = 0; NavHideHighlightOneFrame = false; NavHasScroll = false; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 33ddb376..1f3ba21b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3833,7 +3833,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ return false; } draw_window = g.CurrentWindow; // Child window - draw_window->DC.NavLayerActiveMaskNext |= draw_window->DC.NavLayerCurrentMask; // This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it. + draw_window->DC.NavLayerActiveMaskNext |= (1 << draw_window->DC.NavLayerCurrent); // This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it. inner_size.x -= draw_window->ScrollbarSizes.x; } else @@ -6462,7 +6462,6 @@ bool ImGui::BeginMenuBar() window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); window->DC.LayoutType = ImGuiLayoutType_Horizontal; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); window->DC.MenuBarAppending = true; AlignTextToFramePadding(); return true; @@ -6505,7 +6504,6 @@ void ImGui::EndMenuBar() EndGroup(); // Restore position on layer 0 window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; - window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->DC.MenuBarAppending = false; } From 12d95055347e452c48bf663a9aa02e8338bec154 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Oct 2020 15:13:04 +0200 Subject: [PATCH 300/959] CheckboxFlags: Display mixed-value/tristate marker when passed flags that have multiple bits set and stored value matches neither zero neither the full set. --- docs/CHANGELOG.txt | 14 ++++++++------ imgui_widgets.cpp | 21 ++++++++++++++++++--- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 633293f7..220fef30 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -39,12 +39,12 @@ Breaking Changes: - Fonts: Removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. - It was also getting in the way of better font scaling, so let's get rid of it now! + It was also getting in the way of better font scaling, so let's get rid of it now! If you used DisplayOffset it was probably in association to rasterizing a font at a specific size, in which case the corresponding offset may be reported into GlyphOffset. (#1619) -- ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using +- ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases. Always use ImGuiListClipper::Begin()! - Kept inline redirection function (will obsolete). + Kept inline redirection function (will obsolete). (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). - Style: Renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - Renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete). @@ -72,7 +72,7 @@ Other Changes: - InputText: Fixed cursor being partially covered after using Ctrl+End key. - InputText: Fixed callback's helper DeleteChars() function when cursor is inside the deleted block. (#3454) - InputText: Made pressing Down arrow on the last line when it doesn't have a carriage return not move to - the end of the line (so it is consistent with Up arrow, and behave same as Notepad and Visual Studio. + the end of the line (so it is consistent with Up arrow, and behave same as Notepad and Visual Studio. Note that some other text editors instead would move the crusor to the end of the line). [@Xipiryon] - DragFloat, DragScalar: Fixed ImGuiSliderFlags_ClampOnInput not being honored in the special case where v_min == v_max. (#3361) @@ -80,6 +80,8 @@ Other Changes: with signed and unsigned types. Added reverse Sliders to Demo. (#3432, #3449) [@rokups] - Text: Bypass unnecessary formatting when using the TextColored()/TextWrapped()/TextDisabled() helpers with a "%s" format string. (#3466) +- CheckboxFlags: Display mixed-value/tristate marker when passed flags that have multiple bits set and + stored value matches neither zero neither the full set. - BeginMenuBar: Fixed minor bug where CursorPosMax gets pushed to CursorPos prior to calling BeginMenuBar(), so e.g. calling the function at the end of a window would often add +ItemSpacing.y to scrolling range. - TreeNode, CollapsingHeader: Made clicking on arrow toggle toggle the open state on the Mouse Down event @@ -87,7 +89,7 @@ Other Changes: and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) - Tab Bar: Added TabItemButton() to submit tab that behave like a button. (#3291) [@Xipiryon] -- Tab Bar: Added ImGuiTabItemFlags_Leading and ImGuiTabItemFlags_Trailing flags to position tabs or button +- Tab Bar: Added ImGuiTabItemFlags_Leading and ImGuiTabItemFlags_Trailing flags to position tabs or button at either end of the tab bar. Those tabs won't be part of the scrolling region, and when reordering cannot be moving outside of their section. Most often used with TabItemButton(). (#3291) [@Xipiryon] - Tab Bar: Added ImGuiTabItemFlags_NoReorder flag to disable reordering a given tab. @@ -104,7 +106,7 @@ Other Changes: - Fonts: AddFontDefault() adjust its vertical offset based on floor(size/13) instead of always +1. - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). -- Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 contexts which have +- Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 contexts which have the defines set by a loader. (#3467, #1985) [@jjwebb] - Backends: Vulkan: Some internal refactor aimed at allowing multi-viewport feature to create their own render pass. (#3455, #3459) [@FunMiles] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1f3ba21b..1214523a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1071,7 +1071,8 @@ bool ImGui::Checkbox(const char* label, bool* v) RenderNavHighlight(total_bb, id); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); - if (window->DC.ItemFlags & ImGuiItemFlags_MixedValue) + bool mixed_value = (window->DC.ItemFlags & ImGuiItemFlags_MixedValue) != 0; + if (mixed_value) { // Undocumented tristate/mixed/indeterminate checkbox (#2644) ImVec2 pad(ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)), ImMax(1.0f, IM_FLOOR(square_sz / 3.6f))); @@ -1084,7 +1085,7 @@ bool ImGui::Checkbox(const char* label, bool* v) } if (g.LogEnabled) - LogRenderedText(&total_bb.Min, *v ? "[x]" : "[ ]"); + LogRenderedText(&total_bb.Min, mixed_value ? "[~]" : *v ? "[x]" : "[ ]"); if (label_size.x > 0.0f) RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label); @@ -1095,7 +1096,21 @@ bool ImGui::Checkbox(const char* label, bool* v) bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { bool v = ((*flags & flags_value) == flags_value); - bool pressed = Checkbox(label, &v); + bool pressed; + if (v == false && (*flags & flags_value) != 0) + { + // Mixed value (FIXME: find a way to expose neatly to Checkbox?) + ImGuiWindow* window = GetCurrentWindow(); + const ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; + window->DC.ItemFlags |= ImGuiItemFlags_MixedValue; + pressed = Checkbox(label, &v); + window->DC.ItemFlags = backup_item_flags; + } + else + { + // Regular checkbox + pressed = Checkbox(label, &v); + } if (pressed) { if (v) From 03b1e643b48768db7c47b8b52553738c69361beb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Oct 2020 10:47:10 +0200 Subject: [PATCH 301/959] Docs: Funding link, Tweaks, Gallery links. --- .github/FUNDING.yml | 1 + imgui_widgets.cpp | 1 + 2 files changed, 2 insertions(+) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..2aa08b44 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +custom: ['https://github.com/ocornut/imgui/wiki/Sponsors'] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 1214523a..d0cc5b2f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7841,6 +7841,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, text_pixel_clip_bb.Max.x -= close_button_sz; } + // 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; 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); From ae5b4991be80cb516162703e6ea51976ae929763 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 8 Oct 2020 13:56:05 +0200 Subject: [PATCH 302/959] Docs: update gallery links. (#3514) --- docs/FAQ.md | 4 ++-- docs/README.md | 4 ++-- imgui.cpp | 4 ++-- imgui.h | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 2745b122..acc99ede 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -600,7 +600,7 @@ You may take a look at: - [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) -- [Gallery](https://github.com/ocornut/imgui/issues/3075) +- [Gallery](https://github.com/ocornut/imgui/issues/3488) ##### [Return to Index](#index) @@ -646,7 +646,7 @@ There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/ci - Individuals: you can support continued maintenance and development via PayPal donations. See [README](https://github.com/ocornut/imgui/blob/master/docs/README.md). - If you are experienced with Dear ImGui and C++, look at the [GitHub Issues](https://github.com/ocornut/imgui/issues), look at the [Wiki](https://github.com/ocornut/imgui/wiki), read [docs/TODO.txt](https://github.com/ocornut/imgui/blob/master/docs/TODO.txt) and see how you want to help and can help! - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. -You may post screenshot or links in the [gallery threads](https://github.com/ocornut/imgui/issues/3075). Visuals are ideal as they inspire other programmers. Disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. +You may post screenshot or links in the [gallery threads](https://github.com/ocornut/imgui/issues/3488). Visuals are ideal as they inspire other programmers. Disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues or sometimes incomplete PR. ##### [Return to Index](#index) diff --git a/docs/README.md b/docs/README.md index f696b274..81c92b3c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -132,7 +132,7 @@ Some of the goals for 2020 are: ### Gallery -For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/3075)! +For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/3488)! Custom engine [![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) @@ -165,7 +165,7 @@ Advanced users may want to use the `docking` branch with [Multi-Viewport](https: **Who uses Dear ImGui?** -See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors), [Software using dear imgui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also see the [Gallery Threads](https://github.com/ocornut/imgui/issues/3075)! +See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors), [Software using dear imgui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also see the [Gallery Threads](https://github.com/ocornut/imgui/issues/3488)! How to help ----------- diff --git a/imgui.cpp b/imgui.cpp index c825d16e..2425cf2c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11,7 +11,7 @@ // - FAQ http://dearimgui.org/faq // - Homepage & latest https://github.com/ocornut/imgui // - Releases & changelog https://github.com/ocornut/imgui/releases -// - Gallery https://github.com/ocornut/imgui/issues/3075 (please post your screenshots/video there!) +// - Gallery https://github.com/ocornut/imgui/issues/3488 (please post your screenshots/video there!) // - Glossary https://github.com/ocornut/imgui/wiki/Glossary // - Wiki https://github.com/ocornut/imgui/wiki // - Issues & support https://github.com/ocornut/imgui/issues @@ -703,7 +703,7 @@ CODE - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt and see how you want to help and can help! - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. - You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/3075). Visuals are ideal as they inspire other programmers. + You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/3488). Visuals are ideal as they inspire other programmers. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately). diff --git a/imgui.h b/imgui.h index d72243e4..7fe14c4e 100644 --- a/imgui.h +++ b/imgui.h @@ -11,7 +11,7 @@ // - FAQ http://dearimgui.org/faq // - Homepage & latest https://github.com/ocornut/imgui // - Releases & changelog https://github.com/ocornut/imgui/releases -// - Gallery https://github.com/ocornut/imgui/issues/3075 (please post your screenshots/video there!) +// - Gallery https://github.com/ocornut/imgui/issues/3488 (please post your screenshots/video there!) // - Glossary https://github.com/ocornut/imgui/wiki/Glossary // - Wiki https://github.com/ocornut/imgui/wiki // - Issues & support https://github.com/ocornut/imgui/issues From c6f9c558ec53fba6862625bda0f222939428a180 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Thu, 8 Oct 2020 15:06:46 +0300 Subject: [PATCH 303/959] CI: Use our own discord notifier. --- .github/workflows/build.yml | 71 +++++++++++---------------- .github/workflows/static-analysis.yml | 37 +++++++++++--- 2 files changed, 59 insertions(+), 49 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a15d5e23..a8db3199 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -179,14 +179,6 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' - - uses: sarisia/actions-status-discord@v1 - if: failure() - with: - webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} - username: GitHub Actions - color: 0xFF0000 - title: ${{ github.job }} - Linux: runs-on: ubuntu-20.04 steps: @@ -318,15 +310,6 @@ jobs: - name: Build example_sdl_opengl3 run: make -C examples/example_sdl_opengl3 - # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - - uses: sarisia/actions-status-discord@v1 - if: failure() - with: - webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} - username: GitHub Actions - color: 0xFF0000 - title: ${{ github.job }} - MacOS: runs-on: macOS-latest steps: @@ -382,15 +365,6 @@ jobs: - name: Build example_apple_opengl2 run: xcodebuild -project examples/example_apple_opengl2/example_apple_opengl2.xcodeproj -target example_osx_opengl2 - # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - - uses: sarisia/actions-status-discord@v1 - if: failure() - with: - webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} - username: GitHub Actions - color: 0xFF0000 - title: ${{ github.job }} - iOS: runs-on: macOS-latest steps: @@ -403,15 +377,6 @@ jobs: # Code signing is required, but we disable it because it is irrelevant for CI builds. xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_ios CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO - # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - - uses: sarisia/actions-status-discord@v1 - if: failure() - with: - webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} - username: GitHub Actions - color: 0xFF0000 - title: ${{ github.job }} - Emscripten: runs-on: ubuntu-18.04 steps: @@ -434,11 +399,33 @@ jobs: popd make -C examples/example_emscripten - # Use https://github.com/marketplace/actions/actions-status-discord to send status to Discord - - uses: sarisia/actions-status-discord@v1 - if: failure() + Discord-CI: + runs-on: ubuntu-18.04 + if: always() + needs: [Windows, Linux, MacOS, iOS, Emscripten] + steps: + - uses: dearimgui/github_discord_notifier@latest with: - webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} - username: GitHub Actions - color: 0xFF0000 - title: ${{ github.job }} + discord-webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + github-token: ${{ github.token }} + action-task: discord-jobs + discord-filter: "'{{ github.branch }}'.match(/master|docking|tables/g) != null && '{{ run.conclusion }}' != '{{ last_run.conclusion }}'" + discord-username: GitHub Actions + discord-job-new-failure-message: '' + discord-job-fixed-failure-message: '' + discord-job-new-failure-embed: | + { + "title": "`{{ job.name }}` job is failing on `{{ github.branch }}`!", + "description": "Commit [{{ github.context.payload.head_commit.title }}]({{ github.context.payload.head_commit.url }}) pushed to [{{ github.branch }}]({{ github.branch_url }}) broke [{{ job.name }}]({{ job.url }}) build job.\nFailing steps: {{ failing_steps }}", + "url": "{{ job.url }}", + "color": "0xFF0000", + "timestamp": "{{ run.updated_at }}" + } + discord-job-fixed-failure-embed: | + { + "title": "`{{ github.branch }}` branch is no longer failing!", + "description": "Build failures were fixed on [{{ github.branch }}]({{ github.branch_url }}) branch.", + "color": "0x00FF00", + "url": "{{ github.context.payload.head_commit.url }}", + "timestamp": "{{ run.completed_at }}" + } diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 3681ecb2..868b5740 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -42,10 +42,33 @@ jobs: pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log plog-converter -a 'GA:1,2;OP:1' -t errorfile -w pvs-studio.log - - uses: sarisia/actions-status-discord@v1 - if: failure() - with: - webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} - username: GitHub Actions - color: 0xFF0000 - title: ${{ github.job }} + Discord-CI: + runs-on: ubuntu-18.04 + needs: [PVS-Studio] + if: always() + steps: + - uses: dearimgui/github_discord_notifier@latest + with: + discord-webhook: ${{ secrets.DISCORD_CI_WEBHOOK }} + github-token: ${{ github.token }} + action-task: discord-jobs + discord-filter: "'{{ github.branch }}'.match(/master|docking|tables/g) != null && '{{ run.conclusion }}' != '{{ last_run.conclusion }}'" + discord-username: GitHub Actions + discord-job-new-failure-message: '' + discord-job-fixed-failure-message: '' + discord-job-new-failure-embed: | + { + "title": "`{{ job.name }}` job is failing on `{{ github.branch }}`!", + "description": "Commit [{{ github.context.payload.head_commit.title }}]({{ github.context.payload.head_commit.url }}) pushed to [{{ github.branch }}]({{ github.branch_url }}) broke static analysis [{{ job.name }}]({{ job.url }}) job.\nFailing steps: {{ failing_steps }}", + "url": "{{ job.url }}", + "color": "0xFF0000", + "timestamp": "{{ run.updated_at }}" + } + discord-job-fixed-failure-embed: | + { + "title": "`{{ github.branch }}` branch is no longer failing!", + "description": "Staic analysis failures were fixed on [{{ github.branch }}]({{ github.branch_url }}) branch.", + "color": "0x00FF00", + "url": "{{ github.context.payload.head_commit.url }}", + "timestamp": "{{ run.completed_at }}" + } From e5cb04b132cba94f902beb6186cb58b864777012 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 8 Oct 2020 13:55:25 +0200 Subject: [PATCH 304/959] Version 1.79 + Update readme and mission statement. Removed "Minimize screen reel-estate usage", removed details on memory consumption (still very valid, just too much noise in a mission statement) --- .github/workflows/static-analysis.yml | 2 +- docs/CHANGELOG.txt | 10 ++++++---- docs/README.md | 25 +++++++++++++------------ examples/README.txt | 2 +- imgui.cpp | 11 +++++------ imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 10 files changed, 33 insertions(+), 31 deletions(-) diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 868b5740..0b7ef361 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -67,7 +67,7 @@ jobs: discord-job-fixed-failure-embed: | { "title": "`{{ github.branch }}` branch is no longer failing!", - "description": "Staic analysis failures were fixed on [{{ github.branch }}]({{ github.branch_url }}) branch.", + "description": "Static analysis failures were fixed on [{{ github.branch }}]({{ github.branch_url }}) branch.", "color": "0x00FF00", "url": "{{ github.context.payload.head_commit.url }}", "timestamp": "{{ run.completed_at }}" diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 220fef30..729f0b88 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -32,7 +32,7 @@ HOW TO UPDATE? ----------------------------------------------------------------------- - VERSION 1.79 WIP (In Progress) + VERSION 1.79 (Released 2020-10-08) ----------------------------------------------------------------------- Breaking Changes: @@ -42,6 +42,7 @@ Breaking Changes: It was also getting in the way of better font scaling, so let's get rid of it now! If you used DisplayOffset it was probably in association to rasterizing a font at a specific size, in which case the corresponding offset may be reported into GlyphOffset. (#1619) + If you scaled this value after calling AddFontDefault(), this is now done automatically. - ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases. Always use ImGuiListClipper::Begin()! Kept inline redirection function (will obsolete). @@ -49,7 +50,7 @@ Breaking Changes: - Style: Renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - Renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete). - Renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), REVERTED CHANGE FROM 1.77. - For variety of reason this is more self-explanatory. Kept inline redirection function. + For variety of reason this is more self-explanatory and less error-prone. Kept inline redirection function. - Removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popups API and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. @@ -59,8 +60,8 @@ Other Changes: - Window: Fixed using non-zero pivot in SetNextWindowPos() when the window is collapsed. (#3433) - Nav: Fixed navigation resuming on first visible item when using gamepad. [@rokups] - Nav: Fixed using Alt to toggle the Menu layer when inside a Modal window. (#787) -- Scrolling: Fixed SetScrollHere functions edge snapping when called during a frame where ContentSize - is changing (issue introduced in 1.78). (#3452). +- Scrolling: Fixed SetScrollHere(0) functions edge snapping when called during a frame where + ContentSize is changing (issue introduced in 1.78). (#3452). - InputText: Added support for Page Up/Down in InputTextMultiline(). (#3430) [@Xipiryon] - InputText: Added selection helpers in ImGuiInputTextCallbackData(). - InputText: Added ImGuiInputTextFlags_CallbackEdit to modify internally owned buffer after an edit. @@ -104,6 +105,7 @@ Other Changes: - Popups, Tooltips: Fix edge cases issues with positionning popups and tooltips when they are larger than viewport on either or both axises. [@Rokups] - Fonts: AddFontDefault() adjust its vertical offset based on floor(size/13) instead of always +1. + Was previously done by altering DisplayOffset.y but wouldn't work for DPI scaled font. - Metrics: Various tweaks, listing windows front-to-back, greying inactive items when possible. - Demo: Add simple InputText() callbacks demo (aside from the more elaborate ones in 'Examples->Console'). - Backends: OpenGL3: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 contexts which have diff --git a/docs/README.md b/docs/README.md index 81c92b3c..476540de 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,10 +5,12 @@ Dear ImGui (This library is available under a free and permissive license, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out.) -Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts: +Businesses: support continued development and maintenance via invoiced technical support, maintenance, sponsoring contracts:
  _E-mail: contact @ dearimgui dot com_ -Individuals: support continued maintenance and development with [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). +Individuals: support continued development and maintenance [here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). + +Also see [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) page. ---- @@ -18,7 +20,7 @@ Dear ImGui is designed to **enable fast iterations** and to **empower programmer Dear ImGui is particularly suited to integration in games engine (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on consoles platforms where operating system features are non-standard. -| [Usage](#usage) - [How it works](#how-it-works) - [Demo](#demo) - [Integration](#integration) | +| [Usage](#usage) - [How it works](#how-it-works) - [Releases](#releases) - [Demo](#demo) - [Integration](#integration) | :----------------------------------------------------------: | | [Upcoming changes](#upcoming-changes) - [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - [Sponsors](#sponsors) - [Credits](#credits) - [License](#license) | | [Wiki](https://github.com/ocornut/imgui/wiki) - [Language & frameworks bindings](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | @@ -36,7 +38,7 @@ You will need a backend to integrate Dear ImGui in your app. The backend passes After Dear ImGui is setup in your application, you can use it from \_anywhere\_ in your program loop: Code: -```cp +```cpp ImGui::Text("Hello, world %d", 123); if (ImGui::Button("Save")) MySaveFunction(); @@ -45,7 +47,7 @@ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ``` Result:
![sample code output (dark)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v175/capture_readme_styles_0001.png) ![sample code output (light)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v175/capture_readme_styles_0002.png) -
_(settings: Dark style (left), Light style (right) / Font: Roboto-Medium, 16px / Rounding: 5)_ +
_(settings: Dark style (left), Light style (right) / Font: Roboto-Medium, 16px)_ Code: ```cpp @@ -91,6 +93,10 @@ Dear ImGui outputs vertex buffers and command lists that you can easily render i _A common misunderstanding is to mistake immediate mode gui for immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes as the gui functions are called. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely._ +### Releases + +See [Releases](https://github.com/ocornut/imgui/releases) page. + ### Demo Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. @@ -179,12 +185,7 @@ How to help **How can I help financing further development of Dear ImGui?** -Your contributions are keeping this project alive. The library is available under a free and permissive license, but continued maintenance and development are a full-time endeavor and I would like to grow the team. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out for invoiced technical support and maintenance contracts. Thank you! - -Businesses: support continued development via invoiced technical support, maintenance, sponsoring contracts: -
  _E-mail: contact @ dearimgui.com_ - -Individuals: support continued maintenance and development with [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). +See [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) page. Sponsors -------- @@ -214,7 +215,7 @@ Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indi Recurring contributors (2020): Omar Cornut [@ocornut](https://github.com/ocornut), Rokas Kupstys [@rokups](https://github.com/rokups), Ben Carter [@ShironekoBen](https://github.com/ShironekoBen). A large portion of work on automation systems, regression tests and other features are currently unpublished. -"I first discovered the IMGUI paradigm at [Q-Games](http://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it." +Omar: "I first discovered the IMGUI paradigm at [Q-Games](http://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it." Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license). diff --git a/examples/README.txt b/examples/README.txt index e2577edb..68b6c104 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.79 WIP + dear imgui, v1.79 ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 2425cf2c..6e6d65d7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 WIP +// dear imgui, v1.79 // (main code and documentation) // Help: @@ -92,14 +92,13 @@ CODE - Easy to use to create code-driven and data-driven tools. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. - Easy to hack and improve. - - Minimize screen real-estate usage. - Minimize setup and maintenance. - Minimize state storage on user side. - Portable, minimize dependencies, run on target (consoles, phones, etc.). - - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,. - opening a tree node for the first time, etc. but a typical frame should not allocate anything). + - Efficient runtime and memory consumption. + + Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes: - Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - Doesn't look fancy, doesn't animate. - Limited layout features, intricate layouts are typically crafted in code. @@ -377,7 +376,7 @@ CODE - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. - - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. It was also getting in the way of better font scaling, so let's get rid of it now! + - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now! - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: diff --git a/imgui.h b/imgui.h index 7fe14c4e..798ae065 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.79 WIP +// dear imgui, v1.79 // (headers) // Help: @@ -59,8 +59,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.79 WIP" -#define IMGUI_VERSION_NUM 17803 +#define IMGUI_VERSION "1.79" +#define IMGUI_VERSION_NUM 17900 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index eb7e24b9..60be4b2f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 WIP +// dear imgui, v1.79 // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3f666698..c491cd25 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 WIP +// dear imgui, v1.79 // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 896a8ae5..470bf4e9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.79 WIP +// dear imgui, v1.79 // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d0cc5b2f..fe5d2ba3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 WIP +// dear imgui, v1.79 // (widgets code) /* From a38c6dfcc83fba7166c953e54cfbf8dceba7be0b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 9 Oct 2020 17:13:03 +0200 Subject: [PATCH 305/959] Internals: Added support for context hooks (for test engine or other extensions) --- imgui.cpp | 41 ++++++++++++++++++++++++++++++----------- imgui.h | 2 +- imgui_internal.h | 35 +++++++++++++++++++++++++++++------ 3 files changed, 60 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 6e6d65d7..8b7cbd17 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3310,6 +3310,24 @@ void ImGui::DestroyContext(ImGuiContext* ctx) IM_DELETE(ctx); } +// No specific ordering/dependency support, will see as needed +void ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook) +{ + ImGuiContext& g = *ctx; + IM_ASSERT(hook->Callback != NULL); + g.Hooks.push_back(*hook); +} + +// Call context hooks (used by e.g. test engine) +// We assume a small number of hooks so all stored in same array +void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type) +{ + ImGuiContext& g = *ctx; + for (int n = 0; n < g.Hooks.Size; n++) + if (g.Hooks[n].Type == hook_type) + g.Hooks[n].Callback(&g, &g.Hooks[n]); +} + ImGuiIO& ImGui::GetIO() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); @@ -3735,9 +3753,7 @@ void ImGui::NewFrame() IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); ImGuiContext& g = *GImGui; -#ifdef IMGUI_ENABLE_TEST_ENGINE - ImGuiTestEngineHook_PreNewFrame(&g); -#endif + CallContextHooks(&g, ImGuiContextHookType_NewFramePre); // Check and assert for various common IO and Configuration mistakes ErrorCheckNewFrameSanityChecks(); @@ -3907,9 +3923,7 @@ void ImGui::NewFrame() Begin("Debug##Default"); IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true); -#ifdef IMGUI_ENABLE_TEST_ENGINE - ImGuiTestEngineHook_PostNewFrame(&g); -#endif + CallContextHooks(&g, ImGuiContextHookType_NewFramePost); } // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. @@ -3994,15 +4008,12 @@ void ImGui::Shutdown(ImGuiContext* context) if (g.SettingsLoaded && g.IO.IniFilename != NULL) { ImGuiContext* backup_context = GImGui; - SetCurrentContext(context); + SetCurrentContext(&g); SaveIniSettingsToDisk(g.IO.IniFilename); SetCurrentContext(backup_context); } - // Notify hooked test engine, if any -#ifdef IMGUI_ENABLE_TEST_ENGINE - ImGuiTestEngineHook_Shutdown(context); -#endif + CallContextHooks(&g, ImGuiContextHookType_Shutdown); // Clear everything else for (int i = 0; i < g.Windows.Size; i++) @@ -4202,6 +4213,8 @@ void ImGui::EndFrame() return; IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?"); + CallContextHooks(&g, ImGuiContextHookType_EndFramePre); + ErrorCheckEndFrameSanityChecks(); // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) @@ -4268,6 +4281,8 @@ void ImGui::EndFrame() g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f; g.IO.InputQueueCharacters.resize(0); memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs)); + + CallContextHooks(&g, ImGuiContextHookType_EndFramePost); } void ImGui::Render() @@ -4281,6 +4296,8 @@ void ImGui::Render() g.IO.MetricsRenderWindows = 0; g.DrawDataBuilder.Clear(); + CallContextHooks(&g, ImGuiContextHookType_RenderPre); + // Add background ImDrawList if (!g.BackgroundDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList); @@ -4318,6 +4335,8 @@ void ImGui::Render() if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) g.IO.RenderDrawListsFn(&g.DrawData); #endif + + CallContextHooks(&g, ImGuiContextHookType_RenderPost); } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. diff --git a/imgui.h b/imgui.h index 798ae065..71986e8c 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.79" -#define IMGUI_VERSION_NUM 17900 +#define IMGUI_VERSION_NUM 17901 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_internal.h b/imgui_internal.h index 470bf4e9..5139d1f8 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -19,16 +19,17 @@ Index of this file: // [SECTION] ImDrawList support // [SECTION] Widgets support: flags, enums, data structures // [SECTION] Columns support -// [SECTION] Settings support // [SECTION] Multi-select support // [SECTION] Docking support // [SECTION] Viewport support +// [SECTION] Settings support +// [SECTION] Generic context hooks // [SECTION] ImGuiContext (main imgui context) // [SECTION] ImGuiWindowTempData, ImGuiWindow // [SECTION] Tab bar, Tab item support // [SECTION] Table support // [SECTION] Internal API -// [SECTION] Test Engine Hooks (imgui_test_engine) +// [SECTION] Test Engine specific hooks (imgui_test_engine) */ @@ -93,6 +94,7 @@ struct ImGuiColorMod; // Stacked color modifier, backup of modifie struct ImGuiColumnData; // Storage data for a single column struct ImGuiColumns; // Storage data for a columns set struct ImGuiContext; // Main Dear ImGui context +struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box @@ -1099,6 +1101,23 @@ struct ImGuiSettingsHandler ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } }; +//----------------------------------------------------------------------------- +// [SECTION] Generic context hooks +//----------------------------------------------------------------------------- + +typedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook); +enum ImGuiContextHookType { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown }; + +struct ImGuiContextHook +{ + ImGuiContextHookType Type; + ImGuiID Owner; + ImGuiContextHookCallback Callback; + void* UserData; + + ImGuiContextHook() { memset(this, 0, sizeof(*this)); } +}; + //----------------------------------------------------------------------------- // [SECTION] ImGuiContext (main imgui context) //----------------------------------------------------------------------------- @@ -1301,6 +1320,7 @@ struct ImGuiContext ImGuiTextBuffer SettingsIniData; // In memory .ini settings ImVector SettingsHandlers; // List of .ini settings handlers ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries + ImVector Hooks; // Hooks for extensions (e.g. test engine) // Capture/Logging bool LogEnabled; // Currently capturing @@ -1819,6 +1839,10 @@ namespace ImGui IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); + // Generic context hooks + IMGUI_API void AddContextHook(ImGuiContext* context, const ImGuiContextHook* hook); + IMGUI_API void CallContextHooks(ImGuiContext* context, ImGuiContextHookType type); + // Settings IMGUI_API void MarkIniSettingsDirty(); IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); @@ -2055,13 +2079,10 @@ IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned cha IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); //----------------------------------------------------------------------------- -// [SECTION] Test Engine Hooks (imgui_test_engine) +// [SECTION] Test Engine specific hooks (imgui_test_engine) //----------------------------------------------------------------------------- #ifdef IMGUI_ENABLE_TEST_ENGINE -extern void ImGuiTestEngineHook_Shutdown(ImGuiContext* ctx); -extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx); -extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx); extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id); extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id); @@ -2080,6 +2101,8 @@ extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const cha #define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) do { } while (0) #endif +//----------------------------------------------------------------------------- + #if defined(__clang__) #pragma clang diagnostic pop #elif defined(__GNUC__) From 04de5ef819d8371ddf5ce25ecd1c73db15817316 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 13:02:38 +0200 Subject: [PATCH 306/959] Version 1.80 WIP --- docs/CHANGELOG.txt | 10 ++++++++++ examples/README.txt | 2 +- imgui.cpp | 2 +- imgui.h | 6 +++--- imgui_demo.cpp | 2 +- imgui_draw.cpp | 2 +- imgui_internal.h | 2 +- imgui_widgets.cpp | 2 +- 8 files changed, 19 insertions(+), 9 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 729f0b88..48f4ec32 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -31,6 +31,16 @@ HOW TO UPDATE? - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.80 (In Progress) +----------------------------------------------------------------------- + +Breaking Changes: + + +Other Changes: + + ----------------------------------------------------------------------- VERSION 1.79 (Released 2020-10-08) ----------------------------------------------------------------------- diff --git a/examples/README.txt b/examples/README.txt index 68b6c104..69a5c86f 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,5 +1,5 @@ ----------------------------------------------------------------------- - dear imgui, v1.79 + dear imgui, v1.80 WIP ----------------------------------------------------------------------- examples/README.txt (This is the README file for the examples/ folder. See docs/ for more documentation) diff --git a/imgui.cpp b/imgui.cpp index 8b7cbd17..f4fdfded 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 +// dear imgui, v1.80 WIP // (main code and documentation) // Help: diff --git a/imgui.h b/imgui.h index 71986e8c..52611d14 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.79 +// dear imgui, v1.80 WIP // (headers) // Help: @@ -59,8 +59,8 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) -#define IMGUI_VERSION "1.79" -#define IMGUI_VERSION_NUM 17901 +#define IMGUI_VERSION "1.80 WIP" +#define IMGUI_VERSION_NUM 17902 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 60be4b2f..6285cdd6 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 +// dear imgui, v1.80 WIP // (demo code) // Help: diff --git a/imgui_draw.cpp b/imgui_draw.cpp index c491cd25..8ce1739f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 +// dear imgui, v1.80 WIP // (drawing and font code) /* diff --git a/imgui_internal.h b/imgui_internal.h index 5139d1f8..e74d2a80 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.79 +// dear imgui, v1.80 WIP // (internal structures/api) // You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fe5d2ba3..a3c5aff3 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.79 +// dear imgui, v1.80 WIP // (widgets code) /* From 0f13fdd1778134a8e87edd27ccd73ef6ee416cd8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 13:13:09 +0200 Subject: [PATCH 307/959] Removed redirecting functions/enums names that were marked obsolete in 1.60: io.RenderDrawListsFn, IsAnyWindowFocused(), IsAnyWindowHovered(), etc. --- docs/CHANGELOG.txt | 10 ++++++++++ examples/imgui_impl_allegro5.cpp | 1 - examples/imgui_impl_dx10.cpp | 1 - examples/imgui_impl_dx11.cpp | 1 - examples/imgui_impl_dx12.cpp | 1 - examples/imgui_impl_dx9.cpp | 1 - examples/imgui_impl_marmalade.cpp | 1 - examples/imgui_impl_opengl2.cpp | 4 ++-- examples/imgui_impl_opengl3.cpp | 4 ++-- examples/imgui_impl_vulkan.cpp | 1 - imgui.cpp | 18 +++++++----------- imgui.h | 28 ++-------------------------- 12 files changed, 23 insertions(+), 48 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 48f4ec32..cd608c38 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,16 @@ HOW TO UPDATE? Breaking Changes: +- Removed redirecting functions/enums names that were marked obsolete in 1.60 (April 2017): + - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your back-end + - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) + - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT + - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT + If you were still using the old names, while you are cleaning up, considering enabling + IMGUI_DISABLE_OBSOLETE_FUNCTIONS in imconfig.h even temporarily to have a pass at finding + and removing up old API calls, if any remaining. + Other Changes: diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index ca2cfae4..9982f640 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -86,7 +86,6 @@ static void ImGui_ImplAllegro5_SetupRenderState(ImDrawData* draw_data) } // Render function. -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index beade17f..787afcfa 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -90,7 +90,6 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* } // Render function -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 0f4a8615..77d70957 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -94,7 +94,6 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC } // Render function -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index 8d3ee417..aa92b26c 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -128,7 +128,6 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic } // Render function -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx) { // Avoid rendering when minimized diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index b4c49cdc..c5bdec8a 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -102,7 +102,6 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) } // Render function. -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index 00626072..0f723e57 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -39,7 +39,6 @@ static bool g_osdKeyboardEnabled = false; static ImVec2 g_RenderScale = ImVec2(1.0f, 1.0f); // Render function. -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_Marmalade_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index b062697b..79aeadcd 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -113,8 +113,8 @@ static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_wid } // OpenGL2 Render function. -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) -// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. +// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. +// This is in order to be able to run within an OpenGL engine that doesn't do so. void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 8a1f5873..5349b02d 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -289,8 +289,8 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid } // OpenGL3 Render function. -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) -// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. +// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. +// This is in order to be able to run within an OpenGL engine that doesn't do so. void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index c3135605..6c585b8a 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -314,7 +314,6 @@ static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline } // Render function -// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) diff --git a/imgui.cpp b/imgui.cpp index f4fdfded..69c53aa1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -371,6 +371,12 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): + - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your back-end + - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) + - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT + - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently). - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. @@ -1038,10 +1044,6 @@ ImGuiIO::ImGuiIO() ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; ImeWindowHandle = NULL; -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - RenderDrawListsFn = NULL; -#endif - // Input (NB: we already have memset zero the entire structure!) MousePos = ImVec2(-FLT_MAX, -FLT_MAX); MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); @@ -3334,7 +3336,7 @@ ImGuiIO& ImGui::GetIO() return GImGui->IO; } -// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame() +// Pass this to your back-end rendering function! Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { ImGuiContext& g = *GImGui; @@ -4330,12 +4332,6 @@ void ImGui::Render() g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount; g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount; - // (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) - g.IO.RenderDrawListsFn(&g.DrawData); -#endif - CallContextHooks(&g, ImGuiContextHookType_RenderPost); } diff --git a/imgui.h b/imgui.h index 52611d14..6e1c02c3 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.80 WIP" -#define IMGUI_VERSION_NUM 17902 +#define IMGUI_VERSION_NUM 17903 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -251,7 +251,7 @@ namespace ImGui IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame! 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 get call GetDrawData() to obtain it and run your rendering function (up to v1.60, this used to call io.RenderDrawListsFn(). Nowadays, we allow and prefer calling your render function yourself.) + 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. // Demo, Debug, Information @@ -828,7 +828,6 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu() // [Obsolete] - //ImGuiWindowFlags_ShowBorders = 1 << 7, // --> Set style.FrameBorderSize=1.0f or style.WindowBorderSize=1.0f to enable borders around items or windows. //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by back-end (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) }; @@ -1193,7 +1192,6 @@ enum ImGuiCol_ // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiCol_ModalWindowDarkening = ImGuiCol_ModalWindowDimBg // [renamed in 1.63] - //, ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered// [unused since 1.60+] the close button now uses regular button colors. #endif }; @@ -1231,11 +1229,6 @@ enum ImGuiStyleVar_ ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_COUNT - - // Obsolete names (will be removed) -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT // [renamed in 1.60] -#endif }; // Flags for InvisibleButton() [extended in imgui_internal.h] @@ -1339,11 +1332,6 @@ enum ImGuiMouseCursor_ ImGuiMouseCursor_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. ImGuiMouseCursor_COUNT - - // Obsolete names (will be removed) -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - , ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT // [renamed in 1.60] -#endif }; // Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions @@ -1561,15 +1549,6 @@ struct ImGuiIO void (*ImeSetInputScreenPosFn)(int x, int y); void* ImeWindowHandle; // = NULL // (Windows) Set this to your HWND to get automatic IME cursor positioning. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // [OBSOLETE since 1.60+] Rendering function, will be automatically called in Render(). Please call your rendering function yourself now! - // You can obtain the ImDrawData* by calling ImGui::GetDrawData() after Render(). See example applications if you are unsure of how to implement this. - void (*RenderDrawListsFn)(ImDrawData* data); -#else - // This is only here to keep ImGuiIO the same size/layout, so that IMGUI_DISABLE_OBSOLETE_FUNCTIONS can exceptionally be used outside of imconfig.h. - void* RenderDrawListsFnUnused; -#endif - //------------------------------------------------------------------ // Input - Fill before calling NewFrame() //------------------------------------------------------------------ @@ -1758,9 +1737,6 @@ namespace ImGui IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags = 0); IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags = 0); IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags = 0); - // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) - static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } - static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } } typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; From 041ef01b33f5aa2e40fb466682eb9c5df0d8512d Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 15:08:43 +0200 Subject: [PATCH 308/959] Removed redirecting functions/enums names that were marked obsolete in 1.61: InputFloat, InputFloat2, InputFloat3, InputFloat4 with int decimal_precision parameter. (#648, #712) --- docs/CHANGELOG.txt | 15 +++++++++------ imgui.cpp | 3 +++ imgui.h | 7 +------ imgui_widgets.cpp | 35 ----------------------------------- 4 files changed, 13 insertions(+), 47 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cd608c38..4de27509 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -38,12 +38,15 @@ HOW TO UPDATE? Breaking Changes: - Removed redirecting functions/enums names that were marked obsolete in 1.60 (April 2017): - - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your back-end - - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) - - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) - - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT - - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT - If you were still using the old names, while you are cleaning up, considering enabling + - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your back-end + - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) + - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) + - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT + - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT +- Removed redirecting functions/enums names that were marked obsolete in 1.61 (May 2018): + - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X was value for decimal_precision. + - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter. +- If you were still using the old names, while you are cleaning up, considering enabling IMGUI_DISABLE_OBSOLETE_FUNCTIONS in imconfig.h even temporarily to have a pass at finding and removing up old API calls, if any remaining. diff --git a/imgui.cpp b/imgui.cpp index 69c53aa1..3cd37c44 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -377,6 +377,9 @@ CODE - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT + - removed redirecting functions names that were marked obsolete in 1.61 (May 2018): + - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision. + - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter. - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently). - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. diff --git a/imgui.h b/imgui.h index 6e1c02c3..e9dcf847 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.80 WIP" -#define IMGUI_VERSION_NUM 17903 +#define IMGUI_VERSION_NUM 17904 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -1732,11 +1732,6 @@ namespace ImGui static inline void SetScrollHere(float center_ratio=0.5f){ SetScrollHereY(center_ratio); } // OBSOLETED in 1.63 (between Aug 2018 and Sept 2018) static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } - // OBSOLETED in 1.61 (between Apr 2018 and Aug 2018) - IMGUI_API bool InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags = 0); // Use the 'const char* format' version instead of 'decimal_precision'! - IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags = 0); - IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags = 0); } typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a3c5aff3..d657028e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3363,41 +3363,6 @@ bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGui return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags); } -// Prefer using "const char* format" directly, which is more flexible and consistent with other API. -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags) -{ - char format[16] = "%f"; - if (decimal_precision >= 0) - ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); - return InputFloat(label, v, step, step_fast, format, flags); -} - -bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags) -{ - char format[16] = "%f"; - if (decimal_precision >= 0) - ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); - return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags); -} - -bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags) -{ - char format[16] = "%f"; - if (decimal_precision >= 0) - ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); - return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags); -} - -bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags) -{ - char format[16] = "%f"; - if (decimal_precision >= 0) - ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); - return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags); -} -#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS - bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags) { // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. From 124c2608f1bf708b3abf039c93d16d704f76a815 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 17:34:22 +0200 Subject: [PATCH 309/959] Docs: Renamed all occurences of "binding" and "back-end" to "backend" in comments and documentations, for consistency. --- docs/CHANGELOG.txt | 74 ++++++++++--------- docs/FAQ.md | 18 ++--- docs/FONTS.md | 2 +- docs/README.md | 8 +- docs/TODO.txt | 4 +- examples/README.txt | 50 ++++++------- examples/example_allegro5/README.md | 2 +- examples/example_allegro5/main.cpp | 2 +- .../example_apple_metal/Shared/Renderer.mm | 2 +- examples/example_apple_opengl2/main.mm | 4 +- examples/example_emscripten/README.md | 2 +- examples/example_emscripten/main.cpp | 2 +- examples/example_glfw_metal/main.mm | 3 +- examples/example_glfw_opengl2/main.cpp | 2 +- examples/example_glfw_opengl3/main.cpp | 2 +- examples/example_glfw_vulkan/main.cpp | 6 +- examples/example_glut_opengl2/main.cpp | 2 +- examples/example_marmalade/main.cpp | 2 +- .../example_marmalade/marmalade_example.mkb | 2 +- examples/example_null/Makefile | 2 +- examples/example_sdl_directx11/main.cpp | 2 +- examples/example_sdl_metal/main.mm | 3 +- examples/example_sdl_opengl2/main.cpp | 2 +- examples/example_sdl_opengl3/main.cpp | 2 +- examples/example_sdl_vulkan/main.cpp | 6 +- examples/example_win32_directx10/main.cpp | 2 +- examples/example_win32_directx11/main.cpp | 2 +- .../example_win32_directx12/build_win32.bat | 2 +- examples/example_win32_directx12/main.cpp | 2 +- examples/example_win32_directx9/main.cpp | 2 +- examples/imgui_impl_allegro5.cpp | 4 +- examples/imgui_impl_allegro5.h | 2 +- examples/imgui_impl_dx10.cpp | 10 +-- examples/imgui_impl_dx10.h | 6 +- examples/imgui_impl_dx11.cpp | 6 +- examples/imgui_impl_dx11.h | 4 +- examples/imgui_impl_dx12.cpp | 8 +- examples/imgui_impl_dx12.h | 6 +- examples/imgui_impl_dx9.cpp | 6 +- examples/imgui_impl_dx9.h | 4 +- examples/imgui_impl_glfw.cpp | 6 +- examples/imgui_impl_glfw.h | 2 +- examples/imgui_impl_glut.cpp | 2 +- examples/imgui_impl_glut.h | 2 +- examples/imgui_impl_marmalade.cpp | 2 +- examples/imgui_impl_marmalade.h | 2 +- examples/imgui_impl_metal.h | 4 +- examples/imgui_impl_metal.mm | 4 +- examples/imgui_impl_opengl2.cpp | 6 +- examples/imgui_impl_opengl2.h | 4 +- examples/imgui_impl_opengl3.cpp | 6 +- examples/imgui_impl_opengl3.h | 4 +- examples/imgui_impl_osx.h | 6 +- examples/imgui_impl_osx.mm | 8 +- examples/imgui_impl_sdl.cpp | 6 +- examples/imgui_impl_sdl.h | 2 +- examples/imgui_impl_vulkan.cpp | 16 ++-- examples/imgui_impl_vulkan.h | 12 +-- examples/imgui_impl_win32.cpp | 10 +-- examples/imgui_impl_win32.h | 2 +- imconfig.h | 4 +- imgui.cpp | 58 +++++++-------- imgui.h | 68 ++++++++--------- imgui_demo.cpp | 16 ++-- imgui_widgets.cpp | 2 +- 65 files changed, 265 insertions(+), 261 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4de27509..9af626e4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -3,7 +3,7 @@ CHANGELOG This document holds the user-facing changelog that we also use in release notes. We generally fold multiple commits pertaining to the same topic as a single entry. -Changes to the examples/bindings are included within the individual .cpp files in the examples/ folder. +Changes to backends are also included within the individual .cpp files of each backend. RELEASE NOTES: https://github.com/ocornut/imgui/releases REPORT ISSUES, ASK QUESTIONS: https://github.com/ocornut/imgui/issues @@ -38,7 +38,7 @@ HOW TO UPDATE? Breaking Changes: - Removed redirecting functions/enums names that were marked obsolete in 1.60 (April 2017): - - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your back-end + - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT @@ -53,6 +53,8 @@ Breaking Changes: Other Changes: +- Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. + ----------------------------------------------------------------------- VERSION 1.79 (Released 2020-10-08) @@ -719,7 +721,7 @@ Other Changes: - Style: Attenuated default opacity of ImGuiCol_Separator in Classic and Light styles. - Style: Added style.ColorButtonPosition (left/right, defaults to ImGuiDir_Right) to move the color button of ColorEdit3/ColorEdit4 functions to either side of the inputs. -- IO: Added ImGuiKey_KeyPadEnter and support in various back-ends (previously back-ends would need to +- IO: Added ImGuiKey_KeyPadEnter and support in various backends (previously backends would need to specifically redirect key-pad keys to their regular counterpart). This is a temporary attenuating measure until we actually refactor and add whole sets of keys into the ImGuiKey enum. (#2677, #2005) [@amc522] - Misc: Made Button(), ColorButton() not trigger an "edited" event leading to IsItemDeactivatedAfterEdit() @@ -743,7 +745,7 @@ Other Changes: - Backends: OSX: Disabled default native Mac clipboard copy/paste implementation in core library (added in 1.71), because it needs application to be linked with '-framework ApplicationServices'. It can be explicitly enabled back by using '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h. Re-added - equivalent using NSPasteboard api in the imgui_impl_osx.mm experimental back-end. (#2546) + equivalent using NSPasteboard api in the imgui_impl_osx.mm experimental backend. (#2546) - Backends: SDL2: Added ImGui_ImplSDL2_InitForD3D() function to make D3D support more visible. (#2482, #2632) [@josiahmanson] - Examples: Added SDL2+DirectX11 example application. (#2632, #2612, #2482) [@vincenthamm] @@ -794,7 +796,7 @@ Other Changes: - Nav: Fixed gamepad/keyboard moving of window affecting contents size incorrectly, sometimes leading to scrollbars appearing during the movement. - Nav: Fixed rare crash when e.g. releasing Alt-key while focusing a window with a menu at the same - frame as clearing the focus. This was in most noticeable in back-ends such as Glfw and SDL which + frame as clearing the focus. This was in most noticeable in backends such as Glfw and SDL which emits key release events when focusing another viewport, leading to Alt+clicking on void on another viewport triggering the issue. (#2609) - TreeNode, CollapsingHeader: Fixed highlight frame not covering horizontal area fully when using @@ -810,14 +812,14 @@ Other Changes: - Style: Made window close button cross slightly smaller. - Log/Capture: Fixed BeginTabItem() label not being included in a text log/capture. - ImDrawList: Added ImDrawCmd::VtxOffset value to support large meshes (64k+ vertices) using 16-bit indices. - The renderer back-end needs to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' to enable + The renderer backend needs to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' to enable this, and honor the ImDrawCmd::VtxOffset field. Otherwise the value will always be zero. (#2591) This has the advantage of preserving smaller index buffers and allowing to execute on hardware that do not - support 32-bit indices. Most examples back-ends have been modified to support the VtxOffset field. + support 32-bit indices. Most examples backends have been modified to support the VtxOffset field. - ImDrawList: Added ImDrawCmd::IdxOffset value, equivalent to summing element count for each draw command. This is provided for convenience and consistency with VtxOffset. (#2591) - ImDrawCallback: Allow to override the signature of ImDrawCallback by #define-ing it. This is meant to - facilitate custom rendering back-ends passing local render-specific data to the draw callback. + facilitate custom rendering backends passing local render-specific data to the draw callback. - ImFontAtlas: FreeType: Added RasterizerFlags::Monochrome flag to disable font anti-aliasing. Combine with RasterizerFlags::MonoHinting for best results. (#2545) [@HolyBlackCat] - ImFontGlyphRangesBuilder: Fixed unnecessarily over-sized buffer, which incidentally was also not @@ -827,7 +829,7 @@ Other Changes: dealing with Win32, and to facilitate integration in custom engines. (#2546) [@andrewwillmott] - Backends: OSX: imgui_impl_osx: Added mouse cursor support. (#2585, #1873) [@actboy168] - Examples/Backends: DirectX9/10/11/12, Metal, Vulkan, OpenGL3 (Desktop GL only): Added support for large meshes - (64k+ vertices) with 16-bit indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those back-ends. (#2591) + (64k+ vertices) with 16-bit indices, enable 'ImGuiBackendFlags_RendererHasVtxOffset' in those backends. (#2591) - Examples/Backends: Don't filter characters under 0x10000 before calling io.AddInputCharacter(), the filtering is done in io.AddInputCharacter() itself. This is in prevision for fuller Unicode support. (#2538, #2541) @@ -855,15 +857,15 @@ Breaking Changes: Other Changes: - ImDrawList: Added ImDrawCallback_ResetRenderState, a special ImDrawList::AddCallback() value - to request the renderer back-end to reset its render state. (#2037, #1639, #2452) - Examples: Added support for ImDrawCallback_ResetRenderState in all renderer back-ends. Each + to request the renderer backend to reset its render state. (#2037, #1639, #2452) + Examples: Added support for ImDrawCallback_ResetRenderState in all renderer backends. Each renderer code setting up initial render state has been moved to a function so it could be called at the start of rendering and when a ResetRenderState is requested. [@ocornut, @bear24rw] - InputText: Fixed selection background rendering one frame after the cursor movement when first transitioning from no-selection to has-selection. (Bug in 1.69) (#2436) [@Nazg-Gul] - InputText: Work-around for buggy standard libraries where isprint('\t') returns true. (#2467, #1336) - InputText: Fixed ImGuiInputTextFlags_AllowTabInput leading to two tabs characters being inserted - if the back-end provided both Key and Character input. (#2467, #1336) + if the backend provided both Key and Character input. (#2467, #1336) - Layout: Added SetNextItemWidth() helper to avoid using PushItemWidth/PopItemWidth() for single items. Note that SetNextItemWidth() currently only affect the same subset of items as PushItemWidth(), generally referred to as the large framed+labeled items. Because the new SetNextItemWidth() @@ -1020,7 +1022,7 @@ Other Changes: - ImDrawData: Added FramebufferScale field (currently a copy of the value from io.DisplayFramebufferScale). This is to allow render functions being written without pulling any data from ImGuiIO, allowing incoming multi-viewport feature to behave on Retina display and with multiple displays. - If you are not using a custom binding, please update your render function code ahead of time, + If you are not using a custom backend, please update your render function code ahead of time, and use draw_data->FramebufferScale instead of io.DisplayFramebufferScale. (#2306, #1676) - Added IsItemActivated() as an extension to the IsItemDeactivated/IsItemDeactivatedAfterEdit functions which are useful to implement variety of undo patterns. (#820, #956, #1875) @@ -1103,7 +1105,7 @@ Other Changes: - Window: Contents size is preserved while a window collapsed. Fix auto-resizing window losing their size for one frame when uncollapsed. - Window: Contents size is preserved while a window contents is hidden (unless it is hidden for resizing purpose). - Window: Resizing windows from edge is now enabled by default (io.ConfigWindowsResizeFromEdges=true). Note that - it only works _if_ the back-end sets ImGuiBackendFlags_HasMouseCursors, which the standard back-ends do. + it only works _if_ the backend sets ImGuiBackendFlags_HasMouseCursors, which the standard backends do. - Window: Added io.ConfigWindowsMoveFromTitleBarOnly option. This is ignored by window with no title bars (often popups). This affects clamping window within the visible area: with this option enabled title bars need to be visible. (#899) - Window: Fixed using SetNextWindowPos() on a child window (which wasn't really documented) position the cursor as expected @@ -1125,7 +1127,7 @@ Other Changes: - ImFontAtlas: FreeType: Fixed support for any values of TexGlyphPadding (not just only 1). - ImDrawList: Optimized some of the functions for performance of debug builds where non-inline function call cost are non-negligible. (Our test UI scene on VS2015 Debug Win64 with /RTC1 went ~5.9 ms -> ~4.9 ms. In Release same scene stays at ~0.3 ms.) -- IO: Added BackendPlatformUserData, BackendRendererUserData, BackendLanguageUserData void* for storage use by back-ends. +- IO: Added BackendPlatformUserData, BackendRendererUserData, BackendLanguageUserData void* for storage use by backends. - IO: Renamed InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - IO: AddInputCharacter() goes into a queue which can receive as many characters as needed during the frame. This is useful for automation to not have an upper limit on typing speed. Will later transition key/mouse to use the event queue later. @@ -1152,7 +1154,7 @@ Other Changes: - Demo: Added ShowAboutWindow() call, previously was only accessible from the demo window. - Demo: ShowAboutWindow() now display various Build/Config Information (compiler, os, etc.) that can easily be copied into bug reports. - Fixed build issue with osxcross and macOS. (#2218) [@dos1] -- Examples: Setting up 'io.BackendPlatformName'/'io.BackendRendererName' fields to the current back-end can be displayed in the About window. +- Examples: Setting up 'io.BackendPlatformName'/'io.BackendRendererName' fields to the current backend can be displayed in the About window. - Examples: SDL: changed the signature of ImGui_ImplSDL2_ProcessEvent() to use a const SDL_Event*. (#2187) @@ -1380,23 +1382,23 @@ Breaking Changes: Other Changes: -- Examples back-ends have been refactored to separate the platform code (e.g. Win32, Glfw, SDL2) from the renderer code (e.g. DirectX11, OpenGL3, Vulkan). - The "Platform" bindings are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, etc. - The "Renderer" bindings are in charge of: creating the main font texture, rendering imgui draw data. +- Examples backends have been refactored to separate the platform code (e.g. Win32, Glfw, SDL2) from the renderer code (e.g. DirectX11, OpenGL3, Vulkan). + The "Platform" backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, etc. + The "Renderer" backends are in charge of: creating the main font texture, rendering imgui draw data. before: imgui_impl_dx11.cpp --> after: imgui_impl_win32.cpp + imgui_impl_dx11.cpp before: imgui_impl_dx12.cpp --> after: imgui_impl_win32.cpp + imgui_impl_dx12.cpp before: imgui_impl_glfw_gl3.cpp --> after: imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp before: imgui_impl_glfw_vulkan.cpp --> after: imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp before: imgui_impl_sdl_gl3.cpp --> after: imgui_impl_sdl2.cpp + imgui_impl_opengl2.cpp before: imgui_impl_sdl_gl3.cpp --> after: imgui_impl_sdl2.cpp + imgui_impl_opengl3.cpp etc. - - The idea is what we can now easily combine and maintain back-ends and reduce code redundancy. Individual files are + - The idea is what we can now easily combine and maintain backends and reduce code redundancy. Individual files are smaller and more reusable. Integration of imgui into a new/custom engine may also be easier as there is less overlap between "windowing / inputs" and "rendering" code, so you may study or grab one half of the code and not the other. - This change was motivated by the fact that adding support for the upcoming multi-viewport feature requires more work - from the Platform and Renderer back-ends, and the amount of redundancy across files was becoming too difficult to - maintain. If you use default back-ends, you'll benefit from an easy update path to support multi-viewports later + from the Platform and Renderer backends, and the amount of redundancy across files was becoming too difficult to + maintain. If you use default backends, you'll benefit from an easy update path to support multi-viewports later (for future ImGui 1.7x). - - This is not strictly a breaking change if you keep your old bindings, but when you'll want to fully update your bindings, + - This is not strictly a breaking change if you keep your old backends, but when you'll want to fully update your backends, expect to have to reshuffle a few things. - Each example still has its own main.cpp which you may refer you to understand how to initialize and glue everything together. - Some frameworks (such as the Allegro, Marmalade) handle both the "platform" and "rendering" part, and your custom engine may as well. @@ -1423,20 +1425,20 @@ Other Changes: for icon fonts. (#1869) - ImFontAtlas: Added GetGlyphRangesChineseSimplifiedCommon() helper that returns a list of ~2500 most common Simplified Chinese characters. (#1859) [@JX-Master, @ocornut] -- Examples: OSX: Added imgui_impl_osx.mm binding to be used along with e.g. imgui_impl_opengl2.cpp. (#281, #1870) [@pagghiu, @itamago, @ocornut] +- Examples: OSX: Added imgui_impl_osx.mm backend to be used along with e.g. imgui_impl_opengl2.cpp. (#281, #1870) [@pagghiu, @itamago, @ocornut] - Examples: GLFW: Made it possible to Shutdown/Init the backend again (by reseting the time storage properly). (#1827) [@ice1000] - Examples: Win32: Fixed handling of mouse wheel messages to support sub-unit scrolling messages (typically sent by track-pads). (#1874) [@zx64] - Examples: SDL+Vulkan: Added SDL+Vulkan example. - Examples: Allegro5: Added support for ImGuiConfigFlags_NoMouseCursorChange flag. Added clipboard support. -- Examples: Allegro5: Unindexing buffers ourselves as Allegro indexed drawing primitives are buggy in the DirectX9 back-end +- Examples: Allegro5: Unindexing buffers ourselves as Allegro indexed drawing primitives are buggy in the DirectX9 backend (will be fixed in Allegro 5.2.5+). - Examples: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from ImGui_ImplDX12_NewFrame() to ImGui_ImplDX12_RenderDrawData() which makes a lots more sense. (#301) -- Examples: Vulkan: Reordered parameters ImGui_ImplVulkan_RenderDrawData() to be consistent with other bindings, +- Examples: Vulkan: Reordered parameters ImGui_ImplVulkan_RenderDrawData() to be consistent with other backends, a good occasion since we refactored the code. -- Examples: FreeGLUT: Added FreeGLUT bindings. Added FreeGLUT+OpenGL2 example. (#801) +- Examples: FreeGLUT: Added FreeGLUT backends. Added FreeGLUT+OpenGL2 example. (#801) - Examples: The functions in imgui_impl_xxx.cpp are prefixed with IMGUI_IMPL_API (which defaults to IMGUI_API) to facilitate some uses. (#1888) -- Examples: Fixed bindings to use ImGuiMouseCursor_COUNT instead of old name ImGuiMouseCursor_Count_ so they can compile +- Examples: Fixed backends to use ImGuiMouseCursor_COUNT instead of old name ImGuiMouseCursor_Count_ so they can compile with IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#1887) - Misc: Updated stb_textedit from 1.09 + patches to 1.12 + minor patches. - Internals: PushItemFlag() flags are inherited by BeginChild(). @@ -1512,9 +1514,9 @@ Other Changes: - Demo: Added demo for DragScalar(), InputScalar(), SliderScalar(). (#643) - Examples: Calling IMGUI_CHECKVERSION() in the main.cpp of every example application. - Examples: Allegro 5: Added support for 32-bit indices setup via defining ImDrawIdx, to avoid an unnecessary conversion (Allegro 5 doesn't support 16-bit indices). -- Examples: Allegro 5: Renamed bindings from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp. +- Examples: Allegro 5: Renamed backend from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp. - Examples: DirectX 9: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud. (#1790, #1687) [@sr-tream] -- Examples: SDL: Fixed clipboard paste memory leak in the SDL binding code. (#1803) [@eliasdaler] +- Examples: SDL: Fixed clipboard paste memory leak in the SDL backend code. (#1803) [@eliasdaler] - Various minor fixes, tweaks, refactoring, comments. @@ -1545,7 +1547,7 @@ Breaking Changes: - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment. - Obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete). - Obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete). -- Renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, not used by core, and honored by some binding ahead of merging the Nav branch). +- Renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, not used by core, and honored by some backend ahead of merging the Nav branch). - Removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered style colors as the closing cross uses regular button colors now. - Renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData. - Removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it should be easy to replicate on your side (you can find the code in 1.53). @@ -1587,9 +1589,9 @@ Other Changes: - ImGuiConfigFlags_NoMouse: Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information passed by the backend. - ImGuiConfigFlags_IsSRGB, ImGuiConfigFlags_IsTouchScreen: Flags for general application use. - IO: Added io.BackendFlags for backend to store its capabilities (currently: _HasGamepad, _HasMouseCursors, _HasSetMousePos). This will be used more in the next version. -- IO: Added ImGuiKey_Insert, ImGuiKey_Space keys. Setup in all example bindings. (#1541) +- IO: Added ImGuiKey_Insert, ImGuiKey_Space keys. Setup in all example backends. (#1541) - IO: Added Horizontal Mouse Wheel support for horizontal scrolling. (#1463) [@tseeker] -- IO: Added IsAnyMouseDown() helper which is helpful for bindings to handle mouse capturing. +- IO: Added IsAnyMouseDown() helper which is helpful for backends to handle mouse capturing. - Window: Clicking on a window with the ImGuiWIndowFlags_NoMove flags takes an ActiveId so we can't hover something else when dragging afterwards. (#1381, #1337) - Window: IsWindowHovered(): Added ImGuiHoveredFlags_AnyWindow, ImGuiFocusedFlags_AnyWindow flags (See Breaking Changes). Added to demo. (#1382) - Window: Added SetNextWindowBgAlpha() helper. Particularly helpful since the legacy 5-parameters version of Begin() has been marked as obsolete in 1.53. (#1567) @@ -1655,7 +1657,7 @@ Other Changes: - Demo: Tweaked the Child demos, added a menu bar to the second child to test some navigation functions. - Demo: Console: Using ImGuiCol_Text to be more friendly to color changes. - Demo: Using IM_COL32() instead of ImColor() in ImDrawList centric contexts. Trying to phase out use of the ImColor helper whenever possible. -- Examples: Files in examples/ now include their own changelog so it is easier to occasionally update your bindings if needed. +- Examples: Files in examples/ now include their own changelog so it is easier to occasionally update your backends if needed. - Examples: Using Dark theme by default. (#707). Tweaked demo code. - Examples: Added support for horizontal mouse wheel for API that allows it. (#1463) [@tseeker] - Examples: All examples now setup the io.BackendFlags to signify they can honor mouse cursors, gamepad, etc. @@ -1666,7 +1668,7 @@ Other Changes: - Examples: OpenGL3+GLFW,SDL: Creating VAO in the render function so it can be more easily used by multiple shared OpenGL contexts. (#1217) - Examples: OpenGL3+GLFW: Using 3.2 context instead of 3.3. (#1466) - Examples: OpenGL: Setting up glPixelStorei() explicitly before uploading texture. -- Examples: OpenGL: Calls to glPolygonMode() are casting parameters as GLEnum to not fail with more strict bindings. (#1628) [@ilia-glushchenko] +- Examples: OpenGL: Calls to glPolygonMode() are casting parameters as GLEnum to not fail with more strict backends. (#1628) [@ilia-glushchenko] - Examples: Win32 (DirectX9,10,11,12): Added support for mouse cursor shapes. (#1495) - Examples: Win32 (DirectX9,10,11,12: Support for windows using the CS_DBLCLKS class flag by handling the double-click messages (WM_LBUTTONDBLCLK etc.). (#1538, #754) [@ndandoulakis] - Examples: Win32 (DirectX9,10,11,12): Made the Win32 proc handlers not assert if there is no active context yet, to be more flexible with creation order. (#1565) @@ -2061,7 +2063,7 @@ Other Changes: - Context: Support for #define-ing GImGui and IMGUI_SET_CURRENT_CONTEXT_FUNC to enable custom thread-based hackery (#586) - Updated stb_truetype.h to 1.14 (added OTF support, removed warnings). (#883, #976) - Updated stb_rect_pack.h to 0.10 (removed warnings). (#883) -- Added ImGuiMouseCursor_None enum value for convenient usage by app/binding. +- Added ImGuiMouseCursor_None enum value for convenient usage by app/backends. - Clipboard: Added a void* user_data parameter to Clipboard function handlers. (#875) (BREAKING API) - Internals: Refactor internal text alignment options to use ImVec2, removed ImGuiAlign. (#842, #222) - Internals: Renamed ImLoadFileToMemory to ImFileLoadToMemory to be consistent with ImFileOpen + fix mismatching .h name. (#917) diff --git a/docs/FAQ.md b/docs/FAQ.md index acc99ede..20abe638 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -126,7 +126,7 @@ e.g. `if (ImGui::GetIO().WantCaptureMouse) { ... }` ### Q: How can I enable keyboard or gamepad controls? - The gamepad/keyboard navigation is fairly functional and keeps being improved. The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. Gamepad support is particularly useful to use Dear ImGui on a game console (e.g. PS4, Switch, XB1) without a mouse connected! - Keyboard: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard` to enable. -- Gamepad: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad` to enable (with a supporting back-end). +- Gamepad: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad` to enable (with a supporting backend). - See [Control Sheets for Gamepads](http://www.dearimgui.org/controls_sheets) (reference PNG/PSD for for PS4, XB1, Switch gamepads). - See `USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp) for more details. @@ -151,7 +151,7 @@ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-lik ### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. This usually means that: your font texture wasn't uploaded into GPU, or your shader or other rendering state are not reading from the right texture (e.g. texture wasn't bound). -If this happens using the standard back-ends it is probably that the texture failed to upload, which could happens if for some reason your texture is too big. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). +If this happens using the standard backends it is probably that the texture failed to upload, which could happens if for some reason your texture is too big. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). ##### [Return to Index](#index) @@ -165,7 +165,7 @@ Rectangles provided by Dear ImGui are defined as `(x1=left,y1=top,x2=right,y2=bottom)` and **NOT** as `(x1,y1,width,height)` -Refer to rendering back-ends in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder for references of how to handle the `ClipRect` field. +Refer to rendering backends in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder for references of how to handle the `ClipRect` field. ##### [Return to Index](#index) @@ -325,7 +325,7 @@ Long explanation: We carry the information to identify a "texture" in the ImTextureID type. ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice. Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function. -- In the [examples/](https://github.com/ocornut/imgui/tree/master/examples) bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: +- In the [examples/](https://github.com/ocornut/imgui/tree/master/examples) backends, for each graphics API we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: ``` OpenGL: - ImTextureID = GLuint @@ -346,11 +346,11 @@ DirectX12: - ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE - See ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp ``` -For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID. -Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure tying together both the texture and information about its format and how to read it. +For example, in the OpenGL example backend we store raw OpenGL texture identifier (GLuint) inside ImTextureID. +Whereas in the DirectX11 example backend we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure tying together both the texture and information about its format and how to read it. - If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them. -If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID representation suggested by the example bindings is probably the best choice. +If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID representation suggested by the example backends is probably the best choice. (Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer) User code may do: @@ -401,7 +401,7 @@ This way you'll be able to use your own types everywhere, e.g. passing `MyVector --- ### Q: How can I interact with standard C++ types (such as std::string and std::vector)? -- Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers), and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases. +- Being highly portable (backends/bindings for several languages, frameworks, programming style, obscure or older platforms/compilers), and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases. - To use ImGui::InputText() with a std::string or any resizable string class, see [misc/cpp/imgui_stdlib.h](https://github.com/ocornut/imgui/blob/master/misc/cpp/imgui_stdlib.h). - To use combo boxes and list boxes with `std::vector` or any other data structure: the `BeginCombo()/EndCombo()` API lets you iterate and submit items yourself, so does the `ListBoxHeader()/ListBoxFooter()` API. @@ -633,7 +633,7 @@ A reasonably skinned application may look like (screenshot from [#2529](https:// Dear ImGui takes advantage of a few C++ languages features for convenience but nothing anywhere Boost insanity/quagmire. Dear ImGui does NOT require C++11 so it can be used with most old C++ compilers. Dear ImGui doesn't use any C++ header file. Language-wise, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience. -There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/cimgui/cimgui) by Sonoro1234 and Stephan Dilly. It is designed for creating binding to other languages. If possible, I would suggest using your target language functionalities to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. Also see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings) for various third-party bindings. +There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/cimgui/cimgui) by Sonoro1234 and Stephan Dilly. It is designed for creating bindings to other languages. If possible, I would suggest using your target language functionalities to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. Also see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings) for various third-party bindings. ##### [Return to Index](#index) diff --git a/docs/FONTS.md b/docs/FONTS.md index c2312fd5..7ce5a88c 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -226,7 +226,7 @@ io.Fonts->Build(); // Build the atlas while ## Using Custom Colorful Icons -**(This is a BETA api, use if you are familiar with dear imgui and with your rendering back-end)** +**(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)** - You can use the `ImFontAtlas::AddCustomRect()` and `ImFontAtlas::AddCustomRectFontGlyph()` api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`. - You can then use `ImFontAtlas::GetCustomRectByIndex(int)` to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles. diff --git a/docs/README.md b/docs/README.md index 476540de..e60e4311 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,7 +23,7 @@ Dear ImGui is particularly suited to integration in games engine (for tooling), | [Usage](#usage) - [How it works](#how-it-works) - [Releases](#releases) - [Demo](#demo) - [Integration](#integration) | :----------------------------------------------------------: | | [Upcoming changes](#upcoming-changes) - [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - [Sponsors](#sponsors) - [Credits](#credits) - [License](#license) | -| [Wiki](https://github.com/ocornut/imgui/wiki) - [Language & frameworks bindings](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | +| [Wiki](https://github.com/ocornut/imgui/wiki) - [Languages & frameworks backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | ### Usage @@ -110,16 +110,16 @@ The demo applications are not DPI aware so expect some blurriness on a 4K screen ### Integration -On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/examples) files without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more of the imgui_impl_xxxx files instead of rewriting them: this will be less work for you and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom binding using your custom engine functions if you wish so. +On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/examples) files without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more of the imgui_impl_xxxx files instead of rewriting them: this will be less work for you and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading one texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that. If you are an experienced programmer at ease with those concepts, it should take you less than two hours to integrate Dear ImGui in your custom engine. **Make sure to spend time reading the [FAQ](https://www.dearimgui.org/faq), comments, and some of the examples/ application!** -Officially maintained bindings (in repository): +Officially maintained backends/bindings (in repository): - Renderers: DirectX9, DirectX10, DirectX11, DirectX12, OpenGL (legacy), OpenGL3/ES/ES2 (modern), Vulkan, Metal. - Platforms: GLFW, SDL2, Win32, Glut, OSX. - Frameworks: Emscripten, Allegro5, Marmalade. -Third-party bindings (see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings/) page): +Third-party backends/bindings (see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings/) page): - Languages: C, C# and: Beef, ChaiScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... - Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, nCine, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. - Note that C bindings ([cimgui](https://github.com/cimgui/cimgui)) are auto-generated, you can use its json/lua output to generate bindings for other languages. diff --git a/docs/TODO.txt b/docs/TODO.txt index 9f99871f..8473d720 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -6,7 +6,7 @@ The list below consist mostly of ideas noted down before they are requested/disc It's mostly a bunch of personal notes, probably incomplete. Feel free to query if you have any questions. - doc/test: add a proper documentation+regression testing system (#435) - - doc/test: checklist app to verify binding/integration of imgui (test inputs, rendering, callback, etc.). + - doc/test: checklist app to verify backends/integration of imgui (test inputs, rendering, callback, etc.). - doc/tips: tips of the day: website? applet in imgui_club? - doc/wiki: work on the wiki https://github.com/ocornut/imgui/wiki @@ -370,7 +370,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - inputs/io: clarify/standardize/expose repeat rate and repeat delays (#1808) - inputs/scrolling: support for smooth scrolling (#2462, #2569) - - misc: idle: expose "woken up" boolean (set by inputs) and/or animation time (for cursor blink) for back-end to be able stop refreshing easily. + - misc: idle: expose "woken up" boolean (set by inputs) and/or animation time (for cursor blink) for backend to be able stop refreshing easily. - misc: idle: if cursor blink if the _only_ visible animation, core imgui could rewrite vertex alpha to avoid CPU pass on ImGui:: calls. - misc: idle: if cursor blink if the _only_ visible animation, could even expose a dirty rectangle that optionally can be leverage by some app to render in a smaller viewport, getting rid of much pixel shading cost. - misc: no way to run a root-most GetID() with ImGui:: api since there's always a Debug window in the stack. (mentioned in #2960) diff --git a/examples/README.txt b/examples/README.txt index 69a5c86f..71700d8f 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -12,19 +12,19 @@ Dear ImGui is highly portable and only requires a few things to run and render: - Providing a render function to render indexed textured triangles - Optional: clipboard support, mouse cursor supports, Windows IME support, etc. -This is essentially what the example bindings in this folder are providing + obligatory portability cruft. +This is essentially what the example backends in this folder are providing + obligatory portability cruft. It is important to understand the difference between the core Dear ImGui library (files in the root folder) -and examples bindings which we are describing here (examples/ folder). -You should be able to write bindings for pretty much any platform and any 3D graphics API. With some extra +and examples backends which we are describing here (examples/ folder). +You should be able to write backends for pretty much any platform and any 3D graphics API. With some extra effort you can even perform the rendering remotely, on a different machine than the one running the logic. This folder contains two things: - - Example bindings for popular platforms/graphics API, which you can use as is or adapt for your own use. + - Example backends for popular platforms/graphics API, which you can use as is or adapt for your own use. They are the imgui_impl_XXXX files found in the examples/ folder. - - Example applications (standalone, ready-to-build) using the aforementioned bindings. + - Example applications (standalone, ready-to-build) using the aforementioned backends. They are the in the XXXX_example/ sub-folders. You can find binaries of some of those example applications at: @@ -63,25 +63,25 @@ You can find binaries of some of those example applications at: --------------------------------------- - EXAMPLE BINDINGS + EXAMPLE BACKENDS --------------------------------------- -Most the example bindings are split in 2 parts: +Most the example backends are split in 2 parts: - - The "Platform" bindings, in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing. + - The "Platform" backends, in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing. Examples: Windows (imgui_impl_win32.cpp), GLFW (imgui_impl_glfw.cpp), SDL2 (imgui_impl_sdl.cpp), etc. - - The "Renderer" bindings, in charge of: creating the main font texture, rendering imgui draw data. + - The "Renderer" backends, in charge of: creating the main font texture, rendering imgui draw data. Examples: DirectX11 (imgui_impl_dx11.cpp), GL3 (imgui_impl_opengl3.cpp), Vulkan (imgui_impl_vulkan.cpp), etc. - - The example _applications_ usually combine 1 platform + 1 renderer binding to create a working program. + - The example _applications_ usually combine 1 platform + 1 renderer backend to create a working program. Examples: the example_win32_directx11/ application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. - - Some bindings for higher level frameworks carry both "Platform" and "Renderer" parts in one file. + - Some backends for higher level frameworks carry both "Platform" and "Renderer" parts in one file. This is the case for Allegro 5 (imgui_impl_allegro5.cpp), Marmalade (imgui_impl_marmalade5.cpp). - - If you use your own engine, you may decide to use some of existing bindings and/or rewrite some using - your own API. As a recommendation, if you are new to Dear ImGui, try using the existing binding as-is + - If you use your own engine, you may decide to use some of existing backends and/or rewrite some using + your own API. As a recommendation, if you are new to Dear ImGui, try using the existing backend as-is first, before moving on to rewrite some of the code. Although it is tempting to rewrite both of the imgui_impl_xxxx files to fit under your coding style, consider that it is not necessary! In fact, if you are new to Dear ImGui, rewriting them will almost always be harder. @@ -91,29 +91,29 @@ Most the example bindings are split in 2 parts: Suggestion: step 1: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. Once this work, _if_ you want you can replace the imgui_impl_dx11.cpp code with a custom renderer using your own functions, etc. - Please consider using the bindings to the lower-level platform/graphics API as-is. + Please consider using the backends to the lower-level platform/graphics API as-is. Example: your engine is multi-platform (consoles, phones, etc.), you have high-level systems everywhere. - Suggestion: step 1: try using a non-portable binding first (e.g. win32 + underlying graphics API)! + Suggestion: step 1: try using a non-portable backend first (e.g. win32 + underlying graphics API)! This is counter-intuitive, but this will get you running faster! Once you better understand how imgui works and is bound, you can rewrite the code using your own systems. - Road-map: Dear ImGui 1.80 (WIP currently in the "docking" branch) will allows imgui windows to be seamlessly detached from the main application window. This is achieved using an extra layer to the - platform and renderer bindings, which allows Dear ImGui to communicate platform-specific requests. + platform and renderer backends, which allows Dear ImGui to communicate platform-specific requests. If you decide to use unmodified imgui_impl_xxxx.cpp files, you will automatically benefit from improvements and fixes related to viewports and platform windows without extra work on your side. -List of Platforms Bindings in this repository: +List of Platforms Backends in this repository: imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ - imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl back-ends) + imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org imgui_impl_win32.cpp ; Win32 native API (Windows) imgui_impl_glut.cpp ; GLUT/FreeGLUT (absolutely not recommended in 2020!) -List of Renderer Bindings in this repository: +List of Renderer Backends in this repository: imgui_impl_dx9.cpp ; DirectX9 imgui_impl_dx10.cpp ; DirectX10 @@ -124,7 +124,7 @@ List of Renderer Bindings in this repository: imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) imgui_impl_vulkan.cpp ; Vulkan -List of high-level Frameworks Bindings in this repository: (combine Platform + Renderer) +List of high-level Frameworks Backends in this repository: (combine Platform + Renderer) imgui_impl_allegro5.cpp imgui_impl_marmalade.cpp @@ -132,7 +132,7 @@ List of high-level Frameworks Bindings in this repository: (combine Platform + R Note that Dear ImGui works with Emscripten. The examples_emscripten/ app uses imgui_impl_sdl.cpp and imgui_impl_opengl3.cpp, but other combinations are possible. -Third-party framework, graphics API and languages bindings are listed at: +Third-party framework, graphics API and languages backends are listed at: https://github.com/ocornut/imgui/wiki/Bindings @@ -181,14 +181,14 @@ example_apple_metal/ OSX & iOS + Metal. = main.m + imgui_impl_osx.mm + imgui_impl_metal.mm It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. - (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms back-ends. - You may prefer to use the GLFW Or SDL back-ends, which will also support Windows and Linux.) + (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. + You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) example_apple_opengl2/ OSX + OpenGL2. = main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp - (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms back-ends. - You may prefer to use the GLFW Or SDL back-ends, which will also support Windows and Linux.) + (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. + You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) example_empscripten: Emcripten + SDL2 + OpenGL3+/ES2/ES3 example. diff --git a/examples/example_allegro5/README.md b/examples/example_allegro5/README.md index 10d9d6e9..74ba4cc7 100644 --- a/examples/example_allegro5/README.md +++ b/examples/example_allegro5/README.md @@ -5,7 +5,7 @@ Dear ImGui outputs 16-bit vertex indices by default. Allegro doesn't support them natively, so we have two solutions: convert the indices manually in imgui_impl_allegro5.cpp, or compile dear imgui with 32-bit indices. You can either modify imconfig.h that comes with Dear ImGui (easier), or set a C++ preprocessor option IMGUI_USER_CONFIG to find to a filename. We are providing `imconfig_allegro5.h` that enables 32-bit indices. -Note that the back-end supports _BOTH_ 16-bit and 32-bit indices, but 32-bit indices will be slightly faster as they won't require a manual conversion. +Note that the backend supports _BOTH_ 16-bit and 32-bit indices, but 32-bit indices will be slightly faster as they won't require a manual conversion. # How to Build diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index c32125b6..60ed680f 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -32,7 +32,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplAllegro5_Init(display); // Load Fonts diff --git a/examples/example_apple_metal/Shared/Renderer.mm b/examples/example_apple_metal/Shared/Renderer.mm index 3f7e32d1..c121f692 100644 --- a/examples/example_apple_metal/Shared/Renderer.mm +++ b/examples/example_apple_metal/Shared/Renderer.mm @@ -35,7 +35,7 @@ ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Renderer bindings + // Setup Renderer backend ImGui_ImplMetal_Init(_device); // Load Fonts diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 133f928a..c7ccc4ae 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -138,7 +138,7 @@ animationTimer = nil; } -// Forward Mouse/Keyboard events to dear imgui OSX back-end. It returns true when imgui is expecting to use the event. +// Forward Mouse/Keyboard events to dear imgui OSX backend. It returns true when imgui is expecting to use the event. -(void)keyUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } -(void)keyDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } -(void)flagsChanged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } @@ -254,7 +254,7 @@ ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplOSX_Init(); ImGui_ImplOpenGL2_Init(); diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten/README.md index 42bab014..01a4e35e 100644 --- a/examples/example_emscripten/README.md +++ b/examples/example_emscripten/README.md @@ -16,5 +16,5 @@ _"Unfortunately several browsers (including Chrome, Safari, and Internet Explore ## Obsolete features: -- Emscripten 2.0 (August 2020) obsoleted the fastcomp back-end, only llvm is supported. +- Emscripten 2.0 (August 2020) obsoleted the fastcomp backend, only llvm is supported. - Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: `#EMS += -s BINARYEN_TRAP_MODE=clamp` diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index 6867b4cd..facbf331 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -72,7 +72,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(g_Window, g_GLContext); ImGui_ImplOpenGL3_Init(glsl_version); diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index d6f9ae3f..1860d8bd 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -22,7 +22,7 @@ static void glfw_error_callback(int error, const char* description) int main(int, char**) { - // Setup Dear ImGui binding + // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; @@ -62,6 +62,7 @@ int main(int, char**) id device = MTLCreateSystemDefaultDevice();; id commandQueue = [device newCommandQueue]; + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplMetal_Init(device); diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 411062fa..2307e1c3 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -50,7 +50,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL2_Init(); diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index aa43471a..f773005f 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -114,7 +114,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(glsl_version); diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index 5e5f7323..ba2c9d6d 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -3,9 +3,9 @@ // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. -// You will use those if you want to use this rendering back-end in your engine/app. +// You will use those if you want to use this rendering backend in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by -// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. #include "imgui.h" @@ -381,7 +381,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForVulkan(window, true); ImGui_ImplVulkan_InitInfo init_info = {}; init_info.Instance = g_Instance; diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 997eeaef..0adc7ae7 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -115,7 +115,7 @@ int main(int argc, char** argv) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplGLUT_Init(); ImGui_ImplGLUT_InstallFuncs(); ImGui_ImplOpenGL2_Init(); diff --git a/examples/example_marmalade/main.cpp b/examples/example_marmalade/main.cpp index 9f2ef798..064e43ce 100644 --- a/examples/example_marmalade/main.cpp +++ b/examples/example_marmalade/main.cpp @@ -26,7 +26,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_Marmalade_Init(true); // Load Fonts diff --git a/examples/example_marmalade/marmalade_example.mkb b/examples/example_marmalade/marmalade_example.mkb index 34315b9a..4c94cc01 100644 --- a/examples/example_marmalade/marmalade_example.mkb +++ b/examples/example_marmalade/marmalade_example.mkb @@ -38,7 +38,7 @@ files ../../imgui.h ../../imgui_internal.h - ["imgui","Marmalade binding"] + ["imgui", "Marmalade backend"] ../imgui_impl_marmalade.h ../imgui_impl_marmalade.cpp main.cpp diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 15c547a5..d6a702ad 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -2,7 +2,7 @@ # Cross Platform Makefile # Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X # -# Important: This is a "null back-end" application, with no visible output or interaction! +# Important: This is a "null backend" application, with no visible output or interaction! # This is used for testing purpose and continuous integration, and has little use for end-user. # diff --git a/examples/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp index 61a93070..82e2206f 100644 --- a/examples/example_sdl_directx11/main.cpp +++ b/examples/example_sdl_directx11/main.cpp @@ -60,7 +60,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForD3D(window); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); diff --git a/examples/example_sdl_metal/main.mm b/examples/example_sdl_metal/main.mm index 3cb1ea4d..8184ddf3 100644 --- a/examples/example_sdl_metal/main.mm +++ b/examples/example_sdl_metal/main.mm @@ -13,7 +13,7 @@ int main(int, char**) { - // Setup Dear ImGui binding + // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; @@ -65,6 +65,7 @@ int main(int, char**) return -3; } + // Setup Platform/Renderer backends CAMetalLayer* layer = (__bridge CAMetalLayer*)SDL_RenderGetMetalLayer(renderer); layer.pixelFormat = MTLPixelFormatBGRA8Unorm; ImGui_ImplMetal_Init(layer.device); diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index 34ea80d0..8bfafb77 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -48,7 +48,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL2_Init(); diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index c61bc544..578c8c41 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -109,7 +109,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL3_Init(glsl_version); diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index c6ce12a1..e4625e3e 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -3,9 +3,9 @@ // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. -// You will use those if you want to use this rendering back-end in your engine/app. +// You will use those if you want to use this rendering backend in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by -// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. #include "imgui.h" @@ -373,7 +373,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForVulkan(window); ImGui_ImplVulkan_InitInfo init_info = {}; init_info.Instance = g_Instance; diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 2e83e826..2dbff10b 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -54,7 +54,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX10_Init(g_pd3dDevice); diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 310dc04a..808599bf 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -54,7 +54,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); diff --git a/examples/example_win32_directx12/build_win32.bat b/examples/example_win32_directx12/build_win32.bat index 85a52b70..097295a8 100644 --- a/examples/example_win32_directx12/build_win32.bat +++ b/examples/example_win32_directx12/build_win32.bat @@ -1,5 +1,5 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@REM Important: to build on 32-bit systems, the DX12 back-ends needs '#define ImTextureID ImU64', so we pass it here. +@REM Important: to build on 32-bit systems, the DX12 backends needs '#define ImTextureID ImU64', so we pass it here. mkdir Debug cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /D ImTextureID=ImU64 /D UNICODE /D _UNICODE *.cpp ..\imgui_impl_dx12.cpp ..\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx12.exe /FoDebug/ /link d3d12.lib d3dcompiler.lib dxgi.lib diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index a2cd494a..a2e83ec6 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -85,7 +85,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX12_Init(g_pd3dDevice, NUM_FRAMES_IN_FLIGHT, DXGI_FORMAT_R8G8B8A8_UNORM, g_pd3dSrvDescHeap, diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index 57a61c0d..a07011c0 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -52,7 +52,7 @@ int main(int, char**) ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); - // Setup Platform/Renderer bindings + // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX9_Init(g_pd3dDevice); diff --git a/examples/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp index 9982f640..61e9ad20 100644 --- a/examples/imgui_impl_allegro5.cpp +++ b/examples/imgui_impl_allegro5.cpp @@ -1,4 +1,4 @@ -// dear imgui: Renderer + Platform Binding for Allegro 5 +// dear imgui: Renderer + Platform Backend for Allegro 5 // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) // Implemented features: @@ -252,7 +252,7 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) { g_Display = display; - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendPlatformName = io.BackendRendererName = "imgui_impl_allegro5"; diff --git a/examples/imgui_impl_allegro5.h b/examples/imgui_impl_allegro5.h index f41e4c90..fe7eef23 100644 --- a/examples/imgui_impl_allegro5.h +++ b/examples/imgui_impl_allegro5.h @@ -1,4 +1,4 @@ -// dear imgui: Renderer + Platform Binding for Allegro 5 +// dear imgui: Renderer + Platform Backend for Allegro 5 // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) // Implemented features: diff --git a/examples/imgui_impl_dx10.cpp b/examples/imgui_impl_dx10.cpp index 787afcfa..d9fce2f1 100644 --- a/examples/imgui_impl_dx10.cpp +++ b/examples/imgui_impl_dx10.cpp @@ -1,8 +1,8 @@ -// dear imgui: Renderer for DirectX10 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX10 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture backend. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. @@ -19,7 +19,7 @@ // 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions. // 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the old combined DX10+Win32 example. // 2018-06-08: DirectX10: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. -// 2018-04-09: Misc: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) on other back-ends. +// 2018-04-09: Misc: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) on other backends. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2016-05-07: DirectX10: Disabling depth-write. @@ -497,7 +497,7 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() bool ImGui_ImplDX10_Init(ID3D10Device* device) { - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx10"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx10.h b/examples/imgui_impl_dx10.h index d974ba8e..89269166 100644 --- a/examples/imgui_impl_dx10.h +++ b/examples/imgui_impl_dx10.h @@ -1,8 +1,8 @@ -// dear imgui: Renderer for DirectX10 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX10 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: User texture backend. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. diff --git a/examples/imgui_impl_dx11.cpp b/examples/imgui_impl_dx11.cpp index 77d70957..efab4296 100644 --- a/examples/imgui_impl_dx11.cpp +++ b/examples/imgui_impl_dx11.cpp @@ -1,5 +1,5 @@ -// dear imgui: Renderer for DirectX11 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX11 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! @@ -509,7 +509,7 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) { - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx11"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx11.h b/examples/imgui_impl_dx11.h index cccadcd2..4fd2ceb0 100644 --- a/examples/imgui_impl_dx11.h +++ b/examples/imgui_impl_dx11.h @@ -1,5 +1,5 @@ -// dear imgui: Renderer for DirectX11 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX11 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! diff --git a/examples/imgui_impl_dx12.cpp b/examples/imgui_impl_dx12.cpp index aa92b26c..e1af860d 100644 --- a/examples/imgui_impl_dx12.cpp +++ b/examples/imgui_impl_dx12.cpp @@ -1,11 +1,11 @@ -// dear imgui: Renderer for DirectX12 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX12 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// Important: to compile on 32-bit systems, this back-end requires code to be compiled with '#define ImTextureID ImU64'. +// Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // This define is done in the example .vcxproj file and need to be replicated in your app (by e.g. editing imconfig.h) @@ -626,7 +626,7 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) { - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx12"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx12.h b/examples/imgui_impl_dx12.h index dd77ba8c..ec0b70ae 100644 --- a/examples/imgui_impl_dx12.h +++ b/examples/imgui_impl_dx12.h @@ -1,11 +1,11 @@ -// dear imgui: Renderer for DirectX12 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX12 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// Important: to compile on 32-bit systems, this back-end requires code to be compiled with '#define ImTextureID ImU64'. +// Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // This define is done in the example .vcxproj file and need to be replicated in your app (by e.g. editing imconfig.h) diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp index c5bdec8a..7375abb8 100644 --- a/examples/imgui_impl_dx9.cpp +++ b/examples/imgui_impl_dx9.cpp @@ -1,5 +1,5 @@ -// dear imgui: Renderer for DirectX9 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX9 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! @@ -217,7 +217,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx9"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. diff --git a/examples/imgui_impl_dx9.h b/examples/imgui_impl_dx9.h index b93c89f7..73316ab5 100644 --- a/examples/imgui_impl_dx9.h +++ b/examples/imgui_impl_dx9.h @@ -1,5 +1,5 @@ -// dear imgui: Renderer for DirectX9 -// This needs to be used along with a Platform Binding (e.g. Win32) +// dear imgui: Renderer Backend for DirectX9 +// This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp index 5ea7be08..c96c4e02 100644 --- a/examples/imgui_impl_glfw.cpp +++ b/examples/imgui_impl_glfw.cpp @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for GLFW +// dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) // (Requires: GLFW 3.1+) @@ -143,7 +143,7 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw g_Window = window; g_Time = 0.0; - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) @@ -345,7 +345,7 @@ static void ImGui_ImplGlfw_UpdateGamepads() void ImGui_ImplGlfw_NewFrame() { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); + IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) int w, h; diff --git a/examples/imgui_impl_glfw.h b/examples/imgui_impl_glfw.h index f62f44f3..6345d7a9 100644 --- a/examples/imgui_impl_glfw.h +++ b/examples/imgui_impl_glfw.h @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for GLFW +// dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) diff --git a/examples/imgui_impl_glut.cpp b/examples/imgui_impl_glut.cpp index c8051452..e48bb285 100644 --- a/examples/imgui_impl_glut.cpp +++ b/examples/imgui_impl_glut.cpp @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for GLUT/FreeGLUT +// dear imgui: Platform Backend for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! diff --git a/examples/imgui_impl_glut.h b/examples/imgui_impl_glut.h index 9acb77fb..7b2d919c 100644 --- a/examples/imgui_impl_glut.h +++ b/examples/imgui_impl_glut.h @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for GLUT/FreeGLUT +// dear imgui: Platform Backend for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! diff --git a/examples/imgui_impl_marmalade.cpp b/examples/imgui_impl_marmalade.cpp index 0f723e57..7b17512d 100644 --- a/examples/imgui_impl_marmalade.cpp +++ b/examples/imgui_impl_marmalade.cpp @@ -1,4 +1,4 @@ -// dear imgui: Renderer + Platform Binding for Marmalade + IwGx +// dear imgui: Renderer + Platform Backend for Marmalade + IwGx // Marmalade code: Copyright (C) 2015 by Giovanni Zito (this file is part of Dear ImGui) // Implemented features: diff --git a/examples/imgui_impl_marmalade.h b/examples/imgui_impl_marmalade.h index 9e92d899..c614380c 100644 --- a/examples/imgui_impl_marmalade.h +++ b/examples/imgui_impl_marmalade.h @@ -1,4 +1,4 @@ -// dear imgui: Renderer + Platform Binding for Marmalade + IwGx +// dear imgui: Renderer + Platform Backend for Marmalade + IwGx // Marmalade code: Copyright (C) 2015 by Giovanni Zito (this file is part of Dear ImGui) // Implemented features: diff --git a/examples/imgui_impl_metal.h b/examples/imgui_impl_metal.h index 3e61085c..2a1e6daf 100644 --- a/examples/imgui_impl_metal.h +++ b/examples/imgui_impl_metal.h @@ -1,5 +1,5 @@ -// dear imgui: Renderer for Metal -// This needs to be used along with a Platform Binding (e.g. OSX) +// dear imgui: Renderer Backend for Metal +// This needs to be used along with a Platform Backend (e.g. OSX) // Implemented features: // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! diff --git a/examples/imgui_impl_metal.mm b/examples/imgui_impl_metal.mm index 7cdda733..a8cd2883 100644 --- a/examples/imgui_impl_metal.mm +++ b/examples/imgui_impl_metal.mm @@ -1,5 +1,5 @@ -// dear imgui: Renderer for Metal -// This needs to be used along with a Platform Binding (e.g. OSX) +// dear imgui: Renderer Backend for Metal +// This needs to be used along with a Platform Backend (e.g. OSX) // Implemented features: // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! diff --git a/examples/imgui_impl_opengl2.cpp b/examples/imgui_impl_opengl2.cpp index 79aeadcd..a2e3c423 100644 --- a/examples/imgui_impl_opengl2.cpp +++ b/examples/imgui_impl_opengl2.cpp @@ -1,5 +1,5 @@ -// dear imgui: Renderer for OpenGL2 (legacy OpenGL, fixed pipeline) -// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline) +// 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! @@ -58,7 +58,7 @@ static GLuint g_FontTexture = 0; // Functions bool ImGui_ImplOpenGL2_Init() { - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_opengl2"; return true; diff --git a/examples/imgui_impl_opengl2.h b/examples/imgui_impl_opengl2.h index 9b72cbba..76a675b8 100644 --- a/examples/imgui_impl_opengl2.h +++ b/examples/imgui_impl_opengl2.h @@ -1,5 +1,5 @@ -// dear imgui: Renderer for OpenGL2 (legacy OpenGL, fixed pipeline) -// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline) +// 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! diff --git a/examples/imgui_impl_opengl3.cpp b/examples/imgui_impl_opengl3.cpp index 5349b02d..8e9a068c 100644 --- a/examples/imgui_impl_opengl3.cpp +++ b/examples/imgui_impl_opengl3.cpp @@ -1,7 +1,7 @@ -// dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline +// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline // - Desktop GL: 2.x 3.x 4.x // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) -// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// 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! @@ -155,7 +155,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) g_GlVersion = 200; // GLES 2 #endif - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_opengl3"; #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h index 14eb2842..85bd4bae 100644 --- a/examples/imgui_impl_opengl3.h +++ b/examples/imgui_impl_opengl3.h @@ -1,7 +1,7 @@ -// dear imgui: Renderer for modern OpenGL with shaders / programmatic pipeline +// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline // - Desktop GL: 2.x 3.x 4.x // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) -// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// 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! diff --git a/examples/imgui_impl_osx.h b/examples/imgui_impl_osx.h index d37652be..93d63c58 100644 --- a/examples/imgui_impl_osx.h +++ b/examples/imgui_impl_osx.h @@ -1,10 +1,10 @@ -// dear imgui: Platform Binding for OSX / Cocoa +// dear imgui: Platform Backend for OSX / Cocoa // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) -// [ALPHA] Early bindings, not well tested. If you want a portable application, prefer using the GLFW or SDL platform bindings on Mac. +// [ALPHA] Early backend, not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. // Implemented features: // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this back-end). +// [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend). // Issues: // [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. diff --git a/examples/imgui_impl_osx.mm b/examples/imgui_impl_osx.mm index 90501624..c9a7631d 100644 --- a/examples/imgui_impl_osx.mm +++ b/examples/imgui_impl_osx.mm @@ -1,10 +1,10 @@ -// dear imgui: Platform Binding for OSX / Cocoa +// dear imgui: Platform Backend for OSX / Cocoa // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) -// [ALPHA] Early bindings, not well tested. If you want a portable application, prefer using the GLFW or SDL platform bindings on Mac. +// [ALPHA] Early backend, not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. // Implemented features: // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this back-end). +// [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend). // Issues: // [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. @@ -44,7 +44,7 @@ bool ImGui_ImplOSX_Init() { ImGuiIO& io = ImGui::GetIO(); - // Setup back-end capabilities flags + // Setup backend capabilities flags io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) //io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp index 695ac810..494220c0 100644 --- a/examples/imgui_impl_sdl.cpp +++ b/examples/imgui_impl_sdl.cpp @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for SDL2 +// dear imgui: Platform Backend for SDL2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // (Requires: SDL 2.0. Prefer SDL 2.0.4+ for full feature support.) @@ -132,7 +132,7 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window) { g_Window = window; - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) @@ -343,7 +343,7 @@ static void ImGui_ImplSDL2_UpdateGamepads() void ImGui_ImplSDL2_NewFrame(SDL_Window* window) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); + IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) int w, h; diff --git a/examples/imgui_impl_sdl.h b/examples/imgui_impl_sdl.h index bf207ba0..4b024dfa 100644 --- a/examples/imgui_impl_sdl.h +++ b/examples/imgui_impl_sdl.h @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for SDL2 +// dear imgui: Platform Backend for SDL2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp index 6c585b8a..c617acee 100644 --- a/examples/imgui_impl_vulkan.cpp +++ b/examples/imgui_impl_vulkan.cpp @@ -1,10 +1,10 @@ -// dear imgui: Renderer for Vulkan -// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// dear imgui: Renderer Backend for Vulkan +// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. // Missing features: -// [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914 +// [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -15,9 +15,9 @@ // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. -// You will use those if you want to use this rendering back-end in your engine/app. +// You will use those if you want to use this rendering backend in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by -// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. // CHANGELOG @@ -35,7 +35,7 @@ // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case. -// 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other bindings. +// 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other backends. // 2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example. // 2018-06-08: Vulkan: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-03-03: Vulkan: Various refactor, created a couple of ImGui_ImplVulkanH_XXX helper that the example can use and that viewport support will use. @@ -885,7 +885,7 @@ void ImGui_ImplVulkan_DestroyDeviceObjects() bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) { - // Setup back-end capabilities flags + // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_vulkan"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. @@ -937,7 +937,7 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. // 2) the upcoming multi-viewport feature will need them internally. -// Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, +// Generally we avoid exposing any kind of superfluous high-level helpers in the backends, // but it is too much code to duplicate everywhere so we exceptionally expose them. // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h index d5d2516a..06d50e05 100644 --- a/examples/imgui_impl_vulkan.h +++ b/examples/imgui_impl_vulkan.h @@ -1,10 +1,10 @@ -// dear imgui: Renderer for Vulkan -// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..) +// dear imgui: Renderer Backend for Vulkan +// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. // Missing features: -// [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this binding! See https://github.com/ocornut/imgui/pull/914 +// [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. @@ -15,9 +15,9 @@ // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. -// You will use those if you want to use this rendering back-end in your engine/app. +// You will use those if you want to use this rendering backend in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by -// the back-end itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. +// the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. #pragma once @@ -60,7 +60,7 @@ IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_cou // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. // 2) the upcoming multi-viewport feature will need them internally. -// Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, +// Generally we avoid exposing any kind of superfluous high-level helpers in the backends, // but it is too much code to duplicate everywhere so we exceptionally expose them. // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp index f6dd5b82..ed90366c 100644 --- a/examples/imgui_impl_win32.cpp +++ b/examples/imgui_impl_win32.cpp @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for Windows (standard windows API for 32 and 64 bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: @@ -68,7 +68,7 @@ bool ImGui_ImplWin32_Init(void* hwnd) if (!::QueryPerformanceCounter((LARGE_INTEGER*)&g_Time)) return false; - // Setup back-end capabilities flags + // Setup backend capabilities flags g_hWnd = (HWND)hwnd; ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) @@ -214,7 +214,7 @@ static void ImGui_ImplWin32_UpdateGamepads() void ImGui_ImplWin32_NewFrame() { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer back-end. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); + IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) RECT rect; @@ -259,7 +259,7 @@ void ImGui_ImplWin32_NewFrame() // Win32 message handler (process Win32 mouse/keyboard inputs, etc.) // Call from your application's message handler. -// When implementing your own back-end, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs. +// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags. @@ -352,7 +352,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA //--------------------------------------------------------------------------------------------------------- // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable. // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically. -// If you are trying to implement your own back-end for your own engine, you may ignore that noise. +// If you are trying to implement your own backend for your own engine, you may ignore that noise. //--------------------------------------------------------------------------------------------------------- // Implement some of the functions and types normally declared in recent Windows SDK. diff --git a/examples/imgui_impl_win32.h b/examples/imgui_impl_win32.h index 8923bd63..f0a93a43 100644 --- a/examples/imgui_impl_win32.h +++ b/examples/imgui_impl_win32.h @@ -1,4 +1,4 @@ -// dear imgui: Platform Binding for Windows (standard windows API for 32 and 64 bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: diff --git a/imconfig.h b/imconfig.h index 6b87dd6c..280d1436 100644 --- a/imconfig.h +++ b/imconfig.h @@ -76,12 +76,12 @@ */ //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. -// Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bit indices). +// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int -//---- Override ImDrawCallback signature (will need to modify renderer back-ends accordingly) +//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) //struct ImDrawList; //struct ImDrawCmd; //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); diff --git a/imgui.cpp b/imgui.cpp index 3cd37c44..265efd90 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -167,21 +167,21 @@ CODE GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE --------------------------------------------------------------- - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. - - In the majority of cases you should be able to use unmodified back-ends files available in the examples/ folder. - - Add the Dear ImGui source files + selected back-end source files to your projects or using your preferred build system. + - In the majority of cases you should be able to use unmodified backends files available in the examples/ folder. + - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system. It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL). - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render(). - - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code. + - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code. - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder. HOW A SIMPLE APPLICATION MAY LOOK LIKE -------------------------------------- - EXHIBIT 1: USING THE EXAMPLE BINDINGS (= imgui_impl_XXX.cpp files from the examples/ folder). + EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the examples/ folder). The sub-folders in examples/ contains examples applications following this structure. // Application init: create a dear imgui context, setup some options, load fonts @@ -191,7 +191,7 @@ CODE // TODO: Fill optional fields of the io structure later. // TODO: Load TTF/OTF fonts if you don't want to use the default font. - // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp) + // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp) ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); @@ -217,7 +217,7 @@ CODE ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); - EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE + EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE // Application init: create a dear imgui context, setup some options, load fonts ImGui::CreateContext(); @@ -242,7 +242,7 @@ CODE while (true) { // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc. - // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings) + // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends) io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds) io.DisplaySize.x = 1920.0f; // set the current display width io.DisplaySize.y = 1280.0f; // set the current display height here @@ -278,7 +278,7 @@ CODE HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE --------------------------------------------- - The bindings in impl_impl_XXX.cpp files contains many working implementations of a rendering function. + The backends in impl_impl_XXX.cpp files contains many working implementations of a rendering function. void void MyImGuiRenderFunction(ImDrawData* draw_data) { @@ -357,7 +357,7 @@ CODE - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements. When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. - When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that. + When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that. (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!) (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want to set a boolean to ignore your other external mouse positions until the external source is moved again.) @@ -372,7 +372,7 @@ CODE You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): - - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your back-end + - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT @@ -462,10 +462,10 @@ CODE - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). - - 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). - old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports. - when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call. - in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. + - 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). + old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports. + when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call. + in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details. - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. @@ -475,7 +475,7 @@ CODE - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format", consistent with other functions. Kept redirection functions (will obsolete). - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value. - - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch). + - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch). - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now. - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums. @@ -519,7 +519,7 @@ CODE - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete). - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete). - - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". + - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)! - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). @@ -817,7 +817,7 @@ CODE 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 -// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end) +// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend) static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow(). static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. @@ -961,7 +961,7 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. - AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require back-end to render with bilinear filtering. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -3339,7 +3339,7 @@ ImGuiIO& ImGui::GetIO() return GImGui->IO; } -// Pass this to your back-end rendering function! Valid after Render() and until the next call to NewFrame() +// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { ImGuiContext& g = *GImGui; @@ -4115,11 +4115,11 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds. // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents. // - If you want large meshes with more than 64K vertices, you can either: - // (A) Handle the ImDrawCmd::VtxOffset value in your renderer back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. - // Most example back-ends already support this from 1.71. Pre-1.71 back-ends won't. + // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. + // Most example backends already support this from 1.71. Pre-1.71 backends won't. // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them. - // (B) Or handle 32-bit indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. - // Most example back-ends already support this. For example, the OpenGL example code detect index size at compile-time: + // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. + // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time: // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); // Your own engine or render API may use different parameters or function calls to specify index sizes. // 2 and 4 bytes indices are generally supported by most graphics API. @@ -4444,7 +4444,7 @@ int ImGui::GetKeyIndex(ImGuiKey imgui_key) } // Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]! -// Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]! +// Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]! bool ImGui::IsKeyDown(int user_key_index) { if (user_key_index < 0) @@ -4600,7 +4600,7 @@ bool ImGui::IsAnyMouseDown() // Return the delta from the initial clicking position while the mouse button is clicked or was just released. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once. -// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window. +// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window. ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold) { ImGuiContext& g = *GImGui; @@ -6899,7 +6899,7 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); - // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. + // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) g.IO.ConfigWindowsResizeFromEdges = false; } @@ -6909,7 +6909,7 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() ImGuiContext& g = *GImGui; // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() - // One possible reason leading to this assert is that your back-ends update inputs _AFTER_ NewFrame(). + // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame(). const ImGuiKeyModFlags expected_key_mod_flags = GetMergedKeyModFlags(); IM_ASSERT(g.IO.KeyMods == expected_key_mod_flags && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(expected_key_mod_flags); @@ -8574,7 +8574,7 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer]; ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight())); ImRect visible_rect = GetViewportRect(); - return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta. + return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta. } } @@ -9216,7 +9216,7 @@ static void ImGui::NavUpdateWindowing() } // Keyboard: Press and Release ALT to toggle menu layer - // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB + // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of backend clearing releases all keys on ALT-TAB if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed)) g.NavWindowingToggleLayer = true; if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released)) diff --git a/imgui.h b/imgui.h index e9dcf847..9d16a39d 100644 --- a/imgui.h +++ b/imgui.h @@ -64,7 +64,7 @@ Index of this file: #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) -// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h) +// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h) // Using dear imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as dear imgui is a call-heavy API) #ifndef IMGUI_API #define IMGUI_API @@ -172,7 +172,7 @@ typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: f // Other types #ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx'] -typedef void* ImTextureID; // User data for rendering back-end to identify a texture. This is whatever to you want it to be! read the FAQ about ImTextureID for details. +typedef void* ImTextureID; // User data for rendering backend to identify a texture. This is whatever to you want it to be! read the FAQ about ImTextureID for details. #endif typedef unsigned int ImGuiID; // A unique ID used by widgets, typically hashed from a stack of string. typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); @@ -733,7 +733,7 @@ namespace ImGui IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); // Inputs Utilities: Keyboard - // - For 'int user_key_index' you can use your own indices/enums according to how your back-end/engine stored them in io.KeysDown[]. + // - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[]. // - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index. IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. @@ -828,7 +828,7 @@ enum ImGuiWindowFlags_ ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu() // [Obsolete] - //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by back-end (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) + //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by backend (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) }; // Flags for ImGui::InputText() @@ -1065,7 +1065,7 @@ enum ImGuiKey_ ImGuiKey_COUNT }; -// To test io.KeyMods (which is a combination of individual fields io.KeyCtrl, io.KeyShift, io.KeyAlt set by user/back-end) +// To test io.KeyMods (which is a combination of individual fields io.KeyCtrl, io.KeyShift, io.KeyAlt set by user/backend) enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, @@ -1077,7 +1077,7 @@ enum ImGuiKeyModFlags_ // Gamepad/Keyboard navigation // Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays. -// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Back-end: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). +// Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Backend: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). // Read instructions in imgui.cpp for more details. Download PNG/PSD at http://goo.gl/9LgVZW. enum ImGuiNavInput_ { @@ -1115,25 +1115,25 @@ enum ImGuiConfigFlags_ { ImGuiConfigFlags_None = 0, ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeysDown[]. - ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[]. Back-end also needs to set ImGuiBackendFlags_HasGamepad. - ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth. + ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui backend to fill io.NavInputs[]. Backend also needs to set ImGuiBackendFlags_HasGamepad. + ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth. ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. - ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the back-end. - ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. + ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend. + ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. - // User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core Dear ImGui) + // 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. ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse. }; -// Back-end capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom back-end. +// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. enum ImGuiBackendFlags_ { ImGuiBackendFlags_None = 0, - ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end Platform supports gamepad and currently has one connected. - ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end Platform supports honoring GetMouseCursor() value to change the OS cursor shape. - ImGuiBackendFlags_HasSetMousePos = 1 << 2, // Back-end Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). - ImGuiBackendFlags_RendererHasVtxOffset = 1 << 3 // Back-end Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + ImGuiBackendFlags_HasGamepad = 1 << 0, // Backend Platform supports gamepad and currently has one connected. + 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 ImGuiConfigFlags_NavEnableSetMousePos 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. }; // Enumeration for PushStyleColor() / PopStyleColor() @@ -1318,7 +1318,7 @@ enum ImGuiMouseButton_ }; // Enumeration for GetMouseCursor() -// User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here +// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here enum ImGuiMouseCursor_ { ImGuiMouseCursor_None = -1, @@ -1475,7 +1475,7 @@ struct ImGuiStyle ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). - bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require back-end to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList). bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. @@ -1498,7 +1498,7 @@ struct ImGuiIO //------------------------------------------------------------------ ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. - ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by back-end (imgui_impl_xxx files or custom back-end) to communicate features supported by the back-end. + 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. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. @@ -1519,7 +1519,7 @@ struct ImGuiIO 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. // Miscellaneous options - 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 back-end implementations. + 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. bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63) bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) @@ -1528,15 +1528,15 @@ struct ImGuiIO //------------------------------------------------------------------ // Platform Functions - // (the imgui_impl_xxxx back-end files are setting those up for you) + // (the imgui_impl_xxxx backend files are setting those up for you) //------------------------------------------------------------------ - // Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + User data for back-end/wrappers to store their own stuff. + // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff. const char* BackendPlatformName; // = NULL const char* BackendRendererName; // = NULL - void* BackendPlatformUserData; // = NULL // User data for platform back-end - void* BackendRendererUserData; // = NULL // User data for renderer back-end - void* BackendLanguageUserData; // = NULL // User data for non C++ programming language back-end + void* BackendPlatformUserData; // = NULL // User data for platform backend + void* BackendRendererUserData; // = NULL // User data for renderer backend + void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend // Optional: Access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) @@ -1556,7 +1556,7 @@ struct ImGuiIO ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. - float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends. + float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all backends. bool KeyCtrl; // Keyboard modifier pressed: Control bool KeyShift; // Keyboard modifier pressed: Shift bool KeyAlt; // Keyboard modifier pressed: Alt @@ -1579,7 +1579,7 @@ struct ImGuiIO bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). - bool WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. + bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. bool NavVisible; // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events). @@ -1614,7 +1614,7 @@ struct ImGuiIO float NavInputsDownDurationPrev[ImGuiNavInput_COUNT]; float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16 - ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform back-end). Fill using AddInputCharacter() helper. + ImVector InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. IMGUI_API ImGuiIO(); }; @@ -1954,13 +1954,13 @@ struct ImColor // A) Change your GPU render state, // B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' -// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering back-end accordingly. +// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly. #ifndef ImDrawCallback typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); #endif -// Special Draw callback value to request renderer back-end to reset the graphics/render state. -// The renderer back-end needs to handle this special value, otherwise it will crash trying to call a function at this address. +// Special Draw callback value to request renderer backend to reset the graphics/render state. +// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address. // This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored. // It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call). #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-1) @@ -1968,7 +1968,7 @@ typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* c // Typically, 1 command = 1 GPU draw call (unless command is a callback) // - VtxOffset/IdxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, // those fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. -// Pre-1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. +// Pre-1.71 backends will typically ignore the VtxOffset/IdxOffset fields. // - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). struct ImDrawCmd { @@ -1984,7 +1984,7 @@ struct ImDrawCmd }; // Vertex index, default to 16-bit -// To allow large meshes with 16-bit indices: set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer back-end (recommended). +// To allow large meshes with 16-bit indices: set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer backend (recommended). // To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in imconfig.h. #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; @@ -2050,7 +2050,7 @@ enum ImDrawListFlags_ { ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) - ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require back-end to render with bilinear filtering. + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering. ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6285cdd6..13353bad 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -381,7 +381,7 @@ void ImGui::ShowDemoWindow(bool* p_open) { ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); - ImGui::SameLine(); HelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); + ImGui::SameLine(); HelpMarker("Required backend to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); @@ -398,7 +398,7 @@ void ImGui::ShowDemoWindow(bool* p_open) io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; } ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); - ImGui::SameLine(); HelpMarker("Instruct back-end to not alter mouse cursor shape and visibility."); + ImGui::SameLine(); HelpMarker("Instruct backend to not alter mouse cursor shape and visibility."); ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); ImGui::SameLine(); HelpMarker("Set to false to disable blinking cursor, for users who consider it distracting"); ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges); @@ -414,10 +414,10 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Backend Flags")) { HelpMarker( - "Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.\n" - "Here we expose then as read-only fields to avoid breaking interactions with your back-end."); + "Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\n" + "Here we expose then as read-only fields to avoid breaking interactions with your backend."); - // Make a local copy to avoid modifying actual back-end flags. + // Make a local copy to avoid modifying actual backend flags. ImGuiBackendFlags backend_flags = io.BackendFlags; ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasGamepad); ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasMouseCursors); @@ -902,8 +902,8 @@ static void ShowDemoWindowWidgets() // 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 back-end via the ImDrawCmd structure. - // If you use one of the default imgui_impl_XXXX.cpp rendering back-end, they all have comments at the top + // will be passed to the rendering backend via the ImDrawCmd structure. + // 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 // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc. @@ -4053,7 +4053,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); ImGui::SameLine(); - HelpMarker("Faster lines using texture data. Require back-end to render with bilinear filtering (not point/nearest filtering)."); + 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(100); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d657028e..2ea773e2 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4004,7 +4004,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (state->SelectedAllMouseLock && !io.MouseDown[0]) state->SelectedAllMouseLock = false; - // It is ill-defined whether the back-end needs to send a \t character when pressing the TAB keys. + // It is ill-defined whether the backend needs to send a \t character when pressing the TAB keys. // Win32 and GLFW naturally do it but not SDL. const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper); if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !ignore_char_inputs && !io.KeyShift && !is_readonly) From d9b2fb7338a1b67cdbad15b6c9fa60a2bd29cdf4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 15:22:06 +0200 Subject: [PATCH 310/959] Moving backends code from examples/ to backends/ (step 1: moving source files) --- {examples => backends}/imgui_impl_allegro5.cpp | 0 {examples => backends}/imgui_impl_allegro5.h | 0 {examples => backends}/imgui_impl_dx10.cpp | 0 {examples => backends}/imgui_impl_dx10.h | 0 {examples => backends}/imgui_impl_dx11.cpp | 0 {examples => backends}/imgui_impl_dx11.h | 0 {examples => backends}/imgui_impl_dx12.cpp | 0 {examples => backends}/imgui_impl_dx12.h | 0 {examples => backends}/imgui_impl_dx9.cpp | 0 {examples => backends}/imgui_impl_dx9.h | 0 {examples => backends}/imgui_impl_glfw.cpp | 0 {examples => backends}/imgui_impl_glfw.h | 0 {examples => backends}/imgui_impl_glut.cpp | 0 {examples => backends}/imgui_impl_glut.h | 0 {examples => backends}/imgui_impl_marmalade.cpp | 0 {examples => backends}/imgui_impl_marmalade.h | 0 {examples => backends}/imgui_impl_metal.h | 0 {examples => backends}/imgui_impl_metal.mm | 0 {examples => backends}/imgui_impl_opengl2.cpp | 0 {examples => backends}/imgui_impl_opengl2.h | 0 {examples => backends}/imgui_impl_opengl3.cpp | 0 {examples => backends}/imgui_impl_opengl3.h | 0 {examples => backends}/imgui_impl_osx.h | 0 {examples => backends}/imgui_impl_osx.mm | 0 {examples => backends}/imgui_impl_sdl.cpp | 0 {examples => backends}/imgui_impl_sdl.h | 0 {examples => backends}/imgui_impl_vulkan.cpp | 0 {examples => backends}/imgui_impl_vulkan.h | 0 {examples => backends}/imgui_impl_win32.cpp | 0 {examples => backends}/imgui_impl_win32.h | 0 imgui.cpp | 6 +++--- imgui.h | 2 +- 32 files changed, 4 insertions(+), 4 deletions(-) rename {examples => backends}/imgui_impl_allegro5.cpp (100%) rename {examples => backends}/imgui_impl_allegro5.h (100%) rename {examples => backends}/imgui_impl_dx10.cpp (100%) rename {examples => backends}/imgui_impl_dx10.h (100%) rename {examples => backends}/imgui_impl_dx11.cpp (100%) rename {examples => backends}/imgui_impl_dx11.h (100%) rename {examples => backends}/imgui_impl_dx12.cpp (100%) rename {examples => backends}/imgui_impl_dx12.h (100%) rename {examples => backends}/imgui_impl_dx9.cpp (100%) rename {examples => backends}/imgui_impl_dx9.h (100%) rename {examples => backends}/imgui_impl_glfw.cpp (100%) rename {examples => backends}/imgui_impl_glfw.h (100%) rename {examples => backends}/imgui_impl_glut.cpp (100%) rename {examples => backends}/imgui_impl_glut.h (100%) rename {examples => backends}/imgui_impl_marmalade.cpp (100%) rename {examples => backends}/imgui_impl_marmalade.h (100%) rename {examples => backends}/imgui_impl_metal.h (100%) rename {examples => backends}/imgui_impl_metal.mm (100%) rename {examples => backends}/imgui_impl_opengl2.cpp (100%) rename {examples => backends}/imgui_impl_opengl2.h (100%) rename {examples => backends}/imgui_impl_opengl3.cpp (100%) rename {examples => backends}/imgui_impl_opengl3.h (100%) rename {examples => backends}/imgui_impl_osx.h (100%) rename {examples => backends}/imgui_impl_osx.mm (100%) rename {examples => backends}/imgui_impl_sdl.cpp (100%) rename {examples => backends}/imgui_impl_sdl.h (100%) rename {examples => backends}/imgui_impl_vulkan.cpp (100%) rename {examples => backends}/imgui_impl_vulkan.h (100%) rename {examples => backends}/imgui_impl_win32.cpp (100%) rename {examples => backends}/imgui_impl_win32.h (100%) diff --git a/examples/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp similarity index 100% rename from examples/imgui_impl_allegro5.cpp rename to backends/imgui_impl_allegro5.cpp diff --git a/examples/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h similarity index 100% rename from examples/imgui_impl_allegro5.h rename to backends/imgui_impl_allegro5.h diff --git a/examples/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp similarity index 100% rename from examples/imgui_impl_dx10.cpp rename to backends/imgui_impl_dx10.cpp diff --git a/examples/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h similarity index 100% rename from examples/imgui_impl_dx10.h rename to backends/imgui_impl_dx10.h diff --git a/examples/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp similarity index 100% rename from examples/imgui_impl_dx11.cpp rename to backends/imgui_impl_dx11.cpp diff --git a/examples/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h similarity index 100% rename from examples/imgui_impl_dx11.h rename to backends/imgui_impl_dx11.h diff --git a/examples/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp similarity index 100% rename from examples/imgui_impl_dx12.cpp rename to backends/imgui_impl_dx12.cpp diff --git a/examples/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h similarity index 100% rename from examples/imgui_impl_dx12.h rename to backends/imgui_impl_dx12.h diff --git a/examples/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp similarity index 100% rename from examples/imgui_impl_dx9.cpp rename to backends/imgui_impl_dx9.cpp diff --git a/examples/imgui_impl_dx9.h b/backends/imgui_impl_dx9.h similarity index 100% rename from examples/imgui_impl_dx9.h rename to backends/imgui_impl_dx9.h diff --git a/examples/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp similarity index 100% rename from examples/imgui_impl_glfw.cpp rename to backends/imgui_impl_glfw.cpp diff --git a/examples/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h similarity index 100% rename from examples/imgui_impl_glfw.h rename to backends/imgui_impl_glfw.h diff --git a/examples/imgui_impl_glut.cpp b/backends/imgui_impl_glut.cpp similarity index 100% rename from examples/imgui_impl_glut.cpp rename to backends/imgui_impl_glut.cpp diff --git a/examples/imgui_impl_glut.h b/backends/imgui_impl_glut.h similarity index 100% rename from examples/imgui_impl_glut.h rename to backends/imgui_impl_glut.h diff --git a/examples/imgui_impl_marmalade.cpp b/backends/imgui_impl_marmalade.cpp similarity index 100% rename from examples/imgui_impl_marmalade.cpp rename to backends/imgui_impl_marmalade.cpp diff --git a/examples/imgui_impl_marmalade.h b/backends/imgui_impl_marmalade.h similarity index 100% rename from examples/imgui_impl_marmalade.h rename to backends/imgui_impl_marmalade.h diff --git a/examples/imgui_impl_metal.h b/backends/imgui_impl_metal.h similarity index 100% rename from examples/imgui_impl_metal.h rename to backends/imgui_impl_metal.h diff --git a/examples/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm similarity index 100% rename from examples/imgui_impl_metal.mm rename to backends/imgui_impl_metal.mm diff --git a/examples/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp similarity index 100% rename from examples/imgui_impl_opengl2.cpp rename to backends/imgui_impl_opengl2.cpp diff --git a/examples/imgui_impl_opengl2.h b/backends/imgui_impl_opengl2.h similarity index 100% rename from examples/imgui_impl_opengl2.h rename to backends/imgui_impl_opengl2.h diff --git a/examples/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp similarity index 100% rename from examples/imgui_impl_opengl3.cpp rename to backends/imgui_impl_opengl3.cpp diff --git a/examples/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h similarity index 100% rename from examples/imgui_impl_opengl3.h rename to backends/imgui_impl_opengl3.h diff --git a/examples/imgui_impl_osx.h b/backends/imgui_impl_osx.h similarity index 100% rename from examples/imgui_impl_osx.h rename to backends/imgui_impl_osx.h diff --git a/examples/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm similarity index 100% rename from examples/imgui_impl_osx.mm rename to backends/imgui_impl_osx.mm diff --git a/examples/imgui_impl_sdl.cpp b/backends/imgui_impl_sdl.cpp similarity index 100% rename from examples/imgui_impl_sdl.cpp rename to backends/imgui_impl_sdl.cpp diff --git a/examples/imgui_impl_sdl.h b/backends/imgui_impl_sdl.h similarity index 100% rename from examples/imgui_impl_sdl.h rename to backends/imgui_impl_sdl.h diff --git a/examples/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp similarity index 100% rename from examples/imgui_impl_vulkan.cpp rename to backends/imgui_impl_vulkan.cpp diff --git a/examples/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h similarity index 100% rename from examples/imgui_impl_vulkan.h rename to backends/imgui_impl_vulkan.h diff --git a/examples/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp similarity index 100% rename from examples/imgui_impl_win32.cpp rename to backends/imgui_impl_win32.cpp diff --git a/examples/imgui_impl_win32.h b/backends/imgui_impl_win32.h similarity index 100% rename from examples/imgui_impl_win32.h rename to backends/imgui_impl_win32.h diff --git a/imgui.cpp b/imgui.cpp index 265efd90..c24e8e4e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -181,7 +181,7 @@ CODE HOW A SIMPLE APPLICATION MAY LOOK LIKE -------------------------------------- - EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the examples/ folder). + EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). The sub-folders in examples/ contains examples applications following this structure. // Application init: create a dear imgui context, setup some options, load fonts @@ -462,7 +462,7 @@ CODE - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). - - 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). + - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports. when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call. in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. @@ -566,7 +566,7 @@ CODE you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. this necessary change will break your rendering function! the fix should be very easy. sorry for that :( - - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. + - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. - the signature of the io.RenderDrawListsFn handler has changed! old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). diff --git a/imgui.h b/imgui.h index 9d16a39d..01b01f2b 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.80 WIP" -#define IMGUI_VERSION_NUM 17904 +#define IMGUI_VERSION_NUM 17905 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) From 428f4fce7039d9f0201e19553e67ba09557657c6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 15:51:41 +0200 Subject: [PATCH 311/959] Moving backends code from examples/ to backends/ (step 2: moving vulkan cruft) --- .../gen_spv.sh => backends/vulkan/generate_spv.sh | 3 +++ .../example_glfw_vulkan => backends/vulkan}/glsl_shader.frag | 0 .../example_glfw_vulkan => backends/vulkan}/glsl_shader.vert | 0 3 files changed, 3 insertions(+) rename examples/example_glfw_vulkan/gen_spv.sh => backends/vulkan/generate_spv.sh (55%) rename {examples/example_glfw_vulkan => backends/vulkan}/glsl_shader.frag (100%) rename {examples/example_glfw_vulkan => backends/vulkan}/glsl_shader.vert (100%) diff --git a/examples/example_glfw_vulkan/gen_spv.sh b/backends/vulkan/generate_spv.sh similarity index 55% rename from examples/example_glfw_vulkan/gen_spv.sh rename to backends/vulkan/generate_spv.sh index e0d7f3b0..948ef773 100755 --- a/examples/example_glfw_vulkan/gen_spv.sh +++ b/backends/vulkan/generate_spv.sh @@ -1,3 +1,6 @@ #!/bin/bash +## -V: create SPIR-V binary +## -x: save binary output as text-based 32-bit hexadecimal numbers +## -o: output file glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert diff --git a/examples/example_glfw_vulkan/glsl_shader.frag b/backends/vulkan/glsl_shader.frag similarity index 100% rename from examples/example_glfw_vulkan/glsl_shader.frag rename to backends/vulkan/glsl_shader.frag diff --git a/examples/example_glfw_vulkan/glsl_shader.vert b/backends/vulkan/glsl_shader.vert similarity index 100% rename from examples/example_glfw_vulkan/glsl_shader.vert rename to backends/vulkan/glsl_shader.vert From a7e21fb05f9073a7eca7583b3405c207f76aab48 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 15:41:57 +0200 Subject: [PATCH 312/959] Moving backends code from examples/ to backends/ (step 3: fixing project files) --- backends/imgui_impl_allegro5.cpp | 3 ++- backends/imgui_impl_dx12.h | 3 ++- examples/example_allegro5/README.md | 4 ++-- .../example_allegro5/example_allegro5.vcxproj | 14 ++++++------- .../example_allegro5.vcxproj.filters | 6 +++--- .../project.pbxproj | 8 ++++---- .../project.pbxproj | 8 ++++---- examples/example_apple_opengl2/main.mm | 4 ++-- examples/example_emscripten/Makefile | 11 +++++----- examples/example_glfw_metal/Makefile | 15 +++++++------- examples/example_glfw_opengl2/Makefile | 11 +++++----- examples/example_glfw_opengl2/build_win32.bat | 2 +- .../example_glfw_opengl2.vcxproj | 18 ++++++++--------- .../example_glfw_opengl2.vcxproj.filters | 16 +++++++-------- examples/example_glfw_opengl3/Makefile | 11 +++++----- examples/example_glfw_opengl3/build_win32.bat | 2 +- .../example_glfw_opengl3.vcxproj | 18 ++++++++--------- .../example_glfw_opengl3.vcxproj.filters | 16 +++++++-------- examples/example_glfw_vulkan/CMakeLists.txt | 2 +- examples/example_glfw_vulkan/build_win32.bat | 4 ++-- examples/example_glfw_vulkan/build_win64.bat | 4 ++-- .../example_glfw_vulkan.vcxproj | 18 ++++++++--------- .../example_glfw_vulkan.vcxproj.filters | 20 +++++++++---------- examples/example_glut_opengl2/Makefile | 11 +++++----- .../example_glut_opengl2.vcxproj | 10 +++++----- .../example_glut_opengl2.vcxproj.filters | 14 ++++++------- .../example_marmalade/marmalade_example.mkb | 8 ++++---- examples/example_null/Makefile | 13 ++++++------ .../example_sdl_directx11/build_win32.bat | 2 +- .../example_sdl_directx11.vcxproj | 18 ++++++++--------- .../example_sdl_directx11.vcxproj.filters | 14 ++++++------- examples/example_sdl_metal/Makefile | 15 +++++++------- examples/example_sdl_opengl2/Makefile | 11 +++++----- examples/example_sdl_opengl2/README.md | 8 ++++---- examples/example_sdl_opengl2/build_win32.bat | 2 +- .../example_sdl_opengl2.vcxproj | 18 ++++++++--------- .../example_sdl_opengl2.vcxproj.filters | 16 +++++++-------- examples/example_sdl_opengl3/Makefile | 11 +++++----- examples/example_sdl_opengl3/README.md | 8 ++++---- examples/example_sdl_opengl3/build_win32.bat | 2 +- .../example_sdl_opengl3.vcxproj | 16 +++++++-------- .../example_sdl_opengl3.vcxproj.filters | 10 +++++----- .../example_sdl_vulkan.vcxproj | 16 +++++++-------- .../example_sdl_vulkan.vcxproj.filters | 8 ++++---- .../example_win32_directx10/build_win32.bat | 2 +- .../example_win32_directx10.vcxproj | 16 +++++++-------- .../example_win32_directx10.vcxproj.filters | 8 ++++---- .../example_win32_directx11/build_win32.bat | 2 +- .../example_win32_directx11.vcxproj | 18 ++++++++--------- .../example_win32_directx11.vcxproj.filters | 16 +++++++-------- .../example_win32_directx12/build_win32.bat | 2 +- .../example_win32_directx12.vcxproj | 16 +++++++-------- .../example_win32_directx12.vcxproj.filters | 8 ++++---- .../example_win32_directx9/build_win32.bat | 2 +- .../example_win32_directx9.vcxproj | 16 +++++++-------- .../example_win32_directx9.vcxproj.filters | 8 ++++---- 56 files changed, 287 insertions(+), 276 deletions(-) diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index 61e9ad20..f49c0935 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -9,7 +9,8 @@ // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. // [ ] Platform: Missing gamepad support. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// You can copy and use unmodified backends (imgui_impl_* files) in your project. +// See matching application in examples/ for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui, Original Allegro 5 code by @birthggd diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index ec0b70ae..0a0d8d9b 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -9,7 +9,8 @@ // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // This define is done in the example .vcxproj file and need to be replicated in your app (by e.g. editing imconfig.h) -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// You can copy and use unmodified backends (imgui_impl_* files) in your project. +// See matching application in examples/ for an example of using this. // If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui diff --git a/examples/example_allegro5/README.md b/examples/example_allegro5/README.md index 74ba4cc7..0e27f5f6 100644 --- a/examples/example_allegro5/README.md +++ b/examples/example_allegro5/README.md @@ -12,7 +12,7 @@ Note that the backend supports _BOTH_ 16-bit and 32-bit indices, but 32-bit indi ### On Ubuntu 14.04+ and macOS ```bash -g++ -DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" -I .. -I ../.. main.cpp ../imgui_impl_allegro5.cpp ../../imgui*.cpp -lallegro -lallegro_main -lallegro_primitives -o allegro5_example +g++ -DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" -I .. -I ../.. main.cpp ../../backends/imgui_impl_allegro5.cpp ../../imgui*.cpp -lallegro -lallegro_main -lallegro_primitives -o allegro5_example ``` On macOS, install Allegro with homebrew: `brew install allegro`. @@ -31,5 +31,5 @@ cd vcpkg Build: ``` set ALLEGRODIR=path_to_your_allegro5_folder -cl /Zi /MD /I %ALLEGRODIR%\include /DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" /I .. /I ..\.. main.cpp ..\imgui_impl_allegro5.cpp ..\..\imgui*.cpp /link /LIBPATH:%ALLEGRODIR%\lib allegro-5.0.10-monolith-md.lib user32.lib +cl /Zi /MD /I %ALLEGRODIR%\include /DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" /I .. /I ..\.. main.cpp ..\..\backends\imgui_impl_allegro5.cpp ..\..\imgui*.cpp /link /LIBPATH:%ALLEGRODIR%\lib allegro-5.0.10-monolith-md.lib user32.lib ``` diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index f5fadc37..d50318a9 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -90,7 +90,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%(AdditionalIncludeDirectories) true @@ -104,7 +104,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%(AdditionalIncludeDirectories) true @@ -120,7 +120,7 @@ MaxSpeed true true - ..\..;..;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) false @@ -140,7 +140,7 @@ MaxSpeed true true - ..\..;..;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;$(SolutionDir)\libs\gl3w;%(AdditionalIncludeDirectories) false @@ -159,7 +159,7 @@ - + @@ -167,7 +167,7 @@ - + @@ -176,4 +176,4 @@ - \ No newline at end of file + diff --git a/examples/example_allegro5/example_allegro5.vcxproj.filters b/examples/example_allegro5/example_allegro5.vcxproj.filters index 8019ebfd..9abb67e7 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj.filters +++ b/examples/example_allegro5/example_allegro5.vcxproj.filters @@ -22,7 +22,7 @@ sources - + sources @@ -42,7 +42,7 @@ imgui - + sources @@ -52,4 +52,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj index f1c10494..38c45cfd 100644 --- a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj +++ b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj @@ -54,8 +54,8 @@ 8307E7E320E9F9C900473790 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 8307E7E520E9F9C900473790 /* Info-macOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; 8307E7E620E9F9C900473790 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - 836D2A2C20EE208D0098E909 /* imgui_impl_osx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_osx.h; path = ../../imgui_impl_osx.h; sourceTree = ""; }; - 836D2A2D20EE208E0098E909 /* imgui_impl_osx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_osx.mm; path = ../../imgui_impl_osx.mm; sourceTree = ""; }; + 836D2A2C20EE208D0098E909 /* imgui_impl_osx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_osx.h; path = ../../../backends/imgui_impl_osx.h; sourceTree = ""; }; + 836D2A2D20EE208E0098E909 /* imgui_impl_osx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_osx.mm; path = ../../../backends/imgui_impl_osx.mm; sourceTree = ""; }; 836D2A2F20EE4A180098E909 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = ""; }; 836D2A3120EE4A900098E909 /* Launch Screen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = "Launch Screen.storyboard"; sourceTree = ""; }; 83BBE9E420EB46B900295997 /* Metal.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Metal.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.4.sdk/System/Library/Frameworks/Metal.framework; sourceTree = DEVELOPER_DIR; }; @@ -64,8 +64,8 @@ 83BBE9EA20EB471700295997 /* MetalKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MetalKit.framework; path = System/Library/Frameworks/MetalKit.framework; sourceTree = SDKROOT; }; 83BBE9EB20EB471700295997 /* Metal.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Metal.framework; path = System/Library/Frameworks/Metal.framework; sourceTree = SDKROOT; }; 83BBE9EE20EB471C00295997 /* ModelIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ModelIO.framework; path = System/Library/Frameworks/ModelIO.framework; sourceTree = SDKROOT; }; - 83BBE9FC20EB54D800295997 /* imgui_impl_metal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_metal.h; path = ../../imgui_impl_metal.h; sourceTree = ""; }; - 83BBE9FD20EB54D800295997 /* imgui_impl_metal.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_metal.mm; path = ../../imgui_impl_metal.mm; sourceTree = ""; }; + 83BBE9FC20EB54D800295997 /* imgui_impl_metal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_metal.h; path = ../../../backends/imgui_impl_metal.h; sourceTree = ""; }; + 83BBE9FD20EB54D800295997 /* imgui_impl_metal.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_metal.mm; path = ../../../backends/imgui_impl_metal.mm; sourceTree = ""; }; 83BBEA0020EB54E700295997 /* imgui.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui.h; path = ../../imgui.h; sourceTree = ""; }; 83BBEA0120EB54E700295997 /* imgui_draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_draw.cpp; path = ../../imgui_draw.cpp; sourceTree = ""; }; 83BBEA0220EB54E700295997 /* imgui_demo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_demo.cpp; path = ../../imgui_demo.cpp; sourceTree = ""; }; diff --git a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj index 5bdf74b5..204b68a9 100644 --- a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj +++ b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj @@ -34,10 +34,10 @@ 07A82EDA213941D00078D120 /* imgui_widgets.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_widgets.cpp; path = ../../imgui_widgets.cpp; sourceTree = ""; }; 4080A96B20B029B00036BA46 /* example_osx_opengl2 */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = example_osx_opengl2; sourceTree = BUILT_PRODUCTS_DIR; }; 4080A98A20B02CD90036BA46 /* main.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = main.mm; sourceTree = SOURCE_ROOT; }; - 4080A99E20B034280036BA46 /* imgui_impl_opengl2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_impl_opengl2.cpp; path = ../imgui_impl_opengl2.cpp; sourceTree = ""; }; - 4080A99F20B034280036BA46 /* imgui_impl_osx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_osx.mm; path = ../imgui_impl_osx.mm; sourceTree = ""; }; - 4080A9A020B034280036BA46 /* imgui_impl_opengl2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_opengl2.h; path = ../imgui_impl_opengl2.h; sourceTree = ""; }; - 4080A9A120B034280036BA46 /* imgui_impl_osx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_osx.h; path = ../imgui_impl_osx.h; sourceTree = ""; }; + 4080A99E20B034280036BA46 /* imgui_impl_opengl2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_impl_opengl2.cpp; path = ../../backends/imgui_impl_opengl2.cpp; sourceTree = ""; }; + 4080A99F20B034280036BA46 /* imgui_impl_osx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_osx.mm; path = ../../backends/imgui_impl_osx.mm; sourceTree = ""; }; + 4080A9A020B034280036BA46 /* imgui_impl_opengl2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_opengl2.h; path = ../../backends/imgui_impl_opengl2.h; sourceTree = ""; }; + 4080A9A120B034280036BA46 /* imgui_impl_osx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_osx.h; path = ../../backends/imgui_impl_osx.h; sourceTree = ""; }; 4080A9A520B0343C0036BA46 /* imgui_internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_internal.h; path = ../../imgui_internal.h; sourceTree = ""; }; 4080A9A620B0343C0036BA46 /* imgui_demo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_demo.cpp; path = ../../imgui_demo.cpp; sourceTree = ""; }; 4080A9A720B0343C0036BA46 /* imgui.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui.cpp; path = ../../imgui.cpp; sourceTree = ""; }; diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index c7ccc4ae..eaf55dae 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -2,8 +2,8 @@ // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. #include "imgui.h" -#include "../imgui_impl_osx.h" -#include "../imgui_impl_opengl2.h" +#include "../../backends/imgui_impl_osx.h" +#include "../../backends/imgui_impl_opengl2.h" #include #import #import diff --git a/examples/example_emscripten/Makefile b/examples/example_emscripten/Makefile index 9833270e..967d61fb 100644 --- a/examples/example_emscripten/Makefile +++ b/examples/example_emscripten/Makefile @@ -16,9 +16,10 @@ CC = emcc CXX = em++ EXE = example_emscripten.html +IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += ../imgui_impl_sdl.cpp ../imgui_impl_opengl3.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) @@ -51,7 +52,7 @@ endif ## FINAL BUILD FLAGS ##--------------------------------------------------------------------- -CPPFLAGS += -I../ -I../../ +CPPFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends #CPPFLAGS += -g CPPFLAGS += -Wall -Wformat -Os CPPFLAGS += $(EMS) @@ -65,10 +66,10 @@ LDFLAGS += --shell-file shell_minimal.html %.o:%.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< %.o:../libs/gl3w/GL/%.c diff --git a/examples/example_glfw_metal/Makefile b/examples/example_glfw_metal/Makefile index 35f17737..4b7599eb 100644 --- a/examples/example_glfw_metal/Makefile +++ b/examples/example_glfw_metal/Makefile @@ -7,31 +7,32 @@ #CXX = clang++ EXE = example_glfw_metal +IMGUI_DIR = ../.. SOURCES = main.mm -SOURCES += ../imgui_impl_glfw.cpp ../imgui_impl_metal.mm -SOURCES += ../../imgui.cpp ../../imgui_widgets.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_metal.mm OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore LIBS += -L/usr/local/lib -lglfw -CXXFLAGS = -I../ -I../../ -I/usr/local/include +CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include CXXFLAGS += -Wall -Wformat CFLAGS = $(CXXFLAGS) %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.mm +%.o:%.mm $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< -%.o:%.mm +%.o:$(IMGUI_DIR)/backends/%.mm $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< all: $(EXE) diff --git a/examples/example_glfw_opengl2/Makefile b/examples/example_glfw_opengl2/Makefile index 38f865ba..6bcbca5e 100644 --- a/examples/example_glfw_opengl2/Makefile +++ b/examples/example_glfw_opengl2/Makefile @@ -15,13 +15,14 @@ #CXX = clang++ EXE = example_glfw_opengl2 +IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += ../imgui_impl_glfw.cpp ../imgui_impl_opengl2.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I../ -I../../ +CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = @@ -63,10 +64,10 @@ endif %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< all: $(EXE) diff --git a/examples/example_glfw_opengl2/build_win32.bat b/examples/example_glfw_opengl2/build_win32.bat index 538d9a52..ce08445d 100644 --- a/examples/example_glfw_opengl2/build_win32.bat +++ b/examples/example_glfw_opengl2/build_win32.bat @@ -1,3 +1,3 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include *.cpp ..\imgui_impl_opengl2.cpp ..\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeDebug/example_glfw_opengl2.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include *.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeDebug/example_glfw_opengl2.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index b265fea0..35ffdfd9 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -90,7 +90,7 @@ Level4 Disabled - ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) true @@ -104,7 +104,7 @@ Level4 Disabled - ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) true @@ -120,7 +120,7 @@ MaxSpeed true true - ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) false @@ -140,7 +140,7 @@ MaxSpeed true true - ..\..;..;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) false @@ -159,16 +159,16 @@ - - + + - - + + @@ -177,4 +177,4 @@ - \ No newline at end of file + diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters index b7a37e68..4b4dd526 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters @@ -22,14 +22,14 @@ imgui - - sources + + imgui - + sources - - imgui + + sources @@ -42,10 +42,10 @@ imgui - + sources - + sources @@ -55,4 +55,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_glfw_opengl3/Makefile b/examples/example_glfw_opengl3/Makefile index 0e7faa12..1524ac6f 100644 --- a/examples/example_glfw_opengl3/Makefile +++ b/examples/example_glfw_opengl3/Makefile @@ -15,13 +15,14 @@ #CXX = clang++ EXE = example_glfw_opengl3 +IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += ../imgui_impl_glfw.cpp ../imgui_impl_opengl3.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I../ -I../../ +CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = @@ -93,10 +94,10 @@ endif %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< %.o:../libs/gl3w/GL/%.c diff --git a/examples/example_glfw_opengl3/build_win32.bat b/examples/example_glfw_opengl3/build_win32.bat index e5c15c53..eb755d61 100644 --- a/examples/example_glfw_opengl3/build_win32.bat +++ b/examples/example_glfw_opengl3/build_win32.bat @@ -1,3 +1,3 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include /I ..\libs\gl3w *.cpp ..\imgui_impl_glfw.cpp ..\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/example_glfw_opengl3.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include /I ..\libs\gl3w *.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/example_glfw_opengl3.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 47d25380..9c823935 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -90,7 +90,7 @@ Level4 Disabled - ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true @@ -104,7 +104,7 @@ Level4 Disabled - ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true @@ -120,7 +120,7 @@ MaxSpeed true true - ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false @@ -140,7 +140,7 @@ MaxSpeed true true - ..\..;..;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;..\libs\glfw\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false @@ -159,8 +159,8 @@ - - + + @@ -168,8 +168,8 @@ - - + + @@ -180,4 +180,4 @@ - \ No newline at end of file + diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters index efb570ce..000e8d28 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters @@ -28,14 +28,14 @@ imgui - - sources + + imgui - + sources - - imgui + + sources @@ -54,10 +54,10 @@ imgui - + sources - + sources @@ -67,4 +67,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_glfw_vulkan/CMakeLists.txt b/examples/example_glfw_vulkan/CMakeLists.txt index 023d791b..22e17a20 100644 --- a/examples/example_glfw_vulkan/CMakeLists.txt +++ b/examples/example_glfw_vulkan/CMakeLists.txt @@ -39,5 +39,5 @@ include_directories(${GLFW_DIR}/deps) file(GLOB sources *.cpp) -add_executable(example_glfw_vulkan ${sources} ${IMGUI_DIR}/examples/imgui_impl_glfw.cpp ${IMGUI_DIR}/examples/imgui_impl_vulkan.cpp ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_widgets.cpp) +add_executable(example_glfw_vulkan ${sources} ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp ${IMGUI_DIR}/backends/imgui_impl_vulkan.cpp ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_widgets.cpp) target_link_libraries(example_glfw_vulkan ${LIBRARIES}) diff --git a/examples/example_glfw_vulkan/build_win32.bat b/examples/example_glfw_vulkan/build_win32.bat index 0d991b9d..ad53cb07 100644 --- a/examples/example_glfw_vulkan/build_win32.bat +++ b/examples/example_glfw_vulkan/build_win32.bat @@ -1,7 +1,7 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\imgui_impl_vulkan.cpp ..\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeDebug/example_glfw_vulkan.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeDebug/example_glfw_vulkan.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib mkdir Release -cl /nologo /Zi /MD /Ox /Oi /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\imgui_impl_vulkan.cpp ..\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeRelease/example_glfw_vulkan.exe /FoRelease/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib +cl /nologo /Zi /MD /Ox /Oi /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeRelease/example_glfw_vulkan.exe /FoRelease/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib diff --git a/examples/example_glfw_vulkan/build_win64.bat b/examples/example_glfw_vulkan/build_win64.bat index ddedf597..d6b24b5b 100644 --- a/examples/example_glfw_vulkan/build_win64.bat +++ b/examples/example_glfw_vulkan/build_win64.bat @@ -1,7 +1,7 @@ @REM Build for Visual Studio compiler. Run your copy of amd64/vcvars32.bat to setup 64-bit command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\imgui_impl_vulkan.cpp ..\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeDebug/example_glfw_vulkan.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeDebug/example_glfw_vulkan.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib mkdir Release -cl /nologo /Zi /MD /Ox /Oi /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\imgui_impl_vulkan.cpp ..\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeRelease/example_glfw_vulkan.exe /FoRelease/ /link /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib +cl /nologo /Zi /MD /Ox /Oi /I .. /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeRelease/example_glfw_vulkan.exe /FoRelease/ /link /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index 9e2c9b38..d9418579 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -90,7 +90,7 @@ Level4 Disabled - ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) true @@ -104,7 +104,7 @@ Level4 Disabled - ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) true @@ -120,7 +120,7 @@ MaxSpeed true true - ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) false @@ -140,7 +140,7 @@ MaxSpeed true true - ..\..;..;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) false @@ -159,16 +159,16 @@ - - + + - - + + @@ -177,4 +177,4 @@ - \ No newline at end of file + diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters index 98a445d4..43f5f5b6 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters @@ -10,6 +10,9 @@ + + sources + imgui @@ -19,18 +22,15 @@ imgui - - sources + + imgui - + sources - + sources - - imgui - @@ -42,10 +42,10 @@ imgui - + sources - + sources @@ -55,4 +55,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_glut_opengl2/Makefile b/examples/example_glut_opengl2/Makefile index 70576b8f..21984cec 100644 --- a/examples/example_glut_opengl2/Makefile +++ b/examples/example_glut_opengl2/Makefile @@ -10,13 +10,14 @@ #CXX = clang++ EXE = example_glut_opengl2 +IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += ../imgui_impl_glut.cpp ../imgui_impl_opengl2.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glut.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I../ -I../../ +CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = @@ -58,10 +59,10 @@ endif %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< all: $(EXE) diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index 9a239516..736e6e7a 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -159,16 +159,16 @@ - - + + - - + + @@ -177,4 +177,4 @@ - \ No newline at end of file + diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters index 290d43d7..8f8fd955 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters @@ -22,14 +22,14 @@ imgui - - sources + + imgui - + sources - - imgui + + sources @@ -42,10 +42,10 @@ imgui - + sources - + sources diff --git a/examples/example_marmalade/marmalade_example.mkb b/examples/example_marmalade/marmalade_example.mkb index 4c94cc01..bf5d1b86 100644 --- a/examples/example_marmalade/marmalade_example.mkb +++ b/examples/example_marmalade/marmalade_example.mkb @@ -17,8 +17,8 @@ options includepaths { - .. ../.. + ../../backends } subprojects @@ -38,9 +38,9 @@ files ../../imgui.h ../../imgui_internal.h - ["imgui", "Marmalade backend"] - ../imgui_impl_marmalade.h - ../imgui_impl_marmalade.cpp + ["imgui","Marmalade backend"] + ../../backends/imgui_impl_marmalade.h + ../../backends/imgui_impl_marmalade.cpp main.cpp } diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index d6a702ad..25cecd82 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -11,12 +11,13 @@ WITH_EXTRA_WARNINGS ?= 0 WITH_FREETYPE ?= 0 EXE = example_null +IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS += -I../ -I../../ +CXXFLAGS += -I$(IMGUI_DIR) CXXFLAGS += -g -Wall -Wformat LIBS = @@ -28,7 +29,7 @@ endif # We use the WITH_FREETYPE flag on our CI setup to test compiling misc/freetype/imgui_freetype.cpp # (only supported on Linux, and note that the imgui_freetype code currently won't be executed) ifeq ($(WITH_FREETYPE), 1) - SOURCES += ../../misc/freetype/imgui_freetype.cpp + SOURCES += $(IMGUI_DIR)/misc/freetype/imgui_freetype.cpp CXXFLAGS += $(shell pkg-config --cflags freetype2) LIBS += $(shell pkg-config --libs freetype2) endif @@ -71,13 +72,13 @@ endif %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../misc/freetype/%.cpp +%.o:$(IMGUI_DIR)/misc/freetype/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< all: $(EXE) diff --git a/examples/example_sdl_directx11/build_win32.bat b/examples/example_sdl_directx11/build_win32.bat index 8fc702bb..b0b4d88a 100644 --- a/examples/example_sdl_directx11/build_win32.bat +++ b/examples/example_sdl_directx11/build_win32.bat @@ -2,7 +2,7 @@ set OUT_DIR=Debug set OUT_EXE=example_sdl_directx11 set INCLUDES=/I.. /I..\.. /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" -set SOURCES=main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_dx11.cpp ..\..\imgui*.cpp +set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp set LIBS=/libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib mkdir %OUT_DIR% cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj index 804bd500..690c660d 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -91,7 +91,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -105,7 +105,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -121,7 +121,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false @@ -141,7 +141,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false @@ -160,16 +160,16 @@ - - + + - - + + @@ -178,4 +178,4 @@ - \ No newline at end of file + diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters index 879f0dbe..d1f0876e 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters @@ -18,10 +18,10 @@ imgui - + sources - + sources @@ -38,13 +38,13 @@ imgui - - sources - imgui - + + sources + + sources @@ -54,4 +54,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_sdl_metal/Makefile b/examples/example_sdl_metal/Makefile index 9d0d5e0f..53c8aabb 100644 --- a/examples/example_sdl_metal/Makefile +++ b/examples/example_sdl_metal/Makefile @@ -7,16 +7,17 @@ #CXX = clang++ EXE = example_sdl_metal +IMGUI_DIR = ../.. SOURCES = main.mm -SOURCES += ../imgui_impl_sdl.cpp ../imgui_impl_metal.mm -SOURCES += ../../imgui.cpp ../../imgui_widgets.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_metal.mm OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore LIBS += `sdl2-config --libs` LIBS += -L/usr/local/lib -CXXFLAGS = -I../ -I../../ -I/usr/local/include +CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include CXXFLAGS += `sdl2-config --cflags` CXXFLAGS += -Wall -Wformat CFLAGS = $(CXXFLAGS) @@ -24,16 +25,16 @@ CFLAGS = $(CXXFLAGS) %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.mm +%.o:%.mm $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< -%.o:%.mm +%.o:$(IMGUI_DIR)/backends/%.mm $(CXX) $(CXXFLAGS) -ObjC++ -fobjc-weak -fobjc-arc -c -o $@ $< all: $(EXE) diff --git a/examples/example_sdl_opengl2/Makefile b/examples/example_sdl_opengl2/Makefile index 9c57337e..2da745d7 100644 --- a/examples/example_sdl_opengl2/Makefile +++ b/examples/example_sdl_opengl2/Makefile @@ -15,13 +15,14 @@ #CXX = clang++ EXE = example_sdl_opengl2 +IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += ../imgui_impl_sdl.cpp ../imgui_impl_opengl2.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I../ -I../../ +CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = @@ -62,10 +63,10 @@ endif %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< all: $(EXE) diff --git a/examples/example_sdl_opengl2/README.md b/examples/example_sdl_opengl2/README.md index 60a5e377..00900638 100644 --- a/examples/example_sdl_opengl2/README.md +++ b/examples/example_sdl_opengl2/README.md @@ -5,21 +5,21 @@ ``` set SDL2_DIR=path_to_your_sdl2_folder -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console # ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries # or for 64-bit: -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console ``` - On Linux and similar Unixes ``` -c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../imgui_impl_sdl.cpp ../imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL +c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL ``` - On Mac OS X ``` brew install sdl2 -c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../imgui_impl_sdl.cpp ../imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl +c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl ``` diff --git a/examples/example_sdl_opengl2/build_win32.bat b/examples/example_sdl_opengl2/build_win32.bat index d209b2a2..71157f5f 100644 --- a/examples/example_sdl_opengl2/build_win32.bat +++ b/examples/example_sdl_opengl2/build_win32.bat @@ -2,7 +2,7 @@ set OUT_DIR=Debug set OUT_EXE=example_sdl_opengl2 set INCLUDES=/I.. /I..\.. /I%SDL2_DIR%\include -set SOURCES=main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl2.cpp ..\..\imgui*.cpp +set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp set LIBS=/libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib mkdir %OUT_DIR% cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index 83a6a8a0..b8eb9219 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -90,7 +90,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -104,7 +104,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -120,7 +120,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false @@ -140,7 +140,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false @@ -159,16 +159,16 @@ - - + + - - + + @@ -177,4 +177,4 @@ - \ No newline at end of file + diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters index e0c1bf2e..65acfe43 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters @@ -22,14 +22,14 @@ sources - - sources + + imgui - + sources - - imgui + + sources @@ -42,10 +42,10 @@ imgui - + sources - + sources @@ -55,4 +55,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index e8009a4c..b408ce35 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -15,13 +15,14 @@ #CXX = clang++ EXE = example_sdl_opengl3 +IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += ../imgui_impl_sdl.cpp ../imgui_impl_opengl3.cpp -SOURCES += ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp ../../imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I../ -I../../ +CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = @@ -92,10 +93,10 @@ endif %.o:%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../%.cpp +%.o:$(IMGUI_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< -%.o:../../%.cpp +%.o:$(IMGUI_DIR)/backends/%.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< %.o:../libs/gl3w/GL/%.c diff --git a/examples/example_sdl_opengl3/README.md b/examples/example_sdl_opengl3/README.md index ec21fb78..edeafec3 100644 --- a/examples/example_sdl_opengl3/README.md +++ b/examples/example_sdl_opengl3/README.md @@ -5,21 +5,21 @@ ``` set SDL2_DIR=path_to_your_sdl2_folder -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include /I..\libs\gl3w main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/example_sdl_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include /I..\libs\gl3w main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/example_sdl_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console # ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries # or for 64-bit: -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include /I..\libs\gl3w main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/example_sdl_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include /I..\libs\gl3w main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/example_sdl_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console ``` - On Linux and similar Unixes ``` -c++ `sdl2-config --cflags` -I .. -I ../.. -I ../libs/gl3w main.cpp ../imgui_impl_sdl.cpp ../imgui_impl_opengl3.cpp ../../imgui*.cpp ../libs/gl3w/GL/gl3w.c `sdl2-config --libs` -lGL -ldl +c++ `sdl2-config --cflags` -I .. -I ../.. -I ../libs/gl3w main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp ../libs/gl3w/GL/gl3w.c `sdl2-config --libs` -lGL -ldl ``` - On Mac OS X ``` brew install sdl2 -c++ `sdl2-config --cflags` -I .. -I ../.. -I ../libs/gl3w main.cpp ../imgui_impl_sdl.cpp ../imgui_impl_opengl3.cpp ../../imgui*.cpp ../libs/gl3w/GL/gl3w.c `sdl2-config --libs` -framework OpenGl -framework CoreFoundation +c++ `sdl2-config --cflags` -I .. -I ../.. -I ../libs/gl3w main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp ../libs/gl3w/GL/gl3w.c `sdl2-config --libs` -framework OpenGl -framework CoreFoundation ``` diff --git a/examples/example_sdl_opengl3/build_win32.bat b/examples/example_sdl_opengl3/build_win32.bat index ce105602..d13cc940 100644 --- a/examples/example_sdl_opengl3/build_win32.bat +++ b/examples/example_sdl_opengl3/build_win32.bat @@ -2,7 +2,7 @@ set OUT_DIR=Debug set OUT_EXE=example_sdl_opengl3 set INCLUDES=/I.. /I..\.. /I%SDL2_DIR%\include /I..\libs\gl3w -set SOURCES=main.cpp ..\imgui_impl_sdl.cpp ..\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c +set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c set LIBS=/libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib mkdir %OUT_DIR% cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj index 54aaa796..c8d67f98 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj @@ -90,7 +90,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true @@ -104,7 +104,7 @@ Level4 Disabled - ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) true @@ -120,7 +120,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false @@ -140,7 +140,7 @@ MaxSpeed true true - ..\..;..;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%SDL2_DIR%\include;..\libs\gl3w;%(AdditionalIncludeDirectories) false @@ -159,8 +159,8 @@ - - + + @@ -168,8 +168,8 @@ - - + + diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters index fbef18ac..ade2c96c 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters @@ -28,10 +28,10 @@ gl3w - + sources - + sources @@ -54,10 +54,10 @@ gl3w - + sources - + sources @@ -67,4 +67,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj index ac701a2a..84cc94b4 100644 --- a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj +++ b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj @@ -90,7 +90,7 @@ Level4 Disabled - ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -104,7 +104,7 @@ Level4 Disabled - ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) true @@ -120,7 +120,7 @@ MaxSpeed true true - ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false @@ -140,7 +140,7 @@ MaxSpeed true true - ..\..;..;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false @@ -159,16 +159,16 @@ - - + + - - + + diff --git a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj.filters b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj.filters index 6f082524..8a6b48e3 100644 --- a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj.filters +++ b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj.filters @@ -19,13 +19,13 @@ imgui - + sources sources - + sources @@ -42,10 +42,10 @@ imgui - + sources - + sources diff --git a/examples/example_win32_directx10/build_win32.bat b/examples/example_win32_directx10/build_win32.bat index d79cb8f7..75cb837e 100644 --- a/examples/example_win32_directx10/build_win32.bat +++ b/examples/example_win32_directx10/build_win32.bat @@ -1,4 +1,4 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" /D UNICODE /D _UNICODE *.cpp ..\imgui_impl_win32.cpp ..\imgui_impl_dx10.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx10.exe /FoDebug/ /link /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d10.lib d3dcompiler.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" /D UNICODE /D _UNICODE *.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\backends\imgui_impl_dx10.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx10.exe /FoDebug/ /link /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d10.lib d3dcompiler.lib diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 5c3aa69f..4a24dc1b 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -86,7 +86,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); true @@ -99,7 +99,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); true @@ -114,7 +114,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); false @@ -132,7 +132,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); false @@ -148,16 +148,16 @@ - - + + - - + + diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters b/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters index 97620028..16107c9c 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters @@ -18,10 +18,10 @@ imgui - + sources - + sources @@ -38,10 +38,10 @@ imgui - + sources - + sources diff --git a/examples/example_win32_directx11/build_win32.bat b/examples/example_win32_directx11/build_win32.bat index 05e6a6f6..cbe96b04 100644 --- a/examples/example_win32_directx11/build_win32.bat +++ b/examples/example_win32_directx11/build_win32.bat @@ -1,4 +1,4 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" /D UNICODE /D _UNICODE *.cpp ..\imgui_impl_dx11.cpp ..\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx11.exe /FoDebug/ /link /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" /D UNICODE /D _UNICODE *.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx11.exe /FoDebug/ /link /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index bcb71bc4..e9945db9 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -85,7 +85,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); true @@ -98,7 +98,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); true @@ -113,7 +113,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); false @@ -131,7 +131,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories); + ..\..;..\..\backends;%(AdditionalIncludeDirectories); false @@ -147,16 +147,16 @@ - - + + - - + + @@ -166,4 +166,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters b/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters index 1df6a0c4..6956b586 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters @@ -18,10 +18,10 @@ imgui - + sources - + sources @@ -38,14 +38,14 @@ imgui - - sources + + imgui - + sources - - imgui + + sources @@ -54,4 +54,4 @@ sources - \ No newline at end of file + diff --git a/examples/example_win32_directx12/build_win32.bat b/examples/example_win32_directx12/build_win32.bat index 097295a8..5556dfef 100644 --- a/examples/example_win32_directx12/build_win32.bat +++ b/examples/example_win32_directx12/build_win32.bat @@ -1,5 +1,5 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @REM Important: to build on 32-bit systems, the DX12 backends needs '#define ImTextureID ImU64', so we pass it here. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /D ImTextureID=ImU64 /D UNICODE /D _UNICODE *.cpp ..\imgui_impl_dx12.cpp ..\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx12.exe /FoDebug/ /link d3d12.lib d3dcompiler.lib dxgi.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /D ImTextureID=ImU64 /D UNICODE /D _UNICODE *.cpp ..\..\backends\imgui_impl_dx12.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx12.exe /FoDebug/ /link d3d12.lib d3dcompiler.lib dxgi.lib diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj index f03bf760..452328ce 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj @@ -86,7 +86,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) @@ -100,7 +100,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) @@ -116,7 +116,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) @@ -134,7 +134,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories) + ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) @@ -150,16 +150,16 @@ - - + + - - + + diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters b/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters index 28a25572..754c2954 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters @@ -18,10 +18,10 @@ imgui - + sources - + sources @@ -38,10 +38,10 @@ imgui - + sources - + sources diff --git a/examples/example_win32_directx9/build_win32.bat b/examples/example_win32_directx9/build_win32.bat index 4db27653..13781036 100644 --- a/examples/example_win32_directx9/build_win32.bat +++ b/examples/example_win32_directx9/build_win32.bat @@ -1,3 +1,3 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I .. /I ..\.. /I "%DXSDK_DIR%/Include" /D UNICODE /D _UNICODE *.cpp ..\imgui_impl_dx9.cpp ..\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx9.exe /FoDebug/ /link /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d9.lib +cl /nologo /Zi /MD /I .. /I ..\.. /I "%DXSDK_DIR%/Include" /D UNICODE /D _UNICODE *.cpp ..\..\backends\imgui_impl_dx9.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp /FeDebug/example_win32_directx9.exe /FoDebug/ /link /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d9.lib diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index 25bdd859..a33833b3 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -86,7 +86,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; true @@ -99,7 +99,7 @@ Level4 Disabled - ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; true @@ -114,7 +114,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; false @@ -132,7 +132,7 @@ MaxSpeed true true - ..\..;..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; false @@ -149,16 +149,16 @@ - - + + - - + + diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters b/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters index 914cd260..2a684553 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters @@ -22,10 +22,10 @@ imgui - + sources - + sources @@ -42,10 +42,10 @@ imgui - + sources - + sources From a2d845f9dda5f591f57d79158db1c7548c4ce2e9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 12 Oct 2020 18:57:04 +0200 Subject: [PATCH 313/959] Moving backends code from examples/ to backends/ (step 4: update documentation, much improvement) --- backends/README.txt | 154 ++++++++++++++++++++++++++ docs/CHANGELOG.txt | 1 + examples/README.txt | 263 ++++++++++++++++++-------------------------- 3 files changed, 262 insertions(+), 156 deletions(-) create mode 100644 backends/README.txt diff --git a/backends/README.txt b/backends/README.txt new file mode 100644 index 00000000..9dd9dfcf --- /dev/null +++ b/backends/README.txt @@ -0,0 +1,154 @@ +----------------------------------------------------------------------- + dear imgui, v1.80 WIP + Backends +----------------------------------------------------------------------- + (See docs/ and examples/ for more documentation) +----------------------------------------------------------------------- + +This folder contains backends for popular platforms/graphics API, which you can use in +your application or engine to easily integrate Dear ImGui. + +- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing. + e.g. Windows (imgui_impl_win32.cpp), GLFW (imgui_impl_glfw.cpp), SDL2 (imgui_impl_sdl.cpp), etc. + +- The 'Renderer' backends are in charge of: creating atlas texture, rendering imgui draw data. + e.g. DirectX11 (imgui_impl_dx11.cpp), OpenGL/WebGL (imgui_impl_opengl3.cpp), Vulkan (imgui_impl_vulkan.cpp), etc. + +- For some high-level frameworks, a single backend usually handle both 'Platform' and 'Renderer' parts. + e.g. Allegro 5 (imgui_impl_allegro5.cpp), Marmalade (imgui_impl_marmalade5.cpp). + +An application usually combines 1 Platform backend + 1 Renderer backend + main ImGui sources. +For example, the example_win32_directx11/ application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. +See examples/README.txt for details. + + +--------------------------------------- + WHAT ARE BACKENDS? +--------------------------------------- + +Dear ImGui is highly portable and only requires a few things to run and render, typically: + + - Required: providing mouse/keyboard inputs. + - Required: uploading the font atlas texture into graphics memory. + - Required: rendering indexed textured triangles with a clipping rectangle. + + Extra features are opt-in, our backends try to support as many as possible: + + - Optional: custom texture binding support. + - Optional: clipboard support. + - Optional: gamepad support. + - Optional: mouse cursor shape support. + - Optional: IME support. + - Optional: multi-viewports support. + etc. + +This is essentially what the backends in this folder are providing + obligatory portability cruft. + +It is important to understand the difference between the core Dear ImGui library (files in the root folder) +and backends which we are describing here (backends/ folder). + +- Some issues may only be backend or platform specific. +- You should be able to write backends for pretty much any platform and any 3D graphics API. + e.g. get creative and have your backend perform rendering remotely, on a different machine + than the one running Dear ImGui, etc. + + +----------------------------------------------------------------------- + USING A CUSTOM ENGINE? +----------------------------------------------------------------------- + +You will likely be tempted to start by rewrite your own backend using your own custom/high-level facilities... +Think twice! + +If you are new to Dear ImGui, first try using the existing backends as-is. +You will save lots of time integrating the library. +You can LATER decide to rewrite yourself a custom backend if you really need to. +In most situations, custom backends have less features and more bugs than the standard backends we provide. +If you want portability, you can use multiple backends and choose between them either at compile time +or at runtime. + +Example A: your engine is built over Windows + DirectX11 but you have your own high-level rendering +system layered over DirectX11. + - Suggestion: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. + Once it works, if you really need it you can replace the imgui_impl_dx11.cpp code with a + custom renderer using your own rendering functions, and keep using the standard Win32 code etc. + +Example B: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, Vulkan respectively. + - Suggestion: use multiple generic backends! + Once it works, if you really need it you can replace parts of backends with your own abstractions. + +Example C: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch), +and you have high-level systems everywhere. + - Suggestion: try using a non-portable backend first (e.g. win32 + underlying graphics API) to get + your desktop builds working first. This will get you running faster and get your acquainted with + how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API. + +Also: +The multi-viewports feature of the 'docking' branch allows Dear ImGui windows to be seamlessly detached +from the main application window. This is achieved using an extra layer to the Platform and Renderer +backends, which allows Dear ImGui to communicate platform-specific requests. +Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult +than supporting single-viewport. +If you decide to use unmodified imgui_impl_xxxx.cpp files, you can automatically benefit from +improvements and fixes related to viewports and platform windows without extra work on your side. + + +--------------------------------------- + LIST OF BACKENDS +--------------------------------------- + +List of Platforms Backends in this repository: + + imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ + imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) + imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org + imgui_impl_win32.cpp ; Win32 native API (Windows) + imgui_impl_glut.cpp ; GLUT/FreeGLUT (absolutely not recommended in 2020!) + +List of Renderer Backends in this repository: + + imgui_impl_dx9.cpp ; DirectX9 + imgui_impl_dx10.cpp ; DirectX10 + imgui_impl_dx11.cpp ; DirectX11 + imgui_impl_dx12.cpp ; DirectX12 + imgui_impl_metal.mm ; Metal (with ObjC) + imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context) + imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) + imgui_impl_vulkan.cpp ; Vulkan + +Emscripten is also supported. +The example_emscripten/ app uses imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp, but other combos are possible. + +List of high-level Frameworks Backends in this repository: (combine Platform + Renderer) + + imgui_impl_allegro5.cpp + imgui_impl_marmalade.cpp + +Backends for third-party frameworks, graphics API or other programming languages: + + https://github.com/ocornut/imgui/wiki/Bindings + + (AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, + GML/Game Maker Studio2, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, + Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, px_render, Qt/QtDirect3D, SFML, Sokol, + Unreal Engine 4, vtk, Win32 GDI, etc.) + + +--------------------------------------- + RECOMMENDED BACKENDS +--------------------------------------- + +Recommended platform/frameworks for portable applications: + + Library: GLFW + Webpage: https://github.com/glfw/glfw + Backend: imgui_impl_glfw.cpp + + Library: SDL2 + Webpage: https://www.libsdl.org + Backend: imgui_impl_sdl.cpp + + Library: Sokol (lower-level than GLFW/SDL) + Webpage: https://github.com/floooh/sokol + Backend: Use util/sokol_imgui.h in Sokol repository. + diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9af626e4..a01917de 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -53,6 +53,7 @@ Breaking Changes: Other Changes: +- Docs: Split Backends and Examples README and improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. diff --git a/examples/README.txt b/examples/README.txt index 71700d8f..45f0ae66 100644 --- a/examples/README.txt +++ b/examples/README.txt @@ -1,33 +1,14 @@ ----------------------------------------------------------------------- dear imgui, v1.80 WIP + Examples applications ----------------------------------------------------------------------- - examples/README.txt - (This is the README file for the examples/ folder. See docs/ for more documentation) + (See docs/ and backends/ for more documentation) ----------------------------------------------------------------------- -Dear ImGui is highly portable and only requires a few things to run and render: +This folder contains example applications (standalone, ready-to-build) for variety of +platforms and graphics APIs. They all use standard backends from the backends/ folder. - - Providing mouse/keyboard inputs - - Uploading the font atlas texture into graphics memory - - Providing a render function to render indexed textured triangles - - Optional: clipboard support, mouse cursor supports, Windows IME support, etc. - -This is essentially what the example backends in this folder are providing + obligatory portability cruft. - -It is important to understand the difference between the core Dear ImGui library (files in the root folder) -and examples backends which we are describing here (examples/ folder). -You should be able to write backends for pretty much any platform and any 3D graphics API. With some extra -effort you can even perform the rendering remotely, on a different machine than the one running the logic. - -This folder contains two things: - - - Example backends for popular platforms/graphics API, which you can use as is or adapt for your own use. - They are the imgui_impl_XXXX files found in the examples/ folder. - - - Example applications (standalone, ready-to-build) using the aforementioned backends. - They are the in the XXXX_example/ sub-folders. - -You can find binaries of some of those example applications at: +You can find Windows binaries for some of those example applications at: http://www.dearimgui.org/binaries @@ -35,144 +16,72 @@ You can find binaries of some of those example applications at: GETTING STARTED --------------------------------------- - - Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. - Please read the comments and instruction at the top of each file. - Please read FAQ at http://www.dearimgui.org/faq - - - If you are using of the backend provided here, you can add the imgui_impl_xxx.cpp/h files - to your project and use them unmodified. Each imgui_impl_xxxx.cpp comes with its own individual - Changelog at the top of the .cpp files, so if you want to update them later it will be easier to - catch up with what changed. - - - Dear ImGui has no particular extra lag for most behaviors, e.g. the value of 'io.MousePos' provided in - NewFrame() will result at the time of EndFrame()/Render() in a moved windows rendered following that mouse - movement. At 60 FPS your experience should be pleasant. - However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated - path and will feel smoother than the majority of contents rendererd via regular graphics API (including, - but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane as - the mouse, that disconnect may be jarring to particularly sensitive users. - You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor - using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a - regularly rendered software cursor. - However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at - all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ - when an interactive drag is in progress. - Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. - If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple - drawing a flat 2D shape directly under the mouse cursor. - - ---------------------------------------- - EXAMPLE BACKENDS ---------------------------------------- - -Most the example backends are split in 2 parts: - - - The "Platform" backends, in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing. - Examples: Windows (imgui_impl_win32.cpp), GLFW (imgui_impl_glfw.cpp), SDL2 (imgui_impl_sdl.cpp), etc. - - - The "Renderer" backends, in charge of: creating the main font texture, rendering imgui draw data. - Examples: DirectX11 (imgui_impl_dx11.cpp), GL3 (imgui_impl_opengl3.cpp), Vulkan (imgui_impl_vulkan.cpp), etc. - - - The example _applications_ usually combine 1 platform + 1 renderer backend to create a working program. - Examples: the example_win32_directx11/ application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. - - - Some backends for higher level frameworks carry both "Platform" and "Renderer" parts in one file. - This is the case for Allegro 5 (imgui_impl_allegro5.cpp), Marmalade (imgui_impl_marmalade5.cpp). - - - If you use your own engine, you may decide to use some of existing backends and/or rewrite some using - your own API. As a recommendation, if you are new to Dear ImGui, try using the existing backend as-is - first, before moving on to rewrite some of the code. Although it is tempting to rewrite both of the - imgui_impl_xxxx files to fit under your coding style, consider that it is not necessary! - In fact, if you are new to Dear ImGui, rewriting them will almost always be harder. - - Example: your engine is built over Windows + DirectX11 but you have your own high-level rendering - system layered over DirectX11. - Suggestion: step 1: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. - Once this work, _if_ you want you can replace the imgui_impl_dx11.cpp code with a custom renderer - using your own functions, etc. - Please consider using the backends to the lower-level platform/graphics API as-is. - - Example: your engine is multi-platform (consoles, phones, etc.), you have high-level systems everywhere. - Suggestion: step 1: try using a non-portable backend first (e.g. win32 + underlying graphics API)! - This is counter-intuitive, but this will get you running faster! Once you better understand how imgui - works and is bound, you can rewrite the code using your own systems. - - - Road-map: Dear ImGui 1.80 (WIP currently in the "docking" branch) will allows imgui windows to be - seamlessly detached from the main application window. This is achieved using an extra layer to the - platform and renderer backends, which allows Dear ImGui to communicate platform-specific requests. - If you decide to use unmodified imgui_impl_xxxx.cpp files, you will automatically benefit from - improvements and fixes related to viewports and platform windows without extra work on your side. - - -List of Platforms Backends in this repository: - - imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ - imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) - imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org - imgui_impl_win32.cpp ; Win32 native API (Windows) - imgui_impl_glut.cpp ; GLUT/FreeGLUT (absolutely not recommended in 2020!) - -List of Renderer Backends in this repository: - - imgui_impl_dx9.cpp ; DirectX9 - imgui_impl_dx10.cpp ; DirectX10 - imgui_impl_dx11.cpp ; DirectX11 - imgui_impl_dx12.cpp ; DirectX12 - imgui_impl_metal.mm ; Metal (with ObjC) - imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context) - imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) - imgui_impl_vulkan.cpp ; Vulkan - -List of high-level Frameworks Backends in this repository: (combine Platform + Renderer) - - imgui_impl_allegro5.cpp - imgui_impl_marmalade.cpp - -Note that Dear ImGui works with Emscripten. The examples_emscripten/ app uses imgui_impl_sdl.cpp and -imgui_impl_opengl3.cpp, but other combinations are possible. - -Third-party framework, graphics API and languages backends are listed at: - - https://github.com/ocornut/imgui/wiki/Bindings - -Including backends for: - - AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, - GML/Game Maker Studio2, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, - Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, px_render, Qt/QtDirect3D, SFML, Sokol, - Unreal Engine 4, vtk, Win32 GDI, etc. - -Not sure which to use? -Recommended platform/frameworks: - - GLFW https://github.com/glfw/glfw Use imgui_impl_glfw.cpp - SDL2 https://www.libsdl.org Use imgui_impl_sdl.cpp - Sokol https://github.com/floooh/sokol Use util/sokol_imgui.h in Sokol repository. - -Those will allow you to create portable applications and will solve and abstract away many issues. +Integration in a typical existing application, should take <20 lines when using standard backends. + + At initialization: + call ImGui::CreateContext() + call ImGui_ImplXXXX_Init() for each backend. + + At the beginning of your frame: + call ImGui_ImplXXXX_NewFrame() for each backend. + call ImGui::NewFrame() + + At the end of your frame: + call ImGui::Render() + call ImGui_ImplXXXX_RenderDrawData() for your Renderer backend. + + At shutdown: + call ImGui_ImplXXXX_Shutdown() for each backend. + call ImGui::DestroyContext() + +Example (using backends/imgui_impl_win32.cpp + backends/imgui_impl_dx11.cpp): + + // Create a Dear ImGui context, setup some options + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable some options + + // Initialize Platform + Renderer backends (here: using imgui_impl_win32.cpp + imgui_impl_dx11.cpp) + ImGui_ImplWin32_Init(my_hwnd); + ImGui_ImplDX11_Init(my_d3d_device, my_d3d_device_context); + + // Application main loop + while (true) + { + // Beginning of frame: update Renderer + Platform backend, start Dear ImGui frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + // Any application code here + ImGui::Text("Hello, world!"); + + // End of frame: render Dear ImGui + ImGui::Render(); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + // Swap + g_pSwapChain->Present(1, 0); + } + + // Shutdown + ImGui_ImplDX11_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); + +Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. +Please read the comments and instruction at the top of each file. +Please read FAQ at http://www.dearimgui.org/faq + +If you are using of the backend provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) +files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual +Changelog, so if you want to update them later it will be easier to catch up with what changed. --------------------------------------- EXAMPLE APPLICATIONS --------------------------------------- -Building: - Unfortunately in 2020 it is still tedious to create and maintain portable build files using external - libraries (the kind we're using here to create a window and render 3D triangles) without relying on - third party software. For most examples here we choose to provide: - - Makefiles for Linux/OSX - - Batch files for Visual Studio 2008+ - - A .sln project file for Visual Studio 2012+ - - Xcode project files for the Apple examples - Please let us know if they don't work with your setup! - You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those - directly with a command-line compiler. - - If you are interested in using Cmake to build and links examples, see: - https://github.com/ocornut/imgui/pull/1713 and https://github.com/ocornut/imgui/pull/3027 - - example_allegro5/ Allegro 5 example. = main.cpp + imgui_impl_allegro5.cpp @@ -290,3 +199,45 @@ example_win32_directx12/ DirectX12 example, Windows only. = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp This is quite long and tedious, because: DirectX12. + + +--------------------------------------- + MISCELLANEOUS +--------------------------------------- + +Building: + Unfortunately in 2020 it is still tedious to create and maintain portable build files using external + libraries (the kind we're using here to create a window and render 3D triangles) without relying on + third party software. For most examples here we choose to provide: + - Makefiles for Linux/OSX + - Batch files for Visual Studio 2008+ + - A .sln project file for Visual Studio 2012+ + - Xcode project files for the Apple examples + Please let us know if they don't work with your setup! + You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those + directly with a command-line compiler. + + If you are interested in using Cmake to build and links examples, see: + https://github.com/ocornut/imgui/pull/1713 and https://github.com/ocornut/imgui/pull/3027 + +Things feeling laggy? + + Dear ImGui has no particular extra lag for most behaviors, + e.g. the value of 'io.MousePos' provided at the time of NewFrame() will result in windows being moved + to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience should be pleasant. + + However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated + path and will feel smoother than the majority of contents rendered via regular graphics API (including, + but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane + as the mouse, that disconnect may be jarring to particularly sensitive users. + You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor + using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a + regularly rendered software cursor. + However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at + all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ + when an interactive drag is in progress. + + Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. + If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple + drawing a flat 2D shape directly under the mouse cursor! + From a2a3d80f0460287b4ebb09491eb8b2e46b1e6a7c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Oct 2020 11:44:09 +0200 Subject: [PATCH 314/959] Moving backends code from examples/ to backends/ (step 5: move documentation to MD files) --- backends/README.txt => docs/BACKENDS.md | 0 examples/README.txt => docs/EXAMPLES.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename backends/README.txt => docs/BACKENDS.md (100%) rename examples/README.txt => docs/EXAMPLES.md (100%) diff --git a/backends/README.txt b/docs/BACKENDS.md similarity index 100% rename from backends/README.txt rename to docs/BACKENDS.md diff --git a/examples/README.txt b/docs/EXAMPLES.md similarity index 100% rename from examples/README.txt rename to docs/EXAMPLES.md From b1a18d82e32f13a2ae62df70d08ee46bc8ee6a76 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Oct 2020 12:22:53 +0200 Subject: [PATCH 315/959] Moving backends code from examples/ to backends/ (step 6: update markdown documentation) --- backends/imgui_impl_allegro5.cpp | 7 +- backends/imgui_impl_allegro5.h | 6 +- backends/imgui_impl_dx10.cpp | 6 +- backends/imgui_impl_dx10.h | 6 +- backends/imgui_impl_dx11.cpp | 6 +- backends/imgui_impl_dx11.h | 6 +- backends/imgui_impl_dx12.cpp | 6 +- backends/imgui_impl_dx12.h | 7 +- backends/imgui_impl_dx9.cpp | 6 +- backends/imgui_impl_dx9.h | 6 +- backends/imgui_impl_glfw.cpp | 6 +- backends/imgui_impl_glfw.h | 6 +- backends/imgui_impl_glut.cpp | 6 +- backends/imgui_impl_glut.h | 6 +- backends/imgui_impl_marmalade.cpp | 6 +- backends/imgui_impl_marmalade.h | 6 +- backends/imgui_impl_metal.h | 6 +- backends/imgui_impl_metal.mm | 6 +- backends/imgui_impl_opengl2.cpp | 6 +- backends/imgui_impl_opengl2.h | 6 +- backends/imgui_impl_opengl3.cpp | 6 +- backends/imgui_impl_opengl3.h | 6 +- backends/imgui_impl_osx.h | 4 + backends/imgui_impl_osx.mm | 4 + backends/imgui_impl_sdl.cpp | 6 +- backends/imgui_impl_sdl.h | 6 +- backends/imgui_impl_vulkan.cpp | 6 +- backends/imgui_impl_vulkan.h | 6 +- backends/imgui_impl_win32.cpp | 4 + backends/imgui_impl_win32.h | 4 + docs/BACKENDS.md | 196 +++++++------ docs/CHANGELOG.txt | 3 +- docs/EXAMPLES.md | 340 +++++++++++----------- docs/FAQ.md | 6 +- docs/FONTS.md | 4 +- docs/README.md | 2 +- examples/README.txt | 1 + examples/example_allegro5/main.cpp | 5 +- examples/example_apple_opengl2/main.mm | 5 +- examples/example_emscripten/main.cpp | 9 +- examples/example_glfw_metal/main.mm | 5 +- examples/example_glfw_opengl2/main.cpp | 5 +- examples/example_glfw_opengl3/main.cpp | 5 +- examples/example_glfw_vulkan/main.cpp | 5 +- examples/example_glut_opengl2/main.cpp | 5 +- examples/example_marmalade/main.cpp | 5 +- examples/example_sdl_directx11/main.cpp | 5 +- examples/example_sdl_metal/main.mm | 3 +- examples/example_sdl_opengl2/main.cpp | 5 +- examples/example_sdl_opengl3/main.cpp | 5 +- examples/example_sdl_vulkan/main.cpp | 5 +- examples/example_win32_directx10/main.cpp | 5 +- examples/example_win32_directx11/main.cpp | 5 +- examples/example_win32_directx12/main.cpp | 5 +- examples/example_win32_directx9/main.cpp | 5 +- imgui.cpp | 1 + 56 files changed, 427 insertions(+), 392 deletions(-) create mode 100644 examples/README.txt diff --git a/backends/imgui_impl_allegro5.cpp b/backends/imgui_impl_allegro5.cpp index f49c0935..cadc4b7f 100644 --- a/backends/imgui_impl_allegro5.cpp +++ b/backends/imgui_impl_allegro5.cpp @@ -9,10 +9,9 @@ // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. // [ ] Platform: Missing gamepad support. -// You can copy and use unmodified backends (imgui_impl_* files) in your project. -// See matching application in examples/ for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui, Original Allegro 5 code by @birthggd +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_allegro5.h b/backends/imgui_impl_allegro5.h index fe7eef23..ef91d4b3 100644 --- a/backends/imgui_impl_allegro5.h +++ b/backends/imgui_impl_allegro5.h @@ -9,9 +9,9 @@ // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. // [ ] Platform: Missing gamepad support. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui, Original Allegro 5 code by @birthggd +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index d9fce2f1..75db96a0 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -5,9 +5,9 @@ // [X] Renderer: User texture backend. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index 89269166..35a34a9c 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -5,9 +5,9 @@ // [X] Renderer: User texture backend. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index efab4296..ebb8073c 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -5,9 +5,9 @@ // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index 4fd2ceb0..03fee14d 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -5,9 +5,9 @@ // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index e1af860d..ee656a1b 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -9,9 +9,9 @@ // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // This define is done in the example .vcxproj file and need to be replicated in your app (by e.g. editing imconfig.h) -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 0a0d8d9b..ad3240c3 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -9,10 +9,9 @@ // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // This define is done in the example .vcxproj file and need to be replicated in your app (by e.g. editing imconfig.h) -// You can copy and use unmodified backends (imgui_impl_* files) in your project. -// See matching application in examples/ for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 7375abb8..0565ff4f 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -5,9 +5,9 @@ // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_dx9.h b/backends/imgui_impl_dx9.h index 73316ab5..88edca73 100644 --- a/backends/imgui_impl_dx9.h +++ b/backends/imgui_impl_dx9.h @@ -5,9 +5,9 @@ // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index c96c4e02..74a266e1 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -9,9 +9,9 @@ // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_glfw.h b/backends/imgui_impl_glfw.h index 6345d7a9..6abb4056 100644 --- a/backends/imgui_impl_glfw.h +++ b/backends/imgui_impl_glfw.h @@ -8,9 +8,9 @@ // [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW. // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // About GLSL version: // The 'glsl_version' initialization parameter defaults to "#version 150" if NULL. diff --git a/backends/imgui_impl_glut.cpp b/backends/imgui_impl_glut.cpp index e48bb285..90ad3330 100644 --- a/backends/imgui_impl_glut.cpp +++ b/backends/imgui_impl_glut.cpp @@ -11,9 +11,9 @@ // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_glut.h b/backends/imgui_impl_glut.h index 7b2d919c..9d8282e7 100644 --- a/backends/imgui_impl_glut.h +++ b/backends/imgui_impl_glut.h @@ -11,9 +11,9 @@ // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_marmalade.cpp b/backends/imgui_impl_marmalade.cpp index 7b17512d..805d0c3e 100644 --- a/backends/imgui_impl_marmalade.cpp +++ b/backends/imgui_impl_marmalade.cpp @@ -6,9 +6,9 @@ // Missing features: // [ ] Renderer: Clipping rectangles are not honored. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_marmalade.h b/backends/imgui_impl_marmalade.h index c614380c..db521d58 100644 --- a/backends/imgui_impl_marmalade.h +++ b/backends/imgui_impl_marmalade.h @@ -4,9 +4,9 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'CIwTexture*' as ImTextureID. Read the FAQ about ImTextureID! -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_metal.h b/backends/imgui_impl_metal.h index 2a1e6daf..1db7d873 100644 --- a/backends/imgui_impl_metal.h +++ b/backends/imgui_impl_metal.h @@ -5,9 +5,9 @@ // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index a8cd2883..3b0d34c6 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -5,9 +5,9 @@ // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_opengl2.cpp b/backends/imgui_impl_opengl2.cpp index a2e3c423..e56e87d6 100644 --- a/backends/imgui_impl_opengl2.cpp +++ b/backends/imgui_impl_opengl2.cpp @@ -4,9 +4,9 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in imgui_impl_opengl3.cpp** diff --git a/backends/imgui_impl_opengl2.h b/backends/imgui_impl_opengl2.h index 76a675b8..c0e29760 100644 --- a/backends/imgui_impl_opengl2.h +++ b/backends/imgui_impl_opengl2.h @@ -4,9 +4,9 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in imgui_impl_opengl3.cpp** diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index 8e9a068c..ed151304 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -7,9 +7,9 @@ // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h index 85bd4bae..8c0126d8 100644 --- a/backends/imgui_impl_opengl3.h +++ b/backends/imgui_impl_opengl3.h @@ -7,9 +7,9 @@ // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // About Desktop OpenGL function loaders: // Modern Desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. diff --git a/backends/imgui_impl_osx.h b/backends/imgui_impl_osx.h index 93d63c58..789ee18d 100644 --- a/backends/imgui_impl_osx.h +++ b/backends/imgui_impl_osx.h @@ -8,6 +8,10 @@ // Issues: // [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs + #include "imgui.h" // IMGUI_IMPL_API @class NSEvent; diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index c9a7631d..bf643e29 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -8,6 +8,10 @@ // Issues: // [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters].. +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs + #include "imgui.h" #include "imgui_impl_osx.h" #import diff --git a/backends/imgui_impl_sdl.cpp b/backends/imgui_impl_sdl.cpp index 494220c0..bf273ac6 100644 --- a/backends/imgui_impl_sdl.cpp +++ b/backends/imgui_impl_sdl.cpp @@ -11,9 +11,9 @@ // Missing features: // [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) diff --git a/backends/imgui_impl_sdl.h b/backends/imgui_impl_sdl.h index 4b024dfa..03e518b3 100644 --- a/backends/imgui_impl_sdl.h +++ b/backends/imgui_impl_sdl.h @@ -10,9 +10,9 @@ // Missing features: // [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME. -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index c617acee..7e8a1a76 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -6,9 +6,9 @@ // Missing features: // [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914 -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 06d50e05..33dfe6ad 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -6,9 +6,9 @@ // Missing features: // [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914 -// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. -// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp. -// https://github.com/ocornut/imgui +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index ed90366c..130f6730 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -7,6 +7,10 @@ // [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE). // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs + #include "imgui.h" #include "imgui_impl_win32.h" #ifndef WIN32_LEAN_AND_MEAN diff --git a/backends/imgui_impl_win32.h b/backends/imgui_impl_win32.h index f0a93a43..4919f54a 100644 --- a/backends/imgui_impl_win32.h +++ b/backends/imgui_impl_win32.h @@ -7,6 +7,10 @@ // [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE). // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs + #pragma once #include "imgui.h" // IMGUI_IMPL_API diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 9dd9dfcf..87d54542 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -1,34 +1,28 @@ ------------------------------------------------------------------------ - dear imgui, v1.80 WIP - Backends ------------------------------------------------------------------------ - (See docs/ and examples/ for more documentation) ------------------------------------------------------------------------ +_(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md or view this file with any Markdown viewer)_ -This folder contains backends for popular platforms/graphics API, which you can use in -your application or engine to easily integrate Dear ImGui. +## Dear ImGui: Backends -- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing. - e.g. Windows (imgui_impl_win32.cpp), GLFW (imgui_impl_glfw.cpp), SDL2 (imgui_impl_sdl.cpp), etc. +**The backends/ folder contains backends for popular platforms/graphics API, which you can use in +your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h. -- The 'Renderer' backends are in charge of: creating atlas texture, rendering imgui draw data. - e.g. DirectX11 (imgui_impl_dx11.cpp), OpenGL/WebGL (imgui_impl_opengl3.cpp), Vulkan (imgui_impl_vulkan.cpp), etc. +- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing.
+ e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl.cpp)), etc. -- For some high-level frameworks, a single backend usually handle both 'Platform' and 'Renderer' parts. - e.g. Allegro 5 (imgui_impl_allegro5.cpp), Marmalade (imgui_impl_marmalade5.cpp). +- The 'Renderer' backends are in charge of: creating atlas texture, rendering imgui draw data.
+ e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp]((https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp)), Vulkan ([imgui_impl_vulkan.cpp]((https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp)), etc. -An application usually combines 1 Platform backend + 1 Renderer backend + main ImGui sources. -For example, the example_win32_directx11/ application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. -See examples/README.txt for details. +- For some high-level frameworks, a single backend usually handle both 'Platform' and 'Renderer' parts.
+ e.g. Allegro 5 ([imgui_impl_allegro5.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_allegro5.cpp)), Marmalade ([imgui_impl_marmalade.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_marmalade.cpp)). If you end up creating a custom backend for your engine, you may want to do the same. +An application usually combines 1 Platform backend + 1 Renderer backend + main Dear ImGui sources. +For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx11) application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. See [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for details. ---------------------------------------- - WHAT ARE BACKENDS? ---------------------------------------- + +### What are backends Dear ImGui is highly portable and only requires a few things to run and render, typically: - - Required: providing mouse/keyboard inputs. + - Required: providing mouse/keyboard inputs (fed into the `ImGuiIO` structure). - Required: uploading the font atlas texture into graphics memory. - Required: rendering indexed textured triangles with a clipping rectangle. @@ -42,62 +36,21 @@ Dear ImGui is highly portable and only requires a few things to run and render, - Optional: multi-viewports support. etc. -This is essentially what the backends in this folder are providing + obligatory portability cruft. +This is essentially what each backends are doing + obligatory portability cruft. It is important to understand the difference between the core Dear ImGui library (files in the root folder) and backends which we are describing here (backends/ folder). - Some issues may only be backend or platform specific. - You should be able to write backends for pretty much any platform and any 3D graphics API. - e.g. get creative and have your backend perform rendering remotely, on a different machine - than the one running Dear ImGui, etc. - - ------------------------------------------------------------------------ - USING A CUSTOM ENGINE? ------------------------------------------------------------------------ - -You will likely be tempted to start by rewrite your own backend using your own custom/high-level facilities... -Think twice! + e.g. you can get creative and use software rendering or render remotely on a different machine. -If you are new to Dear ImGui, first try using the existing backends as-is. -You will save lots of time integrating the library. -You can LATER decide to rewrite yourself a custom backend if you really need to. -In most situations, custom backends have less features and more bugs than the standard backends we provide. -If you want portability, you can use multiple backends and choose between them either at compile time -or at runtime. - -Example A: your engine is built over Windows + DirectX11 but you have your own high-level rendering -system layered over DirectX11. - - Suggestion: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. - Once it works, if you really need it you can replace the imgui_impl_dx11.cpp code with a - custom renderer using your own rendering functions, and keep using the standard Win32 code etc. - -Example B: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, Vulkan respectively. - - Suggestion: use multiple generic backends! - Once it works, if you really need it you can replace parts of backends with your own abstractions. - -Example C: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch), -and you have high-level systems everywhere. - - Suggestion: try using a non-portable backend first (e.g. win32 + underlying graphics API) to get - your desktop builds working first. This will get you running faster and get your acquainted with - how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API. - -Also: -The multi-viewports feature of the 'docking' branch allows Dear ImGui windows to be seamlessly detached -from the main application window. This is achieved using an extra layer to the Platform and Renderer -backends, which allows Dear ImGui to communicate platform-specific requests. -Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult -than supporting single-viewport. -If you decide to use unmodified imgui_impl_xxxx.cpp files, you can automatically benefit from -improvements and fixes related to viewports and platform windows without extra work on your side. +### List of backends ---------------------------------------- - LIST OF BACKENDS ---------------------------------------- +In the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder: -List of Platforms Backends in this repository: +List of Platforms Backends: imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) @@ -105,7 +58,7 @@ List of Platforms Backends in this repository: imgui_impl_win32.cpp ; Win32 native API (Windows) imgui_impl_glut.cpp ; GLUT/FreeGLUT (absolutely not recommended in 2020!) -List of Renderer Backends in this repository: +List of Renderer Backends: imgui_impl_dx9.cpp ; DirectX9 imgui_impl_dx10.cpp ; DirectX10 @@ -116,39 +69,92 @@ List of Renderer Backends in this repository: imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) imgui_impl_vulkan.cpp ; Vulkan -Emscripten is also supported. -The example_emscripten/ app uses imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp, but other combos are possible. - -List of high-level Frameworks Backends in this repository: (combine Platform + Renderer) +List of high-level Frameworks Backends (combining Platform + Renderer): imgui_impl_allegro5.cpp imgui_impl_marmalade.cpp -Backends for third-party frameworks, graphics API or other programming languages: - - https://github.com/ocornut/imgui/wiki/Bindings - - (AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, - GML/Game Maker Studio2, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib, - Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, px_render, Qt/QtDirect3D, SFML, Sokol, - Unreal Engine 4, vtk, Win32 GDI, etc.) - - ---------------------------------------- - RECOMMENDED BACKENDS ---------------------------------------- +Emscripten is also supported. +The [example_emscripten](https://github.com/ocornut/imgui/tree/master/examples/example_emscripten) app uses imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp, but other combos are possible. + +### Backends for third-party frameworks, graphics API or other languages + +See https://github.com/ocornut/imgui/wiki/Bindings +- AGS/Adventure Game Studio +- Amethyst +- bsf +- Cinder +- Cocos2d-x +- Diligent Engine +- Flexium, +- GML/Game Maker Studio2 +- GTK3+OpenGL3 +- Irrlicht Engine +- LÖVE+LUA +- Magnum +- NanoRT +- Nim Game Lib, +- Ogre +- openFrameworks +- OSG/OpenSceneGraph +- Orx +- px_render +- Qt/QtDirect3D +- SFML +- Sokol +- Unity +- Unreal Engine 4 +- vtk +- Win32 GDI +etc. + + +### Recommended Backends + +If you are not sure which backend to use, the recommended platform/frameworks for portable applications: + +|Library |Website |Backend |Note | +|--------|--------|--------|-----| +| GLFW | https://github.com/glfw/glfw | imgui_impl_glfw.cpp | | +| SDL2 | https://www.libsdl.org | imgui_impl_sdl.cpp | | +| Sokol | https://github.com/floooh/sokol | [util/sokol_imgui.h](https://github.com/floooh/sokol/blob/master/util/sokol_imgui.h) | Lower-level than GLFW/SDL | + + +### Using a custom engine? + +You will likely be tempted to start by rewrite your own backend using your own custom/high-level facilities...
+Think twice! -Recommended platform/frameworks for portable applications: +If you are new to Dear ImGui, first try using the existing backends as-is. +You will save lots of time integrating the library. +You can LATER decide to rewrite yourself a custom backend if you really need to. +In most situations, custom backends have less features and more bugs than the standard backends we provide. +If you want portability, you can use multiple backends and choose between them either at compile time +or at runtime. - Library: GLFW - Webpage: https://github.com/glfw/glfw - Backend: imgui_impl_glfw.cpp +**Example A**: your engine is built over Windows + DirectX11 but you have your own high-level rendering +system layered over DirectX11.
+Suggestion: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. +Once it works, if you really need it you can replace the imgui_impl_dx11.cpp code with a +custom renderer using your own rendering functions, and keep using the standard Win32 code etc. - Library: SDL2 - Webpage: https://www.libsdl.org - Backend: imgui_impl_sdl.cpp +**Example B**: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, Vulkan respectively.
+Suggestion: use multiple generic backends! +Once it works, if you really need it you can replace parts of backends with your own abstractions. - Library: Sokol (lower-level than GLFW/SDL) - Webpage: https://github.com/floooh/sokol - Backend: Use util/sokol_imgui.h in Sokol repository. +**Example C**: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch), +and you have high-level systems everywhere.
+Suggestion: try using a non-portable backend first (e.g. win32 + underlying graphics API) to get +your desktop builds working first. This will get you running faster and get your acquainted with +how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API. +Also: +The [multi-viewports feature](https://github.com/ocornut/imgui/issues/1542) of the 'docking' branch allows +Dear ImGui windows to be seamlessly detached from the main application window. This is achieved using an +extra layer to the Platform and Renderer backends, which allows Dear ImGui to communicate platform-specific +requests such as: "create an additional OS window", "create a render context", "get the OS position of this +window" etc. See 'ImGuiPlatformIO' for details. +Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult +than supporting single-viewport. +If you decide to use unmodified imgui_impl_XXXX.cpp files, you can automatically benefit from +improvements and fixes related to viewports and platform windows without extra work on your side. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a01917de..164e3554 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,7 @@ HOW TO UPDATE? Breaking Changes: +- Backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. (#3513) - Removed redirecting functions/enums names that were marked obsolete in 1.60 (April 2017): - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) @@ -53,7 +54,7 @@ Breaking Changes: Other Changes: -- Docs: Split Backends and Examples README and improved them. +- Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index 45f0ae66..d318bd35 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -1,20 +1,15 @@ ------------------------------------------------------------------------ - dear imgui, v1.80 WIP - Examples applications ------------------------------------------------------------------------ - (See docs/ and backends/ for more documentation) ------------------------------------------------------------------------ +_(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md or view this file with any Markdown viewer)_ -This folder contains example applications (standalone, ready-to-build) for variety of -platforms and graphics APIs. They all use standard backends from the backends/ folder. +## Dear ImGui: Examples + +**The [examples/](https://github.com/ocornut/imgui/blob/master/examples) folder example applications (standalone, ready-to-build) for variety of +platforms and graphics APIs.** They all use standard backends from the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder. You can find Windows binaries for some of those example applications at: http://www.dearimgui.org/binaries ---------------------------------------- - GETTING STARTED ---------------------------------------- +### Getting Started Integration in a typical existing application, should take <20 lines when using standard backends. @@ -34,7 +29,7 @@ Integration in a typical existing application, should take <20 lines when using call ImGui_ImplXXXX_Shutdown() for each backend. call ImGui::DestroyContext() -Example (using backends/imgui_impl_win32.cpp + backends/imgui_impl_dx11.cpp): +Example (using [backends/imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp) + [backends/imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)): // Create a Dear ImGui context, setup some options ImGui::CreateContext(); @@ -78,166 +73,163 @@ files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with it Changelog, so if you want to update them later it will be easier to catch up with what changed. ---------------------------------------- - EXAMPLE APPLICATIONS ---------------------------------------- - -example_allegro5/ - Allegro 5 example. - = main.cpp + imgui_impl_allegro5.cpp - -example_apple_metal/ - OSX & iOS + Metal. - = main.m + imgui_impl_osx.mm + imgui_impl_metal.mm - It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. - (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. - You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) - -example_apple_opengl2/ - OSX + OpenGL2. - = main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp - (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. - You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) - -example_empscripten: - Emcripten + SDL2 + OpenGL3+/ES2/ES3 example. - = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp - Note that other examples based on SDL or GLFW + OpenGL could easily be modified to work with Emscripten. - We provide this to make the Emscripten differences obvious, and have them not pollute all other examples. - -example_glfw_metal/ - GLFW (Mac) + Metal example. - = main.mm + imgui_impl_glfw.cpp + imgui_impl_metal.mm - -example_glfw_opengl2/ - GLFW + OpenGL2 example (legacy, fixed pipeline). - = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp - **DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** - **Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)** - This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. - If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to - make things more complicated, will require your code to reset many OpenGL attributes to their initial - state, and might confuse your GPU driver. One star, not recommended. - -example_glfw_opengl3/ - GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (programmable pipeline). - = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp - This uses more modern OpenGL calls and custom shaders. - Prefer using that if you are using modern OpenGL in your application (anything with shaders). - (Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent - source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different - from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.) - -example_glfw_vulkan/ - GLFW (Win32, Mac, Linux) + Vulkan example. - = main.cpp + imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp - This is quite long and tedious, because: Vulkan. - For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. - -example_glut_opengl2/ - GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2. - = main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp - Note that GLUT/FreeGLUT is largely obsolete software, prefer using GLFW or SDL. - -example_marmalade/ - Marmalade example using IwGx. - = main.cpp + imgui_impl_marmalade.cpp - -example_null - Null example, compile and link imgui, create context, run headless with no inputs and no graphics output. - = main.cpp - This is used to quickly test compilation of core imgui files in as many setups as possible. - Because this application doesn't create a window nor a graphic context, there's no graphics output. - -example_sdl_directx11/ - SDL2 + DirectX11 example, Windows only. - = main.cpp + imgui_impl_sdl.cpp + imgui_impl_dx11.cpp - This to demonstrate usage of DirectX with SDL. - -example_sdl_metal/ - SDL2 (Mac) + Metal example. - = main.mm + imgui_impl_sdl.cpp + imgui_impl_metal.mm - -example_sdl_opengl2/ - SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline). - = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp - **DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** - **Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)** - This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. - If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to - make things more complicated, will require your code to reset many OpenGL attributes to their initial - state, and might confuse your GPU driver. One star, not recommended. - -example_sdl_opengl3/ - SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example. - = main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp - This uses more modern OpenGL calls and custom shaders. - Prefer using that if you are using modern OpenGL in your application (anything with shaders). - (Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent - source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different - from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.) - -example_sdl_vulkan/ - SDL2 (Win32, Mac, Linux, etc.) + Vulkan example. - = main.cpp + imgui_impl_sdl.cpp + imgui_impl_vulkan.cpp - This is quite long and tedious, because: Vulkan. - For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. - -example_win32_directx9/ - DirectX9 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp - -example_win32_directx10/ - DirectX10 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx10.cpp - -example_win32_directx11/ - DirectX11 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx11.cpp - -example_win32_directx12/ - DirectX12 example, Windows only. - = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp - This is quite long and tedious, because: DirectX12. - - ---------------------------------------- - MISCELLANEOUS ---------------------------------------- - -Building: - Unfortunately in 2020 it is still tedious to create and maintain portable build files using external - libraries (the kind we're using here to create a window and render 3D triangles) without relying on - third party software. For most examples here we choose to provide: - - Makefiles for Linux/OSX - - Batch files for Visual Studio 2008+ - - A .sln project file for Visual Studio 2012+ - - Xcode project files for the Apple examples - Please let us know if they don't work with your setup! - You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those - directly with a command-line compiler. - - If you are interested in using Cmake to build and links examples, see: - https://github.com/ocornut/imgui/pull/1713 and https://github.com/ocornut/imgui/pull/3027 - -Things feeling laggy? - - Dear ImGui has no particular extra lag for most behaviors, - e.g. the value of 'io.MousePos' provided at the time of NewFrame() will result in windows being moved - to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience should be pleasant. - - However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated - path and will feel smoother than the majority of contents rendered via regular graphics API (including, - but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane - as the mouse, that disconnect may be jarring to particularly sensitive users. - You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor - using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a - regularly rendered software cursor. - However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at - all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ - when an interactive drag is in progress. - - Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. - If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple - drawing a flat 2D shape directly under the mouse cursor! +### Examples Applications + +[example_allegro5/](https://github.com/ocornut/imgui/blob/master/examples/example_allegro5/)
+Allegro 5 example.
+= main.cpp + imgui_impl_allegro5.cpp + +[example_apple_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_metal/)
+OSX & iOS + Metal example.
+= main.m + imgui_impl_osx.mm + imgui_impl_metal.mm
+It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. +(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. +You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) + +[example_apple_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_apple_opengl2/)
+OSX + OpenGL2 example.
+= main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp
+(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. + You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) + +[example_emscripten/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten/)
+Emcripten + SDL2 + OpenGL3+/ES2/ES3 example.
+= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp
+Note that other examples based on SDL or GLFW + OpenGL could easily be modified to work with Emscripten. +We provide this to make the Emscripten differences obvious, and have them not pollute all other examples. + +[example_glfw_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_metal/)
+GLFW (Mac) + Metal example.
+= main.mm + imgui_impl_glfw.cpp + imgui_impl_metal.mm + +[example_glfw_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl2/)
+GLFW + OpenGL2 example (legacy, fixed pipeline).
+= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp
+**DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+**Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)**
+This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. +If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to +make things more complicated, will require your code to reset many OpenGL attributes to their initial +state, and might confuse your GPU driver. One star, not recommended. + +[example_glfw_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl3/)
+GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (programmable pipeline).
+= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp
+This uses more modern OpenGL calls and custom shaders.
+Prefer using that if you are using modern OpenGL in your application (anything with shaders). +(Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent +source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different +from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.) + +[example_glfw_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/)
+GLFW (Win32, Mac, Linux) + Vulkan example.
+= main.cpp + imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp
+This is quite long and tedious, because: Vulkan. +For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. + +[example_glut_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_glut_opengl2/)
+GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2 example.
+= main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp
+Note that GLUT/FreeGLUT is largely obsolete software, prefer using GLFW or SDL. + +[example_marmalade/](https://github.com/ocornut/imgui/blob/master/examples/example_marmalade/)
+Marmalade example using IwGx.
+= main.cpp + imgui_impl_marmalade.cpp + +[example_null/](https://github.com/ocornut/imgui/blob/master/examples/example_null/)
+Null example, compile and link imgui, create context, run headless with no inputs and no graphics output.
+= main.cpp
+This is used to quickly test compilation of core imgui files in as many setups as possible. +Because this application doesn't create a window nor a graphic context, there's no graphics output. + +[example_sdl_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_directx11/)
+SDL2 + DirectX11 example, Windows only.
+= main.cpp + imgui_impl_sdl.cpp + imgui_impl_dx11.cpp
+This to demonstrate usage of DirectX with SDL. + +[example_sdl_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_metal/)
+SDL2 (Mac) + Metal example.
+= main.mm + imgui_impl_sdl.cpp + imgui_impl_metal.mm + +[example_sdl_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_opengl2/)
+SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline).
+= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp
+**DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+**Prefer using OPENGL3 code (with gl3w/glew/glad/glad2/glbinding, you can replace the OpenGL function loader)**
+This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. +If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to +make things more complicated, will require your code to reset many OpenGL attributes to their initial +state, and might confuse your GPU driver. One star, not recommended. + +[example_sdl_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_opengl3/)
+SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example.
+= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp
+This uses more modern OpenGL calls and custom shaders.
+Prefer using that if you are using modern OpenGL in your application (anything with shaders). +(Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent +source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different +from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.) + +[example_sdl_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_vulkan/)
+SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
+= main.cpp + imgui_impl_sdl.cpp + imgui_impl_vulkan.cpp
+This is quite long and tedious, because: Vulkan.
+For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. + +[example_win32_directx9/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx9/)
+DirectX9 example, Windows only.
+= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp + +[example_win32_directx10/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx10/)
+DirectX10 example, Windows only.
+= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx10.cpp + +[example_win32_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx11/)
+DirectX11 example, Windows only.
+= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx11.cpp + +[example_win32_directx12/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx12/)
+DirectX12 example, Windows only.
+= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp
+This is quite long and tedious, because: DirectX12. + + +### Miscallaneous + +**Building** + +Unfortunately in 2020 it is still tedious to create and maintain portable build files using external +libraries (the kind we're using here to create a window and render 3D triangles) without relying on +third party software. For most examples here we choose to provide: + - Makefiles for Linux/OSX + - Batch files for Visual Studio 2008+ + - A .sln project file for Visual Studio 2012+ + - Xcode project files for the Apple examples +Please let us know if they don't work with your setup! +You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those +directly with a command-line compiler. + +If you are interested in using Cmake to build and links examples, see: + https://github.com/ocornut/imgui/pull/1713 and https://github.com/ocornut/imgui/pull/3027 + +**About mouse cursor latency** + +Dear ImGui has no particular extra lag for most behaviors, +e.g. the value of 'io.MousePos' provided at the time of NewFrame() will result in windows being moved +to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience should be pleasant. + +However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated +path and will feel smoother than the majority of contents rendered via regular graphics API (including, +but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane +as the mouse, that disconnect may be jarring to particularly sensitive users. +You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor +using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a +regularly rendered software cursor. +However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at +all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ +when an interactive drag is in progress. + +Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. +If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple +drawing a flat 2D shape directly under the mouse cursor! diff --git a/docs/FAQ.md b/docs/FAQ.md index 20abe638..d474607c 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -50,6 +50,7 @@ or view this file with any Markdown viewer. **This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.** - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder to explain how to integrate Dear ImGui with your own engine/application. You can run those applications and explore them. - See demo code in [imgui_demo.cpp](https://github.com/ocornut/imgui/blob/master/imgui_demo.cpp) and particularly the `ImGui::ShowDemoWindow()` function. The demo covers most features of Dear ImGui, so you can read the code and see its output. +- See documentation: [Backends](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md), [Examples](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md), [Fonts](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). - See documentation and comments at the top of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp) + general API comments in [imgui.h](https://github.com/ocornut/imgui/blob/master/imgui.h). - The [Wiki](https://github.com/ocornut/imgui/wiki) has many resources and links. - The [Glossary](https://github.com/ocornut/imgui/wiki/Glossary) page may be useful. @@ -91,8 +92,9 @@ You may merge in the [tables](https://github.com/ocornut/imgui/tree/tables) bran ### Q: How to get started? +Read [EXAMPLES.md](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md).
+Read [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md).
Read `PROGRAMMER GUIDE` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp). -Read [examples/README.txt](https://github.com/ocornut/imgui/tree/master/examples/README.txt). ##### [Return to Index](#index) @@ -142,7 +144,7 @@ and portable source code (uSynergy.c/.h) for a small embeddable client that you to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer. Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols. - Game console users: consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback. -- You may also use a third party solution such as [Remote ImGui](https://github.com/JordiRos/remoteimgui) or [imgui-ws](https://github.com/ggerganov/imgui-ws) which sends the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine. See [Wiki](https://github.com/ocornut/imgui/wiki) index for most details. +- You may also use a third party solution such as [netImgui](https://github.com/sammyfreg/netImgui), [Remote ImGui](https://github.com/JordiRos/remoteimgui) or [imgui-ws](https://github.com/ggerganov/imgui-ws) which sends the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine. See [Wiki](https://github.com/ocornut/imgui/wiki) index for most details. - For touch inputs, you can increase the hit box of widgets (via the `style.TouchPadding` setting) to accommodate for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing for screen real-estate and precision. ##### [Return to Index](#index) diff --git a/docs/FONTS.md b/docs/FONTS.md index 7ce5a88c..87e6ee04 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -1,6 +1,6 @@ -## Dear ImGui: Using Fonts +_(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer)_ -(You may browse this document at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer.) +## Dear ImGui: Using Fonts The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions. diff --git a/docs/README.md b/docs/README.md index e60e4311..a946315f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -33,7 +33,7 @@ Dear ImGui is particularly suited to integration in games engine (for tooling), You will need a backend to integrate Dear ImGui in your app. The backend passes mouse/keyboard/gamepad inputs and variety of settings to Dear ImGui, and is in charge of rendering the resulting vertices. -**Backends for a variety of graphics api and rendering platforms** are provided in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder, along with example applications. See the [Integration](#integration) section of this document for details. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui. +**Backends for a variety of graphics api and rendering platforms** are provided in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder, along with example applications in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder. See the [Integration](#integration) section of this document for details. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui. After Dear ImGui is setup in your application, you can use it from \_anywhere\_ in your program loop: diff --git a/examples/README.txt b/examples/README.txt new file mode 100644 index 00000000..ed16dd9f --- /dev/null +++ b/examples/README.txt @@ -0,0 +1 @@ +See EXAMPLES and BACKENDS files in the docs/ folder. diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 60ed680f..fefcd76d 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for Allegro 5 -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for Allegro 5 +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include #include diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index eaf55dae..c3f43bdb 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "../../backends/imgui_impl_osx.h" diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp index facbf331..13f90ede 100644 --- a/examples/example_emscripten/main.cpp +++ b/examples/example_emscripten/main.cpp @@ -1,10 +1,11 @@ -// dear imgui: standalone example application for Emscripten, using SDL2 + OpenGL3 +// Dear ImGui: standalone example application for Emscripten, using SDL2 + OpenGL3 +// (Emscripten is a C++-to-javascript compiler, used to publish executables for the web. See https://emscripten.org/) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs + // This is mostly the same code as the SDL2 + OpenGL3 example, simply with the modifications needed to run on Emscripten. // It is possible to combine both code into a single source file that will compile properly on Desktop and using Emscripten. // See https://github.com/ocornut/imgui/pull/2492 as an example on how to do just that. -// -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. -// (Emscripten is a C++-to-javascript compiler, used to publish executables for the web. See https://emscripten.org/) #include "imgui.h" #include "imgui_impl_sdl.h" diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index 1860d8bd..d818dba0 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -1,6 +1,7 @@ -// dear imgui: standalone example application for GLFW + Metal, using programmable pipeline -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for GLFW + Metal, using programmable pipeline // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_glfw.h" diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 2307e1c3..9683a4d1 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -1,6 +1,7 @@ -// dear imgui: standalone example application for GLFW + OpenGL2, using legacy fixed pipeline -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for GLFW + OpenGL2, using legacy fixed pipeline // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in the example_glfw_opengl2/ folder** diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index f773005f..434c9f2d 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -1,6 +1,7 @@ -// dear imgui: standalone example application for GLFW + OpenGL 3, using programmable pipeline -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for GLFW + OpenGL 3, using programmable pipeline // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_glfw.h" diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index ba2c9d6d..230d21dc 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for Glfw + Vulkan -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for Glfw + Vulkan +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 0adc7ae7..b8efae9b 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for GLUT/FreeGLUT + OpenGL2, using legacy fixed pipeline -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for GLUT/FreeGLUT + OpenGL2, using legacy fixed pipeline +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // !!! GLUT/FreeGLUT IS OBSOLETE SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT in 2020, you are being abused. Please show some resistance. !!! diff --git a/examples/example_marmalade/main.cpp b/examples/example_marmalade/main.cpp index 064e43ce..e97cb534 100644 --- a/examples/example_marmalade/main.cpp +++ b/examples/example_marmalade/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for Marmalade -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for Marmalade +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // Copyright (C) 2015 by Giovanni Zito // This file is part of Dear ImGui diff --git a/examples/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp index 82e2206f..5a80115d 100644 --- a/examples/example_sdl_directx11/main.cpp +++ b/examples/example_sdl_directx11/main.cpp @@ -1,6 +1,7 @@ -// dear imgui: standalone example application for SDL2 + DirectX 11 -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for SDL2 + DirectX 11 // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_sdl.h" diff --git a/examples/example_sdl_metal/main.mm b/examples/example_sdl_metal/main.mm index 8184ddf3..1f33503d 100644 --- a/examples/example_sdl_metal/main.mm +++ b/examples/example_sdl_metal/main.mm @@ -1,6 +1,7 @@ // Dear ImGui: standalone example application for SDL2 + Metal -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_sdl.h" diff --git a/examples/example_sdl_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp index 8bfafb77..72898d46 100644 --- a/examples/example_sdl_opengl2/main.cpp +++ b/examples/example_sdl_opengl2/main.cpp @@ -1,6 +1,7 @@ -// dear imgui: standalone example application for SDL2 + OpenGL -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for SDL2 + OpenGL // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in the example_sdl_opengl3/ folder** diff --git a/examples/example_sdl_opengl3/main.cpp b/examples/example_sdl_opengl3/main.cpp index 578c8c41..e8c68ae5 100644 --- a/examples/example_sdl_opengl3/main.cpp +++ b/examples/example_sdl_opengl3/main.cpp @@ -1,7 +1,8 @@ -// dear imgui: standalone example application for SDL2 + OpenGL -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for SDL2 + OpenGL // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.) +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_sdl.h" diff --git a/examples/example_sdl_vulkan/main.cpp b/examples/example_sdl_vulkan/main.cpp index e4625e3e..0f21b060 100644 --- a/examples/example_sdl_vulkan/main.cpp +++ b/examples/example_sdl_vulkan/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for SDL2 + Vulkan -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for SDL2 + Vulkan +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index 2dbff10b..edde4060 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for DirectX 10 -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for DirectX 10 +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_win32.h" diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 808599bf..1ae4dfea 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -1,5 +1,6 @@ -// dear imgui - standalone example application for DirectX 11 -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for DirectX 11 +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_win32.h" diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index a2e83ec6..785237f3 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for DirectX 12 -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for DirectX 12 +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // FIXME: 64-bit only for now! (Because sizeof(ImTextureId) == sizeof(void*)) #include "imgui.h" diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index a07011c0..0b0d27cf 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -1,5 +1,6 @@ -// dear imgui: standalone example application for DirectX 9 -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. +// Dear ImGui: standalone example application for DirectX 9 +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #include "imgui.h" #include "imgui_impl_dx9.h" diff --git a/imgui.cpp b/imgui.cpp index c24e8e4e..81a39cd6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -371,6 +371,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) From f2f326024c480e38de6404d11b5d85272bf8d9df Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Oct 2020 18:34:33 +0200 Subject: [PATCH 316/959] Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. --- docs/CHANGELOG.txt | 1 + imgui_internal.h | 6 ++++-- imgui_widgets.cpp | 26 ++++++++++++++++++-------- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 164e3554..e91267d3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -54,6 +54,7 @@ Breaking Changes: Other Changes: +- Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. diff --git a/imgui_internal.h b/imgui_internal.h index e74d2a80..013c8139 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1754,7 +1754,8 @@ struct ImGuiTabBar int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; - float LastTabContentHeight; // Record the height of contents submitted below the tab bar + float CurrTabsContentsHeight; + float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar float WidthAllTabs; // Actual width of all tabs (locked during layout) float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped float ScrollingAnim; @@ -1770,8 +1771,9 @@ struct ImGuiTabBar bool WantLayout; bool VisibleTabWasSubmitted; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame - short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() + short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() + ImVec2 TabsContentsMin; ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ea773e2..5da42da5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6805,7 +6805,7 @@ ImGuiTabBar::ImGuiTabBar() ID = 0; SelectedTabId = NextSelectedTabId = VisibleTabId = 0; CurrFrameVisible = PrevFrameVisible = -1; - LastTabContentHeight = 0.0f; + CurrTabsContentsHeight = PrevTabsContentsHeight = 0.0f; WidthAllTabs = WidthAllTabsIdeal = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; ScrollingRectMinX = ScrollingRectMaxX = 0.0f; @@ -6877,10 +6877,10 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar)); g.CurrentTabBar = tab_bar; + // Append with multiple BeginTabBar()/EndTabBar() pairs. if (tab_bar->CurrFrameVisible == g.FrameCount) { - //IMGUI_DEBUG_LOG("BeginTabBarEx already called this frame\n", g.FrameCount); - IM_ASSERT(0); + window->DC.CursorPos = tab_bar->TabsContentsMin; return true; } @@ -6899,12 +6899,15 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab() tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible; tab_bar->CurrFrameVisible = g.FrameCount; + tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight; + tab_bar->CurrTabsContentsHeight = 0.0f; tab_bar->FramePadding = g.Style.FramePadding; tab_bar->TabsActiveCount = 0; // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap - window->DC.CursorPos.x = tab_bar->BarRect.Min.x; - window->DC.CursorPos.y = tab_bar->BarRect.Max.y + g.Style.ItemSpacing.y; + tab_bar->TabsContentsMin.x = tab_bar->BarRect.Min.x; + tab_bar->TabsContentsMin.y = tab_bar->BarRect.Max.y + g.Style.ItemSpacing.y; + window->DC.CursorPos = tab_bar->TabsContentsMin; // Draw separator const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); @@ -6930,15 +6933,22 @@ void ImGui::EndTabBar() IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); return; } - if (tab_bar->WantLayout) // Fallback in case no TabItem have been submitted + + // Fallback in case no TabItem have been submitted + if (tab_bar->WantLayout) TabBarLayout(tab_bar); // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) - tab_bar->LastTabContentHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f); + { + tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight); + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight; + } else - window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->LastTabContentHeight; + { + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight; + } if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) PopID(); From bae2240edad9e6517c1586951973338c9affcf50 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Oct 2020 18:34:33 +0200 Subject: [PATCH 317/959] Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. # Conflicts: # imgui_widgets.cpp --- docs/CHANGELOG.txt | 3 +-- imgui_internal.h | 6 ++++-- imgui_widgets.cpp | 26 ++++++++++++++++++-------- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 4ccb5fa1..5eebda84 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -120,12 +120,11 @@ Breaking Changes: IMGUI_DISABLE_OBSOLETE_FUNCTIONS in imconfig.h even temporarily to have a pass at finding and removing up old API calls, if any remaining. - Other Changes: +- Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. ->>>>>>> master ----------------------------------------------------------------------- diff --git a/imgui_internal.h b/imgui_internal.h index 5a9e9fc2..0d04d70e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1960,7 +1960,8 @@ struct ImGuiTabBar int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; - float LastTabContentHeight; // Record the height of contents submitted below the tab bar + float CurrTabsContentsHeight; + float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar float WidthAllTabs; // Actual width of all tabs (locked during layout) float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped float ScrollingAnim; @@ -1976,8 +1977,9 @@ struct ImGuiTabBar bool WantLayout; bool VisibleTabWasSubmitted; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame - short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() + short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() + ImVec2 TabsContentsMin; ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f6813593..d2f52a10 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6837,7 +6837,7 @@ ImGuiTabBar::ImGuiTabBar() ID = 0; SelectedTabId = NextSelectedTabId = VisibleTabId = 0; CurrFrameVisible = PrevFrameVisible = -1; - LastTabContentHeight = 0.0f; + CurrTabsContentsHeight = PrevTabsContentsHeight = 0.0f; WidthAllTabs = WidthAllTabsIdeal = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; ScrollingRectMinX = ScrollingRectMaxX = 0.0f; @@ -6909,10 +6909,10 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar)); g.CurrentTabBar = tab_bar; + // Append with multiple BeginTabBar()/EndTabBar() pairs. if (tab_bar->CurrFrameVisible == g.FrameCount) { - //IMGUI_DEBUG_LOG("BeginTabBarEx already called this frame\n", g.FrameCount); - //IM_ASSERT(0); + window->DC.CursorPos = tab_bar->TabsContentsMin; return true; } @@ -6931,12 +6931,15 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab() tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible; tab_bar->CurrFrameVisible = g.FrameCount; + tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight; + tab_bar->CurrTabsContentsHeight = 0.0f; tab_bar->FramePadding = g.Style.FramePadding; tab_bar->TabsActiveCount = 0; // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap - window->DC.CursorPos.x = tab_bar->BarRect.Min.x; - window->DC.CursorPos.y = tab_bar->BarRect.Max.y + g.Style.ItemSpacing.y; + tab_bar->TabsContentsMin.x = tab_bar->BarRect.Min.x; + tab_bar->TabsContentsMin.y = tab_bar->BarRect.Max.y + g.Style.ItemSpacing.y; + window->DC.CursorPos = tab_bar->TabsContentsMin; // Draw separator const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); @@ -6969,15 +6972,22 @@ void ImGui::EndTabBar() IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!"); return; } - if (tab_bar->WantLayout) // Fallback in case no TabItem have been submitted + + // Fallback in case no TabItem have been submitted + if (tab_bar->WantLayout) TabBarLayout(tab_bar); // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) - tab_bar->LastTabContentHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f); + { + tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight); + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight; + } else - window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->LastTabContentHeight; + { + window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight; + } if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) PopID(); From b26f1530b753745d37072078900f2e1d10c68e67 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 14 Oct 2020 19:11:00 +0200 Subject: [PATCH 318/959] Internals: Docking, Tab Bar: Add DockNodeBeginAmendTabBar() and work toward making hybrid dock node with windows tab bars somehow work (not done). --- imgui.cpp | 46 ++++++++++++++++++++++++++++++++++++++-------- imgui_internal.h | 2 ++ imgui_widgets.cpp | 30 ++++++++++++++++-------------- 3 files changed, 56 insertions(+), 22 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index b9ebd0d5..e519b6d5 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -12510,6 +12510,8 @@ bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* // - DockNodeStartMouseMovingWindow() // - DockNodeUpdate() // - DockNodeUpdateWindowMenu() +// - DockNodeBeginAmendTabBar() +// - DockNodeEndAmendTabBar() // - DockNodeUpdateTabBar() // - DockNodeAddTabBar() // - DockNodeRemoveTabBar() @@ -13231,7 +13233,8 @@ static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - IM_ASSERT(tab->Window != NULL); + if (tab->Window == NULL) + continue; if (Selectable(tab->Window->Name, tab->ID == tab_bar->SelectedTabId)) ret_tab_id = tab->ID; SameLine(); @@ -13243,6 +13246,26 @@ static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* return ret_tab_id; } +// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. +bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node) +{ + if (node->TabBar == NULL || node->HostWindow == NULL) + return false; + Begin(node->HostWindow->Name); + PushOverrideID(node->ID); + bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node); + IM_ASSERT(ret); + return true; +} + +void ImGui::DockNodeEndAmendTabBar() +{ + EndTabBar(); + PopID(); + End(); +} + +// Submit the tab bar corresponding to a dock node and various housekeeping details. static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window) { ImGuiContext& g = *GImGui; @@ -13446,7 +13469,14 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id) { bool held; - ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held); + ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap); + if (g.HoveredId == title_bar_id) + { + // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar, + // otherwise dragging window will steal HoveredId and amended tabs cannot get them. + host_window->DC.LastItemId = title_bar_id; + SetItemAllowOverlap(); + } if (held) { if (IsMouseClicked(0)) @@ -15847,13 +15877,13 @@ void ImGui::ShowMetricsWindow(bool* p_open) const char* buf_end = buf + IM_ARRAYSIZE(buf); const bool is_active = (tab_bar->PrevFrameVisible >= ImGui::GetFrameCount() - 2); p += ImFormatString(p, buf_end - p, "Tab Bar 0x%08X (%d tabs)%s", tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); - if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) + p += ImFormatString(p, buf_end - p, " { "); + for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) { - p += ImFormatString(p, buf_end - p, " { "); - for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) - p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", tab_bar->Tabs[tab_n].Window->Name); - p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); + ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???"); } + p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } bool open = ImGui::TreeNode(tab_bar, "%s", buf); if (!is_active) { PopStyleColor(); } @@ -15872,7 +15902,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::PushID(tab); if (ImGui::SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); if (ImGui::SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } ImGui::SameLine(); - ImGui::Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "", tab->Offset, tab->Width, tab->ContentWidth); + ImGui::Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth); ImGui::PopID(); } ImGui::TreePop(); diff --git a/imgui_internal.h b/imgui_internal.h index 0d04d70e..e9398f58 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2170,6 +2170,8 @@ namespace ImGui IMGUI_API void DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window); IMGUI_API void DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); IMGUI_API bool DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos); + IMGUI_API bool DockNodeBeginAmendTabBar(ImGuiDockNode* node); + IMGUI_API void DockNodeEndAmendTabBar(); inline ImGuiDockNode* DockNodeGetRootNode(ImGuiDockNode* node) { while (node->ParentNode) node = node->ParentNode; return node; } inline int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; } inline ImGuiDockNode* GetWindowDockNode() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockNode; } diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d2f52a10..cc87c718 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6824,7 +6824,7 @@ struct ImGuiTabBarSection namespace ImGui { static void TabBarLayout(ImGuiTabBar* tab_bar); - static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label); + static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window); static float TabBarCalcMaxTabWidth(); static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImGuiTabBarSection* sections); @@ -6918,7 +6918,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable))) - if (tab_bar->Tabs.Size > 1 && (flags & ImGuiTabBarFlags_DockNode) == 0) + if (tab_bar->Tabs.Size > 1 && (flags & ImGuiTabBarFlags_DockNode) == 0) // FIXME: TabBar with DockNode can now be hybrid ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder); tab_bar->TabsAddedNew = false; @@ -7177,6 +7177,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) { ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n]; tab->Offset = tab_offset; + tab->NameOffset = -1; tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f); } tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f); @@ -7184,6 +7185,9 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) section_tab_index += section->TabCount; } + // Clear name buffers + tab_bar->TabsNames.Buf.resize(0); + // If we have lost the selected tab, select the next most recently active one if (found_selected_tab_id == false) tab_bar->SelectedTabId = 0; @@ -7220,21 +7224,18 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing; tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing; - // Clear name buffers - if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) - tab_bar->TabsNames.Buf.resize(0); - // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos = tab_bar->BarRect.Min; ItemSize(ImVec2(tab_bar->WidthAllTabsIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y); } -// Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. -static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label) +// Dockable uses Name/ID in the global namespace. Non-dockable items use the ID stack. +static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window) { - if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) + if (docked_window != NULL) { + IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); ImGuiID id = ImHashStr(label); KeepAliveID(id); return id; @@ -7581,7 +7582,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, return false; const ImGuiStyle& style = g.Style; - const ImGuiID id = TabBarCalcTabID(tab_bar, label); + const ImGuiID id = TabBarCalcTabID(tab_bar, label, docked_window); // If the user called us with *p_open == false, we early out and don't render. // We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. @@ -7631,9 +7632,10 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab->Window = docked_window; // Append name with zero-terminator - if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) + // (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar) + if (tab->Window != NULL) { - IM_ASSERT(tab->Window != NULL); + IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode); tab->NameOffset = -1; } else @@ -7851,7 +7853,7 @@ void ImGui::SetTabItemClosed(const char* label) if (is_within_manual_tab_bar) { ImGuiTabBar* tab_bar = g.CurrentTabBar; - ImGuiID tab_id = TabBarCalcTabID(tab_bar, label); + ImGuiID tab_id = TabBarCalcTabID(tab_bar, label, NULL); if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) tab->WantClose = true; // Will be processed by next call to TabBarLayout() } @@ -7860,7 +7862,7 @@ void ImGui::SetTabItemClosed(const char* label) if (window->DockIsActive) if (ImGuiDockNode* node = window->DockNode) { - ImGuiID tab_id = TabBarCalcTabID(node->TabBar, label); + ImGuiID tab_id = TabBarCalcTabID(node->TabBar, label, window); TabBarRemoveTab(node->TabBar, tab_id); window->DockTabWantClose = true; } From d3a80d9f1b543aa89d35546ae6585d696e2eadfd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2020 14:54:41 +0200 Subject: [PATCH 319/959] Internals: Docking: More fixes to make DockNodeBeginAmendTabBar() viable (probably some issues left) --- imgui.cpp | 60 +++++++++++++++++++++++++++-------------------- imgui_widgets.cpp | 4 ++-- 2 files changed, 37 insertions(+), 27 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e519b6d5..dfd3f289 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6747,7 +6747,7 @@ void ImGui::End() IM_ASSERT(g.CurrentWindowStack.Size > 0); // Error checking: verify that user doesn't directly call End() on a child window. - if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive) + if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive) IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!"); // Close anything that is open @@ -12705,7 +12705,7 @@ static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* s IM_ASSERT(src_node && dst_node && dst_node != src_node); ImGuiTabBar* src_tab_bar = src_node->TabBar; if (src_tab_bar != NULL) - IM_ASSERT(src_node->Windows.Size == src_node->TabBar->Tabs.Size); + IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size); // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL); @@ -12717,10 +12717,13 @@ static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* s for (int n = 0; n < src_node->Windows.Size; n++) { - ImGuiWindow* window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n]; - window->DockNode = NULL; - window->DockIsActive = false; - DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true); + // DockNode's TabBar may have non-window Tabs manually appended by user + if (ImGuiWindow* window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n]) + { + window->DockNode = NULL; + window->DockIsActive = false; + DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true); + } } src_node->Windows.clear(); @@ -13233,9 +13236,9 @@ static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - if (tab->Window == NULL) + if (tab->Flags & ImGuiTabItemFlags_Button) continue; - if (Selectable(tab->Window->Name, tab->ID == tab_bar->SelectedTabId)) + if (Selectable(tab_bar->GetTabName(tab), tab->ID == tab_bar->SelectedTabId)) ret_tab_id = tab->ID; SameLine(); Text(" "); @@ -13251,6 +13254,8 @@ bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node) { if (node->TabBar == NULL || node->HostWindow == NULL) return false; + if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly) + return false; Begin(node->HostWindow->Name); PushOverrideID(node->ID); bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node); @@ -13484,7 +13489,7 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w // Forward moving request to selected window if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) - StartMouseMovingWindowOrNode(tab->Window, node, false); + StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); } } @@ -13500,10 +13505,11 @@ static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_w // Apply navigation focus if (focus_tab_id != 0) if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id)) - { - FocusWindow(tab->Window); - NavInitWindow(tab->Window, false); - } + if (tab->Window) + { + FocusWindow(tab->Window); + NavInitWindow(tab->Window, false); + } EndTabBar(); PopID(); @@ -13819,25 +13825,29 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) if (root_payload->DockNodeAsHost) - IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size == root_payload->DockNodeAsHost->TabBar->Tabs.Size); - const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs.Size : 1; + IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size); + ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL; + const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1; for (int payload_n = 0; payload_n < payload_count; payload_n++) { - // Calculate the tab bounding box for each payload window - ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs[payload_n].Window : root_payload; - if (!DockNodeIsDropAllowedOne(payload, host_window)) + // DockNode's TabBar may have non-window Tabs manually appended by user + ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload; + if (tab_bar_with_payload && payload_window == NULL) + continue; + if (!DockNodeIsDropAllowedOne(payload_window, host_window)) continue; - ImVec2 tab_size = TabItemCalcSize(payload->Name, payload->HasCloseButton); + // Calculate the tab bounding box for each payload window + ImVec2 tab_size = TabItemCalcSize(payload_window->Name, payload_window->HasCloseButton); ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y); tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x; for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) { - ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0); + ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0); if (!tab_bar_rect.Contains(tab_bb)) overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max); TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs); - TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload->Name, 0, 0, false); + TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false); if (!tab_bar_rect.Contains(tab_bb)) overlay_draw_lists[overlay_n]->PopClipRect(); } @@ -14358,10 +14368,8 @@ void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags fla // Update the node DockNodeUpdate(node); - g.WithinEndChild = true; End(); ItemSize(size); - g.WithinEndChild = false; } // Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode! @@ -15881,7 +15889,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???"); + p += ImFormatString(p, buf_end - p, "%s'%s'", + tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???"); } p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } @@ -15902,7 +15911,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::PushID(tab); if (ImGui::SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); if (ImGui::SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } ImGui::SameLine(); - ImGui::Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth); + ImGui::Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", + tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???", tab->Offset, tab->Width, tab->ContentWidth); ImGui::PopID(); } ImGui::TreePop(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index cc87c718..5d5d31ee 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7099,7 +7099,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. const char* tab_name = tab_bar->GetTabName(tab); - const bool has_close_button = tab->Window ? tab->Window->HasCloseButton : ((tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0); + const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0; tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x; int section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; @@ -7524,7 +7524,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; } - IM_ASSERT(!(flags & ImGuiTabItemFlags_Button)); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! + IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead! bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) From 31a144b60ca41e5cc5a777b91c53610e068538f3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2020 19:37:18 +0200 Subject: [PATCH 320/959] Fix comments (#3534) --- misc/fonts/binary_to_compressed_c.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/misc/fonts/binary_to_compressed_c.cpp b/misc/fonts/binary_to_compressed_c.cpp index 1f621e16..441c8f67 100644 --- a/misc/fonts/binary_to_compressed_c.cpp +++ b/misc/fonts/binary_to_compressed_c.cpp @@ -10,7 +10,8 @@ // Build with, e.g: // # cl.exe binary_to_compressed_c.cpp -// # gcc binary_to_compressed_c.cpp +// # g++ binary_to_compressed_c.cpp +// # clang++ binary_to_compressed_c.cpp // You can also find a precompiled Windows binary in the binary/demo package available from https://github.com/ocornut/imgui // Usage: From 127f13244730316582bcf230ad55cb20601d1776 Mon Sep 17 00:00:00 2001 From: xndcn Date: Thu, 15 Oct 2020 11:39:08 +0800 Subject: [PATCH 321/959] Backends: OpenGL3: Add compatibility of GL_VERSION for GL 2.x (#3530) GL_MAJOR_VERSION and GL_MINOR_VERSION are available on GL 3.0 and above. So we have to parse GL_VERSION under GL 2.x --- backends/imgui_impl_opengl3.cpp | 10 +++++++++- docs/CHANGELOG.txt | 2 ++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index ed151304..aa0e9e55 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 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-07-10: OpenGL: Added support for glad2 OpenGL loader. // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. @@ -147,9 +148,16 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { // Query for GL version (e.g. 320 for GL 3.2) #if !defined(IMGUI_IMPL_OPENGL_ES2) - GLint major, minor; + GLint major = 0; + GLint minor = 0; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); + if (major == 0 && minor == 0) + { + // Query GL_VERSION in desktop GL 2.x, the string will start with "." + const char* gl_version = (const char*)glGetString(GL_VERSION); + sscanf(gl_version, "%d.%d", &major, &minor); + } g_GlVersion = (GLuint)(major * 100 + minor * 10); #else g_GlVersion = 200; // GLES 2 diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index e91267d3..b20c1a02 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,8 @@ Breaking Changes: Other Changes: - Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. +- Backends: OpenGL: use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) + when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. From d015004f4541892526415dae2086401f110dc60b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 15 Oct 2020 20:05:35 +0200 Subject: [PATCH 322/959] Rename colored>color in comments where possible (#3528) --- imgui.h | 14 +++++++------- imgui_demo.cpp | 12 ++++++------ imgui_widgets.cpp | 4 ++-- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index 01b01f2b..a54e3f9e 100644 --- a/imgui.h +++ b/imgui.h @@ -522,14 +522,14 @@ namespace ImGui IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0); - // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.) + // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); - IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a colored square/button, hover for details, return true when pressed. + IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed. IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. // Widgets: Trees @@ -865,7 +865,7 @@ enum ImGuiTreeNodeFlags_ { ImGuiTreeNodeFlags_None = 0, ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected - ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_Framed = 1 << 1, // Draw frame with background (e.g. for CollapsingHeader) ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) @@ -1249,13 +1249,13 @@ enum ImGuiColorEditFlags_ { ImGuiColorEditFlags_None = 0, ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). - ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square. + ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on color square. ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. - ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs) - ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square). + ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). - ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. + ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. ImGuiColorEditFlags_NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 13353bad..2ce3ddac 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -652,9 +652,9 @@ static void ShowDemoWindowWidgets() static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; ImGui::ColorEdit3("color 1", col1); ImGui::SameLine(); HelpMarker( - "Click on the colored square to open a color picker.\n" + "Click on the color square to open a color picker.\n" "Click and hold to use drag and drop.\n" - "Right-click on the colored square to show options.\n" + "Right-click on the color square to show options.\n" "CTRL+click on individual component to input value.\n"); ImGui::ColorEdit4("color 2", col2); @@ -823,7 +823,7 @@ static void ShowDemoWindowWidgets() if (ImGui::TreeNode("Text")) { - if (ImGui::TreeNode("Colored Text")) + if (ImGui::TreeNode("Colorful Text")) { // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink"); @@ -1405,7 +1405,7 @@ static void ShowDemoWindowWidgets() ImGui::Text("Color widget:"); ImGui::SameLine(); HelpMarker( - "Click on the colored square to open a color picker.\n" + "Click on the color square to open a color picker.\n" "CTRL+click on individual component to input value.\n"); ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags); @@ -1825,7 +1825,7 @@ static void ShowDemoWindowWidgets() // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F // to allow your own widgets to use colors in their drag and drop interaction. // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. - HelpMarker("You can drag from the colored squares."); + HelpMarker("You can drag from the color squares."); static float col1[3] = { 1.0f, 0.0f, 0.2f }; static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f }; ImGui::ColorEdit3("color 1", col1); @@ -3976,7 +3976,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine(); HelpMarker( "In the color list:\n" - "Left-click on colored square to open color picker,\n" + "Left-click on color square to open color picker,\n" "Right-click to open edit options menu."); ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 5da42da5..a908184f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4573,7 +4573,7 @@ bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flag // Edit colors components (each component in 0.0f..1.0f range). // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. -// With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item. +// With typical options: Left-click on color square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) { ImGuiWindow* window = GetCurrentWindow(); @@ -5209,7 +5209,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl return value_changed; } -// A little colored square. Return true when clicked. +// A little color square. Return true when clicked. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. // Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set. From c9fafd5ea4e316996f20067882600676decc97e6 Mon Sep 17 00:00:00 2001 From: Black Cat! Date: Sat, 10 Oct 2020 17:39:06 +0400 Subject: [PATCH 323/959] Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index b20c1a02..c4a8a8bd 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,8 @@ Breaking Changes: Other Changes: - Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. +- Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging + into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] - Backends: OpenGL: use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. diff --git a/imgui.cpp b/imgui.cpp index 81a39cd6..0bb82d23 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9584,7 +9584,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId); ImRect r = g.DragDropTargetRect; float r_surface = r.GetWidth() * r.GetHeight(); - if (r_surface < g.DragDropAcceptIdCurrRectSurface) + if (r_surface <= g.DragDropAcceptIdCurrRectSurface) { g.DragDropAcceptFlags = flags; g.DragDropAcceptIdCurr = g.DragDropTargetId; From 748bd1ba9ce2dd6bdbbf08ef5034f04c37b0a3ca Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Oct 2020 11:32:53 +0200 Subject: [PATCH 324/959] Tab Bar: Restore cursor position in EndTabBar() when amending (amend f2f32602) + made LastTabItemIdx consistent ImS8 as other tab storage relies on same type --- imgui_internal.h | 8 +++++--- imgui_widgets.cpp | 12 +++++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 013c8139..3cdc7792 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1743,10 +1743,11 @@ struct ImGuiTabItem ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; IndexDuringLayout = -1; WantClose = false; } }; -// Storage for a tab bar (sizeof() 92~96 bytes) +// Storage for a tab bar (sizeof() 152 bytes) struct ImGuiTabBar { ImVector Tabs; + ImGuiTabBarFlags Flags; ImGuiID ID; // Zero for tab-bars used by docking ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; @@ -1764,16 +1765,17 @@ struct ImGuiTabBar float ScrollingSpeed; float ScrollingRectMinX; float ScrollingRectMaxX; - ImGuiTabBarFlags Flags; ImGuiID ReorderRequestTabId; ImS8 ReorderRequestDir; ImS8 TabsActiveCount; // Number of tabs submitted this frame. + ImS8 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() + ImS8 BeginCount; bool WantLayout; bool VisibleTabWasSubmitted; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame - short LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() ImVec2 TabsContentsMin; + ImVec2 BackupCursorPos; ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index a908184f..b9346e3d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6802,6 +6802,7 @@ namespace ImGui ImGuiTabBar::ImGuiTabBar() { + Flags = ImGuiTabBarFlags_None; ID = 0; SelectedTabId = NextSelectedTabId = VisibleTabId = 0; CurrFrameVisible = PrevFrameVisible = -1; @@ -6809,12 +6810,12 @@ ImGuiTabBar::ImGuiTabBar() WidthAllTabs = WidthAllTabsIdeal = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; ScrollingRectMinX = ScrollingRectMaxX = 0.0f; - Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; ReorderRequestDir = 0; TabsActiveCount = 0; - WantLayout = VisibleTabWasSubmitted = TabsAddedNew = false; LastTabItemIdx = -1; + BeginCount = 0; + WantLayout = VisibleTabWasSubmitted = TabsAddedNew = false; } static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs) @@ -6878,9 +6879,11 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG g.CurrentTabBar = tab_bar; // Append with multiple BeginTabBar()/EndTabBar() pairs. + tab_bar->BackupCursorPos = window->DC.CursorPos; if (tab_bar->CurrFrameVisible == g.FrameCount) { window->DC.CursorPos = tab_bar->TabsContentsMin; + tab_bar->BeginCount++; return true; } @@ -6903,6 +6906,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->CurrTabsContentsHeight = 0.0f; tab_bar->FramePadding = g.Style.FramePadding; tab_bar->TabsActiveCount = 0; + tab_bar->BeginCount = 1; // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap tab_bar->TabsContentsMin.x = tab_bar->BarRect.Min.x; @@ -6949,6 +6953,8 @@ void ImGui::EndTabBar() { window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight; } + if (tab_bar->BeginCount > 1) + window->DC.CursorPos = tab_bar->BackupCursorPos; if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) PopID(); @@ -7543,7 +7549,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->TabsAddedNew = true; tab_is_new = true; } - tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab); + tab_bar->LastTabItemIdx = (ImS8)tab_bar->Tabs.index_from_ptr(tab); tab->ContentWidth = size.x; tab->BeginOrder = tab_bar->TabsActiveCount++; From 8c9b3c9013167606b7398188a81ac5d106b56b96 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Oct 2020 11:51:38 +0200 Subject: [PATCH 325/959] Tab Bar: Fixed using more than 128 tabs in a tab bar. Using ImS16 consistently + some better packing to avoid struct growing size. --- docs/CHANGELOG.txt | 1 + imgui_internal.h | 10 +++++----- imgui_widgets.cpp | 11 +++++------ 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index c4a8a8bd..3ede8331 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -55,6 +55,7 @@ Breaking Changes: Other Changes: - Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. +- Tab Bar: Fixed using more than 128 tabs in a tab bar (scrolling policy recommended). - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] - Backends: OpenGL: use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) diff --git a/imgui_internal.h b/imgui_internal.h index 3cdc7792..5e408b62 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1736,8 +1736,8 @@ struct ImGuiTabItem float Width; // Width currently displayed float ContentWidth; // Width of label, stored during BeginTabItem() call ImS16 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames - ImS8 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable - ImS8 IndexDuringLayout; // Index only used during TabBarLayout() + ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable + ImS16 IndexDuringLayout; // Index only used during TabBarLayout() bool WantClose; // Marked as closed by SetTabItemClosed() ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; IndexDuringLayout = -1; WantClose = false; } @@ -1767,14 +1767,14 @@ struct ImGuiTabBar float ScrollingRectMaxX; ImGuiID ReorderRequestTabId; ImS8 ReorderRequestDir; - ImS8 TabsActiveCount; // Number of tabs submitted this frame. - ImS8 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() ImS8 BeginCount; bool WantLayout; bool VisibleTabWasSubmitted; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame + ImS16 TabsActiveCount; // Number of tabs submitted this frame. + ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() + float ItemSpacingY; ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() - ImVec2 TabsContentsMin; ImVec2 BackupCursorPos; ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b9346e3d..022012fc 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6882,7 +6882,7 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->BackupCursorPos = window->DC.CursorPos; if (tab_bar->CurrFrameVisible == g.FrameCount) { - window->DC.CursorPos = tab_bar->TabsContentsMin; + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY); tab_bar->BeginCount++; return true; } @@ -6904,14 +6904,13 @@ bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImG tab_bar->CurrFrameVisible = g.FrameCount; tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight; tab_bar->CurrTabsContentsHeight = 0.0f; + tab_bar->ItemSpacingY = g.Style.ItemSpacing.y; tab_bar->FramePadding = g.Style.FramePadding; tab_bar->TabsActiveCount = 0; tab_bar->BeginCount = 1; // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap - tab_bar->TabsContentsMin.x = tab_bar->BarRect.Min.x; - tab_bar->TabsContentsMin.y = tab_bar->BarRect.Max.y + g.Style.ItemSpacing.y; - window->DC.CursorPos = tab_bar->TabsContentsMin; + window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY); // Draw separator const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive); @@ -6990,7 +6989,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n]; tab = &tab_bar->Tabs[tab_dst_n]; - tab->IndexDuringLayout = (ImS8)tab_dst_n; + tab->IndexDuringLayout = (ImS16)tab_dst_n; // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) int curr_tab_section_n = (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1; @@ -7549,7 +7548,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, tab_bar->TabsAddedNew = true; tab_is_new = true; } - tab_bar->LastTabItemIdx = (ImS8)tab_bar->Tabs.index_from_ptr(tab); + tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab); tab->ContentWidth = size.x; tab->BeginOrder = tab_bar->TabsActiveCount++; From fbe74ed50c9aea079dbf4280f4689dffe7ef9d89 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Oct 2020 12:10:31 +0200 Subject: [PATCH 326/959] Tab Bar: zero clear more structures. --- imgui_internal.h | 2 +- imgui_widgets.cpp | 13 +------------ 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5e408b62..72cabb28 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1740,7 +1740,7 @@ struct ImGuiTabItem ImS16 IndexDuringLayout; // Index only used during TabBarLayout() bool WantClose; // Marked as closed by SetTabItemClosed() - ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; BeginOrder = -1; IndexDuringLayout = -1; WantClose = false; } + ImGuiTabItem() { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; NameOffset = BeginOrder = IndexDuringLayout = -1; } }; // Storage for a tab bar (sizeof() 152 bytes) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 022012fc..bb84083e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6802,20 +6802,9 @@ namespace ImGui ImGuiTabBar::ImGuiTabBar() { - Flags = ImGuiTabBarFlags_None; - ID = 0; - SelectedTabId = NextSelectedTabId = VisibleTabId = 0; + memset(this, 0, sizeof(*this)); CurrFrameVisible = PrevFrameVisible = -1; - CurrTabsContentsHeight = PrevTabsContentsHeight = 0.0f; - WidthAllTabs = WidthAllTabsIdeal = 0.0f; - ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; - ScrollingRectMinX = ScrollingRectMaxX = 0.0f; - ReorderRequestTabId = 0; - ReorderRequestDir = 0; - TabsActiveCount = 0; LastTabItemIdx = -1; - BeginCount = 0; - WantLayout = VisibleTabWasSubmitted = TabsAddedNew = false; } static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs) From e6b99a420b74a056da40f9a7af491446f26a29ea Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 19 Oct 2020 15:01:24 +0200 Subject: [PATCH 327/959] Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) --- docs/CHANGELOG.txt | 1 + imgui_internal.h | 2 +- imgui_widgets.cpp | 26 +++++++++++++++++++++----- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 3ede8331..68e30508 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -56,6 +56,7 @@ Other Changes: - Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. - Tab Bar: Fixed using more than 128 tabs in a tab bar (scrolling policy recommended). +- Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] - Backends: OpenGL: use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) diff --git a/imgui_internal.h b/imgui_internal.h index 72cabb28..215f414e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1971,7 +1971,7 @@ namespace ImGui IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags); IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button); IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); - IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible); + IMGUI_API void TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped); // Render helpers // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index bb84083e..fe892451 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7677,7 +7677,9 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Render tab label, process close button const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, id) : 0; - bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible); + bool just_closed; + bool text_clipped; + TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped); if (just_closed && p_open != NULL) { *p_open = false; @@ -7691,7 +7693,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer) // We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores) - if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered()) + if (text_clipped && g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered()) if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip)) SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); @@ -7756,12 +7758,18 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. -bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible) +void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped) { ImGuiContext& g = *GImGui; ImVec2 label_size = CalcTextSize(label, NULL, true); + + if (out_just_closed) + *out_just_closed = false; + if (out_text_clipped) + *out_text_clipped = false; + if (bb.GetWidth() <= 1.0f) - return false; + return; // In Style V2 we'll have full override of all colors per state (e.g. focused, selected) // But right now if you want to alter text color of tabs this is what you need to do. @@ -7782,6 +7790,13 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, } ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; + // 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; + //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)); + } + // Close Button // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() // 'hovered' will be true when hovering the Tab but NOT when hovering the close button @@ -7819,7 +7834,8 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, g.Style.Alpha = backup_alpha; #endif - return close_button_pressed; + if (out_just_closed) + *out_just_closed = close_button_pressed; } From acb8ef200610e0e3618182c8407681090eaa75ec Mon Sep 17 00:00:00 2001 From: Bill Six Date: Wed, 21 Oct 2020 03:13:54 -0400 Subject: [PATCH 328/959] Examples: Vulkan: Fixed CMake include path. (#3550) The backends directory was not included, so the build was failing. --- examples/example_glfw_vulkan/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example_glfw_vulkan/CMakeLists.txt b/examples/example_glfw_vulkan/CMakeLists.txt index 22e17a20..801aee4d 100644 --- a/examples/example_glfw_vulkan/CMakeLists.txt +++ b/examples/example_glfw_vulkan/CMakeLists.txt @@ -25,7 +25,7 @@ include_directories(${GLFW_DIR}/include) # Dear ImGui set(IMGUI_DIR ../../) -include_directories(${IMGUI_DIR} ..) +include_directories(${IMGUI_DIR} ${IMGUI_DIR}/backends ..) # Libraries find_package(Vulkan REQUIRED) From ffe8f0177fb8ca371e5f3195d8399cadf1596483 Mon Sep 17 00:00:00 2001 From: Louis Schnellbach Date: Tue, 20 Oct 2020 10:00:26 +0200 Subject: [PATCH 329/959] Backends: OpenGL3: Backup/restore GL_PRIMITIVE_RESTART state (#3544) --- backends/imgui_impl_opengl3.cpp | 18 ++++++++++++++++++ docs/CHANGELOG.txt | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index aa0e9e55..a26538d7 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -13,6 +13,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-10-23: OpenGL: Save and restore current 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-07-10: OpenGL: Added support for glad2 OpenGL loader. @@ -134,6 +135,11 @@ using namespace gl; #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER #endif +// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART +#endif + // OpenGL Data static GLuint g_GlVersion = 0; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2) static char g_GlslVersionString[32] = ""; // Specified by user or detected based on compile time GL settings. @@ -244,6 +250,10 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART + if (g_GlVersion >= 310) + glDisable(GL_PRIMITIVE_RESTART); +#endif #ifdef GL_POLYGON_MODE glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif @@ -334,6 +344,9 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART + GLboolean last_enable_primitive_restart = g_GlVersion >= 310 ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; +#endif // Setup desired GL state // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) @@ -419,6 +432,11 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART + if (g_GlVersion >= 310) + if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); +#endif + #ifdef GL_POLYGON_MODE glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); #endif diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 68e30508..bd709286 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,8 +59,9 @@ Other Changes: - Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] -- Backends: OpenGL: use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) +- Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] +- Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. From 5292320110b9ee3a303d055cd39fc6963b66150f Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 23 Oct 2020 11:25:26 +0200 Subject: [PATCH 330/959] Amend ffe8f0177fb8ca371e5f3195d8399cadf1596483 (#3544) + readme fixes --- backends/imgui_impl_opengl3.cpp | 5 ++--- docs/README.md | 8 ++++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index a26538d7..c70cfd6c 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -345,7 +345,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - GLboolean last_enable_primitive_restart = g_GlVersion >= 310 ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; + GLboolean last_enable_primitive_restart = (g_GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; #endif // Setup desired GL state @@ -433,8 +433,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART - if (g_GlVersion >= 310) - if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); + if (g_GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } #endif #ifdef GL_POLYGON_MODE diff --git a/docs/README.md b/docs/README.md index a946315f..35b08f9c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -110,7 +110,7 @@ The demo applications are not DPI aware so expect some blurriness on a 4K screen ### Integration -On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/examples) files without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more of the imgui_impl_xxxx files instead of rewriting them: this will be less work for you and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. +On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/backends) backends without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more of the imgui_impl_xxxx files instead of rewriting them: this will be less work for you and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading one texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that. If you are an experienced programmer at ease with those concepts, it should take you less than two hours to integrate Dear ImGui in your custom engine. **Make sure to spend time reading the [FAQ](https://www.dearimgui.org/faq), comments, and some of the examples/ application!** @@ -129,10 +129,10 @@ Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. ### Upcoming Changes Some of the goals for 2020 are: -- Work on docking. (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch) -- Work on multiple viewports / multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) -- Work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) - Work on new Tables API (to replace Columns). (see [#2957](https://github.com/ocornut/imgui/issues/2957), in public [tables](https://github.com/ocornut/imgui/tree/tables) branch looking for feedback) +- Work on Docking (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch) +- Work on Multi-Viewport / Multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) +- Work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) - Work on automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) - Make the examples look better, improve styles, improve font support, make the examples hi-DPI and multi-DPI aware. From bca4749346bd250127a8324bf7f5342ba0d6afcc Mon Sep 17 00:00:00 2001 From: Warren Moore Date: Sun, 18 Oct 2020 13:24:35 -0700 Subject: [PATCH 331/959] Examples: Apple: Consolidated example_apple_metal to reduce class and file count (#1873, #3543) --- docs/CHANGELOG.txt | 1 + .../example_apple_metal/Shared/AppDelegate.h | 18 - .../example_apple_metal/Shared/AppDelegate.m | 11 - .../example_apple_metal/Shared/Renderer.h | 8 - .../example_apple_metal/Shared/Renderer.mm | 154 ------- .../Shared/ViewController.h | 19 - .../Shared/ViewController.mm | 153 ------- examples/example_apple_metal/Shared/main.m | 22 - .../project.pbxproj | 153 +++---- .../iOS/Base.lproj/Main.storyboard | 28 -- .../iOS/Default-568h@2x.png | Bin 1673 -> 0 bytes .../example_apple_metal/iOS/Info-iOS.plist | 4 +- ...een.storyboard => LaunchScreen.storyboard} | 12 +- .../macOS/Info-macOS.plist | 4 +- .../Main.storyboard => MainMenu.storyboard} | 43 +- examples/example_apple_metal/main.mm | 378 ++++++++++++++++++ 16 files changed, 443 insertions(+), 565 deletions(-) delete mode 100644 examples/example_apple_metal/Shared/AppDelegate.h delete mode 100644 examples/example_apple_metal/Shared/AppDelegate.m delete mode 100644 examples/example_apple_metal/Shared/Renderer.h delete mode 100644 examples/example_apple_metal/Shared/Renderer.mm delete mode 100644 examples/example_apple_metal/Shared/ViewController.h delete mode 100644 examples/example_apple_metal/Shared/ViewController.mm delete mode 100644 examples/example_apple_metal/Shared/main.m delete mode 100644 examples/example_apple_metal/iOS/Base.lproj/Main.storyboard delete mode 100644 examples/example_apple_metal/iOS/Default-568h@2x.png rename examples/example_apple_metal/iOS/{Launch Screen.storyboard => LaunchScreen.storyboard} (69%) rename examples/example_apple_metal/macOS/{Base.lproj/Main.storyboard => MainMenu.storyboard} (68%) create mode 100644 examples/example_apple_metal/main.mm diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index bd709286..7c3f32c8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -62,6 +62,7 @@ Other Changes: - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] +- Examples: Apple+Metal: Consolidated/simplified to get closer to other examples. (#3543) [@warrenm] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. diff --git a/examples/example_apple_metal/Shared/AppDelegate.h b/examples/example_apple_metal/Shared/AppDelegate.h deleted file mode 100644 index 94878d94..00000000 --- a/examples/example_apple_metal/Shared/AppDelegate.h +++ /dev/null @@ -1,18 +0,0 @@ -#import - -#if TARGET_OS_IPHONE - -#import - -@interface AppDelegate : UIResponder -@property (strong, nonatomic) UIWindow *window; -@end - -#else - -#import - -@interface AppDelegate : NSObject -@end - -#endif diff --git a/examples/example_apple_metal/Shared/AppDelegate.m b/examples/example_apple_metal/Shared/AppDelegate.m deleted file mode 100644 index 6947eb23..00000000 --- a/examples/example_apple_metal/Shared/AppDelegate.m +++ /dev/null @@ -1,11 +0,0 @@ -#import "AppDelegate.h" - -@implementation AppDelegate - -#if TARGET_OS_OSX -- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { - return YES; -} -#endif - -@end diff --git a/examples/example_apple_metal/Shared/Renderer.h b/examples/example_apple_metal/Shared/Renderer.h deleted file mode 100644 index 81fc6f54..00000000 --- a/examples/example_apple_metal/Shared/Renderer.h +++ /dev/null @@ -1,8 +0,0 @@ -#import - -@interface Renderer : NSObject - --(nonnull instancetype)initWithView:(nonnull MTKView *)view; - -@end - diff --git a/examples/example_apple_metal/Shared/Renderer.mm b/examples/example_apple_metal/Shared/Renderer.mm deleted file mode 100644 index c121f692..00000000 --- a/examples/example_apple_metal/Shared/Renderer.mm +++ /dev/null @@ -1,154 +0,0 @@ -#import "Renderer.h" -#import - -#include "imgui.h" -#include "imgui_impl_metal.h" - -#if TARGET_OS_OSX -#include "imgui_impl_osx.h" -#endif - -@interface Renderer () -@property (nonatomic, strong) id device; -@property (nonatomic, strong) id commandQueue; -@end - -@implementation Renderer - --(nonnull instancetype)initWithView:(nonnull MTKView*)view; -{ - self = [super init]; - if(self) - { - _device = view.device; - _commandQueue = [_device newCommandQueue]; - - // Setup Dear ImGui context - // FIXME: This example doesn't have proper cleanup... - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - - // Setup Dear ImGui style - ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); - - // Setup Renderer backend - ImGui_ImplMetal_Init(_device); - - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. - // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); - } - - return self; -} - -- (void)drawInMTKView:(MTKView*)view -{ - ImGuiIO &io = ImGui::GetIO(); - io.DisplaySize.x = view.bounds.size.width; - io.DisplaySize.y = view.bounds.size.height; - -#if TARGET_OS_OSX - CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor; -#else - CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale; -#endif - io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale); - - io.DeltaTime = 1 / float(view.preferredFramesPerSecond ?: 60); - - id commandBuffer = [self.commandQueue commandBuffer]; - - // Our state (make them static = more or less global) as a convenience to keep the example terse. - static bool show_demo_window = true; - static bool show_another_window = false; - static float clear_color[4] = { 0.28f, 0.36f, 0.5f, 1.0f }; - - MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor; - if (renderPassDescriptor != nil) - { - renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0], clear_color[1], clear_color[2], clear_color[3]); - - // Here, you could do additional rendering work, including other passes as necessary. - - id renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; - [renderEncoder pushDebugGroup:@"ImGui demo"]; - - // Start the Dear ImGui frame - ImGui_ImplMetal_NewFrame(renderPassDescriptor); -#if TARGET_OS_OSX - ImGui_ImplOSX_NewFrame(view); -#endif - ImGui::NewFrame(); - - // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). - if (show_demo_window) - ImGui::ShowDemoWindow(&show_demo_window); - - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. - { - static float f = 0.0f; - static int counter = 0; - - ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. - - ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) - ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state - ImGui::Checkbox("Another Window", &show_another_window); - - ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color - - if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) - counter++; - ImGui::SameLine(); - ImGui::Text("counter = %d", counter); - - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); - ImGui::End(); - } - - // 3. Show another simple window. - if (show_another_window) - { - ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) - ImGui::Text("Hello from another window!"); - if (ImGui::Button("Close Me")) - show_another_window = false; - ImGui::End(); - } - - // Rendering - ImGui::Render(); - ImDrawData* drawData = ImGui::GetDrawData(); - ImGui_ImplMetal_RenderDrawData(drawData, commandBuffer, renderEncoder); - - [renderEncoder popDebugGroup]; - [renderEncoder endEncoding]; - - [commandBuffer presentDrawable:view.currentDrawable]; - } - - [commandBuffer commit]; -} - -- (void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size -{ -} - -@end diff --git a/examples/example_apple_metal/Shared/ViewController.h b/examples/example_apple_metal/Shared/ViewController.h deleted file mode 100644 index 137f93e1..00000000 --- a/examples/example_apple_metal/Shared/ViewController.h +++ /dev/null @@ -1,19 +0,0 @@ -#import -#import -#import "Renderer.h" - -#if TARGET_OS_IPHONE - -#import - -@interface ViewController : UIViewController -@end - -#else - -#import - -@interface ViewController : NSViewController -@end - -#endif diff --git a/examples/example_apple_metal/Shared/ViewController.mm b/examples/example_apple_metal/Shared/ViewController.mm deleted file mode 100644 index 3c79cc1c..00000000 --- a/examples/example_apple_metal/Shared/ViewController.mm +++ /dev/null @@ -1,153 +0,0 @@ -#import "ViewController.h" -#import "Renderer.h" -#include "imgui.h" - -#if TARGET_OS_OSX -#include "imgui_impl_osx.h" -#endif - -@interface ViewController () -@property (nonatomic, readonly) MTKView *mtkView; -@property (nonatomic, strong) Renderer *renderer; -@end - -@implementation ViewController - -- (MTKView *)mtkView { - return (MTKView *)self.view; -} - -- (void)viewDidLoad -{ - [super viewDidLoad]; - - self.mtkView.device = MTLCreateSystemDefaultDevice(); - - if (!self.mtkView.device) { - NSLog(@"Metal is not supported"); - abort(); - } - - self.renderer = [[Renderer alloc] initWithView:self.mtkView]; - - [self.renderer mtkView:self.mtkView drawableSizeWillChange:self.mtkView.bounds.size]; - - self.mtkView.delegate = self.renderer; - -#if TARGET_OS_OSX - // Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view - NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect - options:NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways - owner:self - userInfo:nil]; - [self.view addTrackingArea:trackingArea]; - - // If we want to receive key events, we either need to be in the responder chain of the key view, - // or else we can install a local monitor. The consequence of this heavy-handed approach is that - // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our - // window, we'd want to be much more careful than just ingesting the complete event stream, though we - // do make an effort to be good citizens by passing along events when Dear ImGui doesn't want to capture. - NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged | NSEventTypeScrollWheel; - [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) { - BOOL wantsCapture = ImGui_ImplOSX_HandleEvent(event, self.view); - if (event.type == NSEventTypeKeyDown && wantsCapture) { - return nil; - } else { - return event; - } - - }]; - - ImGui_ImplOSX_Init(); -#endif -} - -#if TARGET_OS_OSX - -- (void)mouseMoved:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)mouseDown:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)rightMouseDown:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)otherMouseDown:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)mouseUp:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)rightMouseUp:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)otherMouseUp:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)mouseDragged:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)rightMouseDragged:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)otherMouseDragged:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -- (void)scrollWheel:(NSEvent *)event { - ImGui_ImplOSX_HandleEvent(event, self.view); -} - -#elif TARGET_OS_IOS - -// This touch mapping is super cheesy/hacky. We treat any touch on the screen -// as if it were a depressed left mouse button, and we don't bother handling -// multitouch correctly at all. This causes the "cursor" to behave very erratically -// when there are multiple active touches. But for demo purposes, single-touch -// interaction actually works surprisingly well. -- (void)updateIOWithTouchEvent:(UIEvent *)event { - UITouch *anyTouch = event.allTouches.anyObject; - CGPoint touchLocation = [anyTouch locationInView:self.view]; - ImGuiIO &io = ImGui::GetIO(); - io.MousePos = ImVec2(touchLocation.x, touchLocation.y); - - BOOL hasActiveTouch = NO; - for (UITouch *touch in event.allTouches) { - if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled) { - hasActiveTouch = YES; - break; - } - } - io.MouseDown[0] = hasActiveTouch; -} - -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { - [self updateIOWithTouchEvent:event]; -} - -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { - [self updateIOWithTouchEvent:event]; -} - -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { - [self updateIOWithTouchEvent:event]; -} - -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { - [self updateIOWithTouchEvent:event]; -} - -#endif - -@end - diff --git a/examples/example_apple_metal/Shared/main.m b/examples/example_apple_metal/Shared/main.m deleted file mode 100644 index 15938a90..00000000 --- a/examples/example_apple_metal/Shared/main.m +++ /dev/null @@ -1,22 +0,0 @@ -#import - -#if TARGET_OS_IPHONE - -#import -#import "AppDelegate.h" - -int main(int argc, char * argv[]) { - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } -} - -#else - -#import - -int main(int argc, const char * argv[]) { - return NSApplicationMain(argc, argv); -} - -#endif diff --git a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj index 38c45cfd..f382520f 100644 --- a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj +++ b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj @@ -9,27 +9,19 @@ /* Begin PBXBuildFile section */ 07A82ED82139413D0078D120 /* imgui_widgets.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07A82ED72139413C0078D120 /* imgui_widgets.cpp */; }; 07A82ED92139418F0078D120 /* imgui_widgets.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07A82ED72139413C0078D120 /* imgui_widgets.cpp */; }; - 8307E7CC20E9F9C900473790 /* ViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7CB20E9F9C900473790 /* ViewController.mm */; }; - 8307E7CF20E9F9C900473790 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8307E7CD20E9F9C900473790 /* Main.storyboard */; }; - 8307E7DE20E9F9C900473790 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7DD20E9F9C900473790 /* AppDelegate.m */; }; - 8307E7E420E9F9C900473790 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8307E7E220E9F9C900473790 /* Main.storyboard */; }; - 8307E7E720E9F9C900473790 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7E620E9F9C900473790 /* main.m */; }; - 8307E7E820E9F9C900473790 /* Renderer.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7BC20E9F9C700473790 /* Renderer.mm */; }; - 8307E7E920E9F9C900473790 /* Renderer.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7BC20E9F9C700473790 /* Renderer.mm */; }; - 836D2A2E20EE208E0098E909 /* imgui_impl_osx.mm in Sources */ = {isa = PBXBuildFile; fileRef = 836D2A2D20EE208E0098E909 /* imgui_impl_osx.mm */; }; - 836D2A3020EE4A180098E909 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 836D2A2F20EE4A180098E909 /* Default-568h@2x.png */; }; - 836D2A3220EE4A900098E909 /* Launch Screen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 836D2A3120EE4A900098E909 /* Launch Screen.storyboard */; }; - 83BBE9DE20EB3FFC00295997 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7E620E9F9C900473790 /* main.m */; }; - 83BBE9DF20EB40AE00295997 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7DD20E9F9C900473790 /* AppDelegate.m */; }; - 83BBE9E020EB42D000295997 /* ViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8307E7CB20E9F9C900473790 /* ViewController.mm */; }; + 8309BD8F253CCAAA0045E2A1 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8309BD8E253CCAAA0045E2A1 /* UIKit.framework */; }; + 8309BDA5253CCC070045E2A1 /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8309BDA0253CCBC10045E2A1 /* main.mm */; }; + 8309BDA8253CCC080045E2A1 /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8309BDA0253CCBC10045E2A1 /* main.mm */; }; + 8309BDBB253CCCAD0045E2A1 /* imgui_impl_metal.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8309BDB5253CCC9D0045E2A1 /* imgui_impl_metal.mm */; }; + 8309BDBE253CCCB60045E2A1 /* imgui_impl_metal.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8309BDB5253CCC9D0045E2A1 /* imgui_impl_metal.mm */; }; + 8309BDBF253CCCB60045E2A1 /* imgui_impl_osx.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8309BDB6253CCC9D0045E2A1 /* imgui_impl_osx.mm */; }; + 8309BDC6253CCCFE0045E2A1 /* AppKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8309BDC5253CCCFE0045E2A1 /* AppKit.framework */; }; + 8309BDFC253CDAB30045E2A1 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8309BDF7253CDAAE0045E2A1 /* LaunchScreen.storyboard */; }; + 8309BE04253CDAB60045E2A1 /* MainMenu.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8309BDFA253CDAAE0045E2A1 /* MainMenu.storyboard */; }; 83BBE9E520EB46B900295997 /* Metal.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83BBE9E420EB46B900295997 /* Metal.framework */; }; 83BBE9E720EB46BD00295997 /* MetalKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83BBE9E620EB46BD00295997 /* MetalKit.framework */; }; - 83BBE9E920EB46C100295997 /* ModelIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83BBE9E820EB46C100295997 /* ModelIO.framework */; }; 83BBE9EC20EB471700295997 /* MetalKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83BBE9EA20EB471700295997 /* MetalKit.framework */; }; 83BBE9ED20EB471700295997 /* Metal.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83BBE9EB20EB471700295997 /* Metal.framework */; }; - 83BBE9EF20EB471C00295997 /* ModelIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83BBE9EE20EB471C00295997 /* ModelIO.framework */; }; - 83BBE9FE20EB54D800295997 /* imgui_impl_metal.mm in Sources */ = {isa = PBXBuildFile; fileRef = 83BBE9FD20EB54D800295997 /* imgui_impl_metal.mm */; }; - 83BBE9FF20EB54D800295997 /* imgui_impl_metal.mm in Sources */ = {isa = PBXBuildFile; fileRef = 83BBE9FD20EB54D800295997 /* imgui_impl_metal.mm */; }; 83BBEA0520EB54E700295997 /* imgui_draw.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 83BBEA0120EB54E700295997 /* imgui_draw.cpp */; }; 83BBEA0620EB54E700295997 /* imgui_draw.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 83BBEA0120EB54E700295997 /* imgui_draw.cpp */; }; 83BBEA0720EB54E700295997 /* imgui_demo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 83BBEA0220EB54E700295997 /* imgui_demo.cpp */; }; @@ -41,31 +33,23 @@ /* Begin PBXFileReference section */ 07A82ED62139413C0078D120 /* imgui_internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_internal.h; path = ../../imgui_internal.h; sourceTree = ""; }; 07A82ED72139413C0078D120 /* imgui_widgets.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_widgets.cpp; path = ../../imgui_widgets.cpp; sourceTree = ""; }; - 8307E7BB20E9F9C700473790 /* Renderer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Renderer.h; sourceTree = ""; }; - 8307E7BC20E9F9C700473790 /* Renderer.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = Renderer.mm; sourceTree = ""; }; 8307E7C420E9F9C900473790 /* example_apple_metal.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example_apple_metal.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 8307E7CA20E9F9C900473790 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; - 8307E7CB20E9F9C900473790 /* ViewController.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = ViewController.mm; sourceTree = ""; }; - 8307E7CE20E9F9C900473790 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 8307E7D320E9F9C900473790 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; 8307E7DA20E9F9C900473790 /* example_apple_metal.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example_apple_metal.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 8307E7DC20E9F9C900473790 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 8307E7DD20E9F9C900473790 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 8307E7E320E9F9C900473790 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 8307E7E520E9F9C900473790 /* Info-macOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; - 8307E7E620E9F9C900473790 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - 836D2A2C20EE208D0098E909 /* imgui_impl_osx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_osx.h; path = ../../../backends/imgui_impl_osx.h; sourceTree = ""; }; - 836D2A2D20EE208E0098E909 /* imgui_impl_osx.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_osx.mm; path = ../../../backends/imgui_impl_osx.mm; sourceTree = ""; }; - 836D2A2F20EE4A180098E909 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = ""; }; - 836D2A3120EE4A900098E909 /* Launch Screen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = "Launch Screen.storyboard"; sourceTree = ""; }; + 8309BD8E253CCAAA0045E2A1 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 8309BDA0253CCBC10045E2A1 /* main.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = main.mm; sourceTree = ""; }; + 8309BDB5253CCC9D0045E2A1 /* imgui_impl_metal.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_metal.mm; path = ../../backends/imgui_impl_metal.mm; sourceTree = ""; }; + 8309BDB6253CCC9D0045E2A1 /* imgui_impl_osx.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_osx.mm; path = ../../backends/imgui_impl_osx.mm; sourceTree = ""; }; + 8309BDC5253CCCFE0045E2A1 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; }; + 8309BDF7253CDAAE0045E2A1 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; + 8309BDF8253CDAAE0045E2A1 /* Info-iOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-iOS.plist"; sourceTree = ""; }; + 8309BDFA253CDAAE0045E2A1 /* MainMenu.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = MainMenu.storyboard; sourceTree = ""; }; + 8309BDFB253CDAAE0045E2A1 /* Info-macOS.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Info-macOS.plist"; sourceTree = ""; }; 83BBE9E420EB46B900295997 /* Metal.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Metal.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.4.sdk/System/Library/Frameworks/Metal.framework; sourceTree = DEVELOPER_DIR; }; 83BBE9E620EB46BD00295997 /* MetalKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MetalKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.4.sdk/System/Library/Frameworks/MetalKit.framework; sourceTree = DEVELOPER_DIR; }; 83BBE9E820EB46C100295997 /* ModelIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ModelIO.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.4.sdk/System/Library/Frameworks/ModelIO.framework; sourceTree = DEVELOPER_DIR; }; 83BBE9EA20EB471700295997 /* MetalKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MetalKit.framework; path = System/Library/Frameworks/MetalKit.framework; sourceTree = SDKROOT; }; 83BBE9EB20EB471700295997 /* Metal.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Metal.framework; path = System/Library/Frameworks/Metal.framework; sourceTree = SDKROOT; }; 83BBE9EE20EB471C00295997 /* ModelIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ModelIO.framework; path = System/Library/Frameworks/ModelIO.framework; sourceTree = SDKROOT; }; - 83BBE9FC20EB54D800295997 /* imgui_impl_metal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_impl_metal.h; path = ../../../backends/imgui_impl_metal.h; sourceTree = ""; }; - 83BBE9FD20EB54D800295997 /* imgui_impl_metal.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = imgui_impl_metal.mm; path = ../../../backends/imgui_impl_metal.mm; sourceTree = ""; }; 83BBEA0020EB54E700295997 /* imgui.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui.h; path = ../../imgui.h; sourceTree = ""; }; 83BBEA0120EB54E700295997 /* imgui_draw.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_draw.cpp; path = ../../imgui_draw.cpp; sourceTree = ""; }; 83BBEA0220EB54E700295997 /* imgui_demo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_demo.cpp; path = ../../imgui_demo.cpp; sourceTree = ""; }; @@ -78,7 +62,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 83BBE9E920EB46C100295997 /* ModelIO.framework in Frameworks */, + 8309BD8F253CCAAA0045E2A1 /* UIKit.framework in Frameworks */, 83BBE9E720EB46BD00295997 /* MetalKit.framework in Frameworks */, 83BBE9E520EB46B900295997 /* Metal.framework in Frameworks */, ); @@ -88,7 +72,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 83BBE9EF20EB471C00295997 /* ModelIO.framework in Frameworks */, + 8309BDC6253CCCFE0045E2A1 /* AppKit.framework in Frameworks */, 83BBE9EC20EB471700295997 /* MetalKit.framework in Frameworks */, 83BBE9ED20EB471700295997 /* Metal.framework in Frameworks */, ); @@ -101,57 +85,45 @@ isa = PBXGroup; children = ( 83BBE9F020EB544400295997 /* imgui */, - 8307E7BA20E9F9C700473790 /* Shared */, - 8307E7C620E9F9C900473790 /* iOS */, - 8307E7DB20E9F9C900473790 /* macOS */, + 8309BD9E253CCBA70045E2A1 /* example */, 8307E7C520E9F9C900473790 /* Products */, 83BBE9E320EB46B800295997 /* Frameworks */, ); sourceTree = ""; }; - 8307E7BA20E9F9C700473790 /* Shared */ = { + 8307E7C520E9F9C900473790 /* Products */ = { isa = PBXGroup; children = ( - 83BBE9FC20EB54D800295997 /* imgui_impl_metal.h */, - 83BBE9FD20EB54D800295997 /* imgui_impl_metal.mm */, - 836D2A2C20EE208D0098E909 /* imgui_impl_osx.h */, - 836D2A2D20EE208E0098E909 /* imgui_impl_osx.mm */, - 8307E7DC20E9F9C900473790 /* AppDelegate.h */, - 8307E7DD20E9F9C900473790 /* AppDelegate.m */, - 8307E7BB20E9F9C700473790 /* Renderer.h */, - 8307E7BC20E9F9C700473790 /* Renderer.mm */, - 8307E7CA20E9F9C900473790 /* ViewController.h */, - 8307E7CB20E9F9C900473790 /* ViewController.mm */, - 8307E7E620E9F9C900473790 /* main.m */, + 8307E7C420E9F9C900473790 /* example_apple_metal.app */, + 8307E7DA20E9F9C900473790 /* example_apple_metal.app */, ); - path = Shared; + name = Products; sourceTree = ""; }; - 8307E7C520E9F9C900473790 /* Products */ = { + 8309BD9E253CCBA70045E2A1 /* example */ = { isa = PBXGroup; children = ( - 8307E7C420E9F9C900473790 /* example_apple_metal.app */, - 8307E7DA20E9F9C900473790 /* example_apple_metal.app */, + 8309BDF6253CDAAE0045E2A1 /* iOS */, + 8309BDF9253CDAAE0045E2A1 /* macOS */, + 8309BDA0253CCBC10045E2A1 /* main.mm */, ); - name = Products; + name = example; sourceTree = ""; }; - 8307E7C620E9F9C900473790 /* iOS */ = { + 8309BDF6253CDAAE0045E2A1 /* iOS */ = { isa = PBXGroup; children = ( - 836D2A2F20EE4A180098E909 /* Default-568h@2x.png */, - 8307E7CD20E9F9C900473790 /* Main.storyboard */, - 8307E7D320E9F9C900473790 /* Info-iOS.plist */, - 836D2A3120EE4A900098E909 /* Launch Screen.storyboard */, + 8309BDF7253CDAAE0045E2A1 /* LaunchScreen.storyboard */, + 8309BDF8253CDAAE0045E2A1 /* Info-iOS.plist */, ); path = iOS; sourceTree = ""; }; - 8307E7DB20E9F9C900473790 /* macOS */ = { + 8309BDF9253CDAAE0045E2A1 /* macOS */ = { isa = PBXGroup; children = ( - 8307E7E220E9F9C900473790 /* Main.storyboard */, - 8307E7E520E9F9C900473790 /* Info-macOS.plist */, + 8309BDFA253CDAAE0045E2A1 /* MainMenu.storyboard */, + 8309BDFB253CDAAE0045E2A1 /* Info-macOS.plist */, ); path = macOS; sourceTree = ""; @@ -159,6 +131,8 @@ 83BBE9E320EB46B800295997 /* Frameworks */ = { isa = PBXGroup; children = ( + 8309BDC5253CCCFE0045E2A1 /* AppKit.framework */, + 8309BD8E253CCAAA0045E2A1 /* UIKit.framework */, 83BBE9EE20EB471C00295997 /* ModelIO.framework */, 83BBE9EB20EB471700295997 /* Metal.framework */, 83BBE9EA20EB471700295997 /* MetalKit.framework */, @@ -172,6 +146,8 @@ 83BBE9F020EB544400295997 /* imgui */ = { isa = PBXGroup; children = ( + 8309BDB5253CCC9D0045E2A1 /* imgui_impl_metal.mm */, + 8309BDB6253CCC9D0045E2A1 /* imgui_impl_osx.mm */, 83BBEA0420EB54E700295997 /* imconfig.h */, 83BBEA0320EB54E700295997 /* imgui.cpp */, 83BBEA0020EB54E700295997 /* imgui.h */, @@ -226,7 +202,7 @@ 8307E7B620E9F9C700473790 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0940; + LastUpgradeCheck = 1200; ORGANIZATIONNAME = "Warren Moore"; TargetAttributes = { 8307E7C320E9F9C900473790 = { @@ -263,9 +239,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 836D2A3220EE4A900098E909 /* Launch Screen.storyboard in Resources */, - 8307E7CF20E9F9C900473790 /* Main.storyboard in Resources */, - 836D2A3020EE4A180098E909 /* Default-568h@2x.png in Resources */, + 8309BDFC253CDAB30045E2A1 /* LaunchScreen.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -273,7 +247,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 8307E7E420E9F9C900473790 /* Main.storyboard in Resources */, + 8309BE04253CDAB60045E2A1 /* MainMenu.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -284,15 +258,12 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 8307E7E820E9F9C900473790 /* Renderer.mm in Sources */, - 8307E7CC20E9F9C900473790 /* ViewController.mm in Sources */, + 8309BDBB253CCCAD0045E2A1 /* imgui_impl_metal.mm in Sources */, 83BBEA0520EB54E700295997 /* imgui_draw.cpp in Sources */, - 83BBE9DF20EB40AE00295997 /* AppDelegate.m in Sources */, 83BBEA0920EB54E700295997 /* imgui.cpp in Sources */, 83BBEA0720EB54E700295997 /* imgui_demo.cpp in Sources */, - 83BBE9FE20EB54D800295997 /* imgui_impl_metal.mm in Sources */, 07A82ED82139413D0078D120 /* imgui_widgets.cpp in Sources */, - 83BBE9DE20EB3FFC00295997 /* main.m in Sources */, + 8309BDA5253CCC070045E2A1 /* main.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -300,40 +271,18 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 83BBE9E020EB42D000295997 /* ViewController.mm in Sources */, - 8307E7E920E9F9C900473790 /* Renderer.mm in Sources */, + 8309BDBE253CCCB60045E2A1 /* imgui_impl_metal.mm in Sources */, + 8309BDBF253CCCB60045E2A1 /* imgui_impl_osx.mm in Sources */, 83BBEA0620EB54E700295997 /* imgui_draw.cpp in Sources */, 07A82ED92139418F0078D120 /* imgui_widgets.cpp in Sources */, - 8307E7E720E9F9C900473790 /* main.m in Sources */, 83BBEA0A20EB54E700295997 /* imgui.cpp in Sources */, 83BBEA0820EB54E700295997 /* imgui_demo.cpp in Sources */, - 83BBE9FF20EB54D800295997 /* imgui_impl_metal.mm in Sources */, - 836D2A2E20EE208E0098E909 /* imgui_impl_osx.mm in Sources */, - 8307E7DE20E9F9C900473790 /* AppDelegate.m in Sources */, + 8309BDA8253CCC080045E2A1 /* main.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ -/* Begin PBXVariantGroup section */ - 8307E7CD20E9F9C900473790 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 8307E7CE20E9F9C900473790 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 8307E7E220E9F9C900473790 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 8307E7E320E9F9C900473790 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - /* Begin XCBuildConfiguration section */ 8307E7EE20E9F9C900473790 /* Debug */ = { isa = XCBuildConfiguration; @@ -361,6 +310,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -416,6 +366,7 @@ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; @@ -451,6 +402,7 @@ PRODUCT_NAME = example_apple_metal; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/../../**"; }; name = Debug; }; @@ -467,6 +419,7 @@ PRODUCT_NAME = example_apple_metal; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/../../**"; VALIDATE_PRODUCT = YES; }; name = Release; @@ -484,6 +437,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "org.imgui.example.apple-metal-macos"; PRODUCT_NAME = example_apple_metal; SDKROOT = macosx; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/../../**"; }; name = Debug; }; @@ -500,6 +454,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "org.imgui.example.apple-metal-macos"; PRODUCT_NAME = example_apple_metal; SDKROOT = macosx; + USER_HEADER_SEARCH_PATHS = "$(SRCROOT)/../../**"; }; name = Release; }; diff --git a/examples/example_apple_metal/iOS/Base.lproj/Main.storyboard b/examples/example_apple_metal/iOS/Base.lproj/Main.storyboard deleted file mode 100644 index 24a4009e..00000000 --- a/examples/example_apple_metal/iOS/Base.lproj/Main.storyboard +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/example_apple_metal/iOS/Default-568h@2x.png b/examples/example_apple_metal/iOS/Default-568h@2x.png deleted file mode 100644 index e3ce940a36b6bebefdc8944e931dac246a1ec425..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1673 zcmeHGJ7^R^7@j;(2?=PCLaT98iQdl4CimDSYfNtMyoGEyFAE;nxVJk=mSi8l0%a#sB~l zdQEEpFuVi6Xn1CXdyE^C62H!~N|P-IE39or6wEt8i$dMAR%wG;PP+M?&H^wp>6%T} zG!_**@I))ah=~_+HUP78Nod*Yl))BVb$wO%`f68zuA>S!^9DA;GF@|P+Yw#fUNY_N zbz63XxvOwCQMiCdnFSMX!;h6j6*{^Ke`jtazz&41tHM!IO`{IWK}2C*EaYr5gJDq? zNdeE~$rUJJQbah9a3P0@f=h}-VD|_-TI8%K4XxUZ#Vu7>V=Pn8D%9PCZg`mu zB@v7H4#Y4N-H(~&+f>(7fs;hnbre$2uq0Qfi^YX1A(c|8f~Cqd(MkneDCeuV$JGLR z%cDN)ah+rC%s_57eJ|vZH5$2hs8fvs4|b|l+`+k!fqGr8GdLG%AQ$muP&UgyX4`Y| zg~^`%P31;^*Qw7JJmQ=D?os-X|AJHXMYF>1G)*trpNssX9qQV=nH+rCe>(y2`0$J8 zzxLfHpU&M{-0>fbn?DanYx1?Zy~}&2vrlw#PCD>kc3^Yp!;jG#dGlI7I~2X#eF{dv Wx9{NM<9i1mvwHN(lJ;!j_TAqnTQ0Z& diff --git a/examples/example_apple_metal/iOS/Info-iOS.plist b/examples/example_apple_metal/iOS/Info-iOS.plist index 8d919d1e..93ef078d 100644 --- a/examples/example_apple_metal/iOS/Info-iOS.plist +++ b/examples/example_apple_metal/iOS/Info-iOS.plist @@ -21,9 +21,7 @@ LSRequiresIPhoneOS UILaunchStoryboardName - Launch Screen - UIMainStoryboardFile - Main + LaunchScreen UIRequiredDeviceCapabilities armv7 diff --git a/examples/example_apple_metal/iOS/Launch Screen.storyboard b/examples/example_apple_metal/iOS/LaunchScreen.storyboard similarity index 69% rename from examples/example_apple_metal/iOS/Launch Screen.storyboard rename to examples/example_apple_metal/iOS/LaunchScreen.storyboard index 96047e1f..12c52cfb 100644 --- a/examples/example_apple_metal/iOS/Launch Screen.storyboard +++ b/examples/example_apple_metal/iOS/LaunchScreen.storyboard @@ -1,11 +1,9 @@ - - - - + + - + @@ -15,10 +13,10 @@ - + - + diff --git a/examples/example_apple_metal/macOS/Info-macOS.plist b/examples/example_apple_metal/macOS/Info-macOS.plist index 52d99204..6f4a2b23 100644 --- a/examples/example_apple_metal/macOS/Info-macOS.plist +++ b/examples/example_apple_metal/macOS/Info-macOS.plist @@ -22,10 +22,8 @@ 1 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) - NSHumanReadableCopyright - Copyright © 2018 Warren Moore. All rights reserved. NSMainStoryboardFile - Main + MainMenu NSPrincipalClass NSApplication diff --git a/examples/example_apple_metal/macOS/Base.lproj/Main.storyboard b/examples/example_apple_metal/macOS/MainMenu.storyboard similarity index 68% rename from examples/example_apple_metal/macOS/Base.lproj/Main.storyboard rename to examples/example_apple_metal/macOS/MainMenu.storyboard index cf414617..38ad432b 100644 --- a/examples/example_apple_metal/macOS/Base.lproj/Main.storyboard +++ b/examples/example_apple_metal/macOS/MainMenu.storyboard @@ -1,9 +1,8 @@ - + - - + @@ -16,8 +15,6 @@ - - @@ -90,41 +87,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm new file mode 100644 index 00000000..ec6482ee --- /dev/null +++ b/examples/example_apple_metal/main.mm @@ -0,0 +1,378 @@ + +#import + +#if TARGET_OS_OSX +#import +#else +#import +#endif + +#import +#import + +#include "imgui.h" +#include "imgui_impl_metal.h" + +#if TARGET_OS_OSX +#include "imgui_impl_osx.h" + +@interface ViewController : NSViewController +@end +#else +@interface ViewController : UIViewController +@end +#endif + +@interface ViewController () +@property (nonatomic, readonly) MTKView *mtkView; +@property (nonatomic, strong) id device; +@property (nonatomic, strong) id commandQueue; +@end + +@implementation ViewController + +- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil { + self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; + + _device = MTLCreateSystemDefaultDevice(); + _commandQueue = [_device newCommandQueue]; + + if (!self.device) { + NSLog(@"Metal is not supported"); + abort(); + } + + // Setup Dear ImGui context + // FIXME: This example doesn't have proper cleanup... + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + + // Setup Renderer backend + ImGui_ImplMetal_Init(_device); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Read 'docs/FONTS.txt' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != NULL); + + return self; +} + +- (MTKView *)mtkView { + return (MTKView *)self.view; +} + +- (void)loadView { + self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)]; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.mtkView.device = self.device; + self.mtkView.delegate = self; + +#if TARGET_OS_OSX + // Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view + NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect + options:NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways + owner:self + userInfo:nil]; + [self.view addTrackingArea:trackingArea]; + + // If we want to receive key events, we either need to be in the responder chain of the key view, + // or else we can install a local monitor. The consequence of this heavy-handed approach is that + // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our + // window, we'd want to be much more careful than just ingesting the complete event stream, though we + // do make an effort to be good citizens by passing along events when Dear ImGui doesn't want to capture. + NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged | NSEventTypeScrollWheel; + [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) { + BOOL wantsCapture = ImGui_ImplOSX_HandleEvent(event, self.view); + if (event.type == NSEventTypeKeyDown && wantsCapture) { + return nil; + } else { + return event; + } + + }]; + + ImGui_ImplOSX_Init(); + +#endif +} + +#pragma mark - Interaction + +#if TARGET_OS_OSX + +- (void)mouseMoved:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)mouseDown:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)rightMouseDown:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseDown:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)mouseUp:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)rightMouseUp:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseUp:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)mouseDragged:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)rightMouseDragged:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)otherMouseDragged:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +- (void)scrollWheel:(NSEvent *)event { + ImGui_ImplOSX_HandleEvent(event, self.view); +} + +#else + +// This touch mapping is super cheesy/hacky. We treat any touch on the screen +// as if it were a depressed left mouse button, and we don't bother handling +// multitouch correctly at all. This causes the "cursor" to behave very erratically +// when there are multiple active touches. But for demo purposes, single-touch +// interaction actually works surprisingly well. +- (void)updateIOWithTouchEvent:(UIEvent *)event { + UITouch *anyTouch = event.allTouches.anyObject; + CGPoint touchLocation = [anyTouch locationInView:self.view]; + ImGuiIO &io = ImGui::GetIO(); + io.MousePos = ImVec2(touchLocation.x, touchLocation.y); + + BOOL hasActiveTouch = NO; + for (UITouch *touch in event.allTouches) { + if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled) { + hasActiveTouch = YES; + break; + } + } + io.MouseDown[0] = hasActiveTouch; +} + +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { + [self updateIOWithTouchEvent:event]; +} + +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { + [self updateIOWithTouchEvent:event]; +} + +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { + [self updateIOWithTouchEvent:event]; +} + +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { + [self updateIOWithTouchEvent:event]; +} + +#endif + +#pragma mark - MTKViewDelegate + +- (void)drawInMTKView:(MTKView*)view +{ + ImGuiIO &io = ImGui::GetIO(); + io.DisplaySize.x = view.bounds.size.width; + io.DisplaySize.y = view.bounds.size.height; + +#if TARGET_OS_OSX + CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor; +#else + CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale; +#endif + io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale); + + io.DeltaTime = 1 / float(view.preferredFramesPerSecond ?: 60); + + id commandBuffer = [self.commandQueue commandBuffer]; + + // Our state (make them static = more or less global) as a convenience to keep the example terse. + static bool show_demo_window = true; + static bool show_another_window = false; + static float clear_color[4] = { 0.28f, 0.36f, 0.5f, 1.0f }; + + MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor; + if (renderPassDescriptor != nil) + { + renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0], clear_color[1], clear_color[2], clear_color[3]); + + // Here, you could do additional rendering work, including other passes as necessary. + + id renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor]; + [renderEncoder pushDebugGroup:@"ImGui demo"]; + + // Start the Dear ImGui frame + ImGui_ImplMetal_NewFrame(renderPassDescriptor); +#if TARGET_OS_OSX + ImGui_ImplOSX_NewFrame(view); +#endif + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + ImDrawData* drawData = ImGui::GetDrawData(); + ImGui_ImplMetal_RenderDrawData(drawData, commandBuffer, renderEncoder); + + [renderEncoder popDebugGroup]; + [renderEncoder endEncoding]; + + [commandBuffer presentDrawable:view.currentDrawable]; + } + + [commandBuffer commit]; +} + +- (void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size +{ +} + +@end + +#pragma mark - Application Delegate + +#if TARGET_OS_OSX + +@interface AppDelegate : NSObject +@property (nonatomic, strong) NSWindow *window; +@end + +@implementation AppDelegate + +- (instancetype)init { + if (self = [super init]) { + NSViewController *rootViewController = [[ViewController alloc] initWithNibName:nil bundle:nil]; + self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect + styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable + backing:NSBackingStoreBuffered + defer:NO]; + self.window.contentViewController = rootViewController; + [self.window orderFront:self]; + [self.window center]; + [self.window becomeKeyWindow]; + } + return self; +} + +- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { + return YES; +} + +@end + +#else + +@interface AppDelegate : UIResponder +@property (strong, nonatomic) UIWindow *window; +@end + +@implementation AppDelegate + +- (BOOL)application:(UIApplication *)application + didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + UIViewController *rootViewController = [[ViewController alloc] init]; + self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds]; + self.window.rootViewController = rootViewController; + [self.window makeKeyAndVisible]; + return YES; +} + +@end + +#endif + +#pragma mark - main() + +#if TARGET_OS_OSX + +int main(int argc, const char * argv[]) { + return NSApplicationMain(argc, argv); +} + +#else + +int main(int argc, char * argv[]) { + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} + +#endif From b3576dd35409a3a3ad742bb74122e14fcda2d886 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 23 Sep 2020 14:35:46 +0300 Subject: [PATCH 332/959] Replace UTF-8 decoder with branchless version by Christopher Wellons. Decoding performance increase ranges from 30-40%. Changes: * Errors handling near the end of string changed. If input does not contain enough bytes, decoder returns `IM_UNICODE_CODEPOINT_INVALID`, consuming all remaining bytes while old decoder consumed only one byte. Guarantees: * At least one byte is consumed, if input had at least one byte available. * Number of consumed bytes will never seek past end of string. Requirements: * `in_text` is a valid pointer. * String pointed by `in_text` must be zero-terminated, or `in_text_end` is not NULL. --- docs/CHANGELOG.txt | 3 ++ imgui.cpp | 107 +++++++++++++++++++++------------------------ 2 files changed, 53 insertions(+), 57 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7c3f32c8..33e84373 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,9 @@ Other Changes: - Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] +- Misc: Replaced UTF-8 decoder by branchless one by Christopher Wellons (30~40% faster). [@rokups] + Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder + returns IM_UNICODE_CODEPOINT_INVALID and consume remaining bytes (vs old decoded consumed only 1 byte). - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] diff --git a/imgui.cpp b/imgui.cpp index 0bb82d23..d8b7d5ed 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1553,66 +1553,59 @@ void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_f //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bit character, process single character input. -// Based on stb_from_utf8() from github.com/nothings/stb/ +// Based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8) // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { - unsigned int c = (unsigned int)-1; - const unsigned char* str = (const unsigned char*)in_text; - if (!(*str & 0x80)) - { - c = (unsigned int)(*str++); - *out_char = c; - return 1; - } - if ((*str & 0xe0) == 0xc0) - { - *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string - if (in_text_end && in_text_end - (const char*)str < 2) return 1; - if (*str < 0xc2) return 2; - c = (unsigned int)((*str++ & 0x1f) << 6); - if ((*str & 0xc0) != 0x80) return 2; - c += (*str++ & 0x3f); - *out_char = c; - return 2; - } - if ((*str & 0xf0) == 0xe0) - { - *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string - if (in_text_end && in_text_end - (const char*)str < 3) return 1; - if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; - if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x0f) << 12); - if ((*str & 0xc0) != 0x80) return 3; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 3; - c += (*str++ & 0x3f); - *out_char = c; - return 3; - } - if ((*str & 0xf8) == 0xf0) - { - *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string - if (in_text_end && in_text_end - (const char*)str < 4) return 1; - if (*str > 0xf4) return 4; - if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; - if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x07) << 18); - if ((*str & 0xc0) != 0x80) return 4; - c += (unsigned int)((*str++ & 0x3f) << 12); - if ((*str & 0xc0) != 0x80) return 4; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 4; - c += (*str++ & 0x3f); - // utf-8 encodings of values used in surrogate pairs are invalid - if ((c & 0xFFFFF800) == 0xD800) return 4; - // If codepoint does not fit in ImWchar, use replacement character U+FFFD instead - if (c > IM_UNICODE_CODEPOINT_MAX) c = IM_UNICODE_CODEPOINT_INVALID; - *out_char = c; - return 4; - } - *out_char = 0; - return 0; + static const char lengths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 }; + static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 }; + static const uint32_t mins[] = { 4194304, 0, 128, 2048, 65536 }; + static const int shiftc[] = { 0, 18, 12, 6, 0 }; + static const int shifte[] = { 0, 6, 4, 2, 0 }; + unsigned char s[4]; + int len = lengths[*(const unsigned char*)in_text >> 3]; + + if (in_text_end == NULL) + in_text_end = in_text + len + !len; // Max length, nulls will be taken into account. + + // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. + s[0] = in_text + 0 < in_text_end ? in_text[0] : 0; + s[1] = s[0] && in_text + 1 < in_text_end ? in_text[1] : 0; + s[2] = s[1] && in_text + 2 < in_text_end ? in_text[2] : 0; + s[3] = s[2] && in_text + 3 < in_text_end ? in_text[3] : 0; + + // Compute the pointer to the next character early so that the next + // iteration can start working on the next character. Neither Clang + // nor GCC figure out this reordering on their own. + //const unsigned char *next = s + len + !len; + + // No bytes are consumed when *in_text == 0 || in_text == in_text_end. + // One byte is consumed in case of invalid first byte of in_text. + // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. + int consumed = !!s[0] + !!s[1] + !!s[2] + !!s[3]; + + // Assume a four-byte character and load four bytes. Unused bits are shifted out. + *out_char = (uint32_t)(s[0] & masks[len]) << 18; + *out_char |= (uint32_t)(s[1] & 0x3f) << 12; + *out_char |= (uint32_t)(s[2] & 0x3f) << 6; + *out_char |= (uint32_t)(s[3] & 0x3f) << 0; + *out_char >>= shiftc[len]; + + // Accumulate the various error conditions. + int e = 0; + e = (*out_char < mins[len]) << 6; // non-canonical encoding + e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half? + e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range? + e |= (s[1] & 0xc0) >> 2; + e |= (s[2] & 0xc0) >> 4; + e |= (s[3] ) >> 6; + e ^= 0x2a; // top two bits of each tail byte correct? + e >>= shifte[len]; + + if (e) + *out_char = IM_UNICODE_CODEPOINT_INVALID; + + return consumed; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) From b7530e5d04fcd9d5859c089244f562be82b4c531 Mon Sep 17 00:00:00 2001 From: ocornut Date: Sun, 25 Oct 2020 16:27:32 +0100 Subject: [PATCH 333/959] Revert "Replace UTF-8 decoder with branchless version by Christopher Wellons." (#3558) This reverts commit b3576dd35409a3a3ad742bb74122e14fcda2d886. --- docs/CHANGELOG.txt | 3 -- imgui.cpp | 107 ++++++++++++++++++++++++--------------------- 2 files changed, 57 insertions(+), 53 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 33e84373..7c3f32c8 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,9 +59,6 @@ Other Changes: - Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] -- Misc: Replaced UTF-8 decoder by branchless one by Christopher Wellons (30~40% faster). [@rokups] - Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder - returns IM_UNICODE_CODEPOINT_INVALID and consume remaining bytes (vs old decoded consumed only 1 byte). - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] diff --git a/imgui.cpp b/imgui.cpp index d8b7d5ed..0bb82d23 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1553,59 +1553,66 @@ void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_f //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bit character, process single character input. -// Based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8) +// Based on stb_from_utf8() from github.com/nothings/stb/ // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { - static const char lengths[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 }; - static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 }; - static const uint32_t mins[] = { 4194304, 0, 128, 2048, 65536 }; - static const int shiftc[] = { 0, 18, 12, 6, 0 }; - static const int shifte[] = { 0, 6, 4, 2, 0 }; - unsigned char s[4]; - int len = lengths[*(const unsigned char*)in_text >> 3]; - - if (in_text_end == NULL) - in_text_end = in_text + len + !len; // Max length, nulls will be taken into account. - - // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. - s[0] = in_text + 0 < in_text_end ? in_text[0] : 0; - s[1] = s[0] && in_text + 1 < in_text_end ? in_text[1] : 0; - s[2] = s[1] && in_text + 2 < in_text_end ? in_text[2] : 0; - s[3] = s[2] && in_text + 3 < in_text_end ? in_text[3] : 0; - - // Compute the pointer to the next character early so that the next - // iteration can start working on the next character. Neither Clang - // nor GCC figure out this reordering on their own. - //const unsigned char *next = s + len + !len; - - // No bytes are consumed when *in_text == 0 || in_text == in_text_end. - // One byte is consumed in case of invalid first byte of in_text. - // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. - int consumed = !!s[0] + !!s[1] + !!s[2] + !!s[3]; - - // Assume a four-byte character and load four bytes. Unused bits are shifted out. - *out_char = (uint32_t)(s[0] & masks[len]) << 18; - *out_char |= (uint32_t)(s[1] & 0x3f) << 12; - *out_char |= (uint32_t)(s[2] & 0x3f) << 6; - *out_char |= (uint32_t)(s[3] & 0x3f) << 0; - *out_char >>= shiftc[len]; - - // Accumulate the various error conditions. - int e = 0; - e = (*out_char < mins[len]) << 6; // non-canonical encoding - e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half? - e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range? - e |= (s[1] & 0xc0) >> 2; - e |= (s[2] & 0xc0) >> 4; - e |= (s[3] ) >> 6; - e ^= 0x2a; // top two bits of each tail byte correct? - e >>= shifte[len]; - - if (e) - *out_char = IM_UNICODE_CODEPOINT_INVALID; - - return consumed; + unsigned int c = (unsigned int)-1; + const unsigned char* str = (const unsigned char*)in_text; + if (!(*str & 0x80)) + { + c = (unsigned int)(*str++); + *out_char = c; + return 1; + } + if ((*str & 0xe0) == 0xc0) + { + *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 2) return 1; + if (*str < 0xc2) return 2; + c = (unsigned int)((*str++ & 0x1f) << 6); + if ((*str & 0xc0) != 0x80) return 2; + c += (*str++ & 0x3f); + *out_char = c; + return 2; + } + if ((*str & 0xf0) == 0xe0) + { + *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 3) return 1; + if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; + if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x0f) << 12); + if ((*str & 0xc0) != 0x80) return 3; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 3; + c += (*str++ & 0x3f); + *out_char = c; + return 3; + } + if ((*str & 0xf8) == 0xf0) + { + *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 4) return 1; + if (*str > 0xf4) return 4; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; + if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x07) << 18); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 12); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 4; + c += (*str++ & 0x3f); + // utf-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xFFFFF800) == 0xD800) return 4; + // If codepoint does not fit in ImWchar, use replacement character U+FFFD instead + if (c > IM_UNICODE_CODEPOINT_MAX) c = IM_UNICODE_CODEPOINT_INVALID; + *out_char = c; + return 4; + } + *out_char = 0; + return 0; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) From df351573977af584d61a0a4437bcaef8db71bf6e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 26 Oct 2020 14:40:44 +0100 Subject: [PATCH 334/959] Drag and Drop: Fix losing drop source ActiveID (and often source tooltip) when opening a TreeNode() or CollapsingHeader() while dragging. (#1738) Amend 7b3d379, 8241cd62 etc. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7c3f32c8..a18eb357 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -57,6 +57,8 @@ Other Changes: - Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. - Tab Bar: Fixed using more than 128 tabs in a tab bar (scrolling policy recommended). - Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) +- Drag and Drop: Fix losing drop source ActiveID (and often source tooltip) when opening a TreeNode() + or CollapsingHeader() while dragging. (#1738) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) diff --git a/imgui.cpp b/imgui.cpp index 0bb82d23..af632a8e 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -9425,6 +9425,8 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) g.DragDropActive = true; g.DragDropSourceFlags = flags; g.DragDropMouseButton = mouse_button; + if (payload.SourceId == g.ActiveId) + g.ActiveIdNoClearOnFocusLoss = true; } g.DragDropSourceFrameCount = g.FrameCount; g.DragDropWithinSource = true; From 6f57d58e825e7c5c740b82acb636f17e49f76c7f Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 28 Oct 2020 11:35:27 +0200 Subject: [PATCH 335/959] Backends: OSX: Fix KeyPadEnter on MacOS. (#3554) --- backends/imgui_impl_osx.mm | 3 ++- docs/CHANGELOG.txt | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index bf643e29..fc347a40 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -18,6 +18,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-10-28: Inputs: Added a fix for handling keypad-enter key. // 2020-05-25: Inputs: Added a fix for missing trackpad clicks when done with "soft tap". // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-10-11: Inputs: Fix using Backspace key. @@ -72,7 +73,7 @@ bool ImGui_ImplOSX_Init() io.KeyMap[ImGuiKey_Space] = 32; io.KeyMap[ImGuiKey_Enter] = 13; io.KeyMap[ImGuiKey_Escape] = 27; - io.KeyMap[ImGuiKey_KeyPadEnter] = 13; + io.KeyMap[ImGuiKey_KeyPadEnter] = 3; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a18eb357..ce65396a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,9 +61,10 @@ Other Changes: or CollapsingHeader() while dragging. (#1738) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] -- Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) +- Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] +- Backends: OSX: Fix keypad-enter key not working on MacOS. (#3554) [@rokups, @lfnoise] - Examples: Apple+Metal: Consolidated/simplified to get closer to other examples. (#3543) [@warrenm] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. @@ -98,7 +99,7 @@ Other Changes: - Window: Fixed using non-zero pivot in SetNextWindowPos() when the window is collapsed. (#3433) - Nav: Fixed navigation resuming on first visible item when using gamepad. [@rokups] - Nav: Fixed using Alt to toggle the Menu layer when inside a Modal window. (#787) -- Scrolling: Fixed SetScrollHere(0) functions edge snapping when called during a frame where +- Scrolling: Fixed SetScrollHere(0) functions edge snapping when called during a frame where ContentSize is changing (issue introduced in 1.78). (#3452). - InputText: Added support for Page Up/Down in InputTextMultiline(). (#3430) [@Xipiryon] - InputText: Added selection helpers in ImGuiInputTextCallbackData(). From a129621292a98454d8d636c2daca063f0fb3e3f3 Mon Sep 17 00:00:00 2001 From: "M. Frink ~ Lemur" Date: Thu, 29 Oct 2020 12:21:06 -0500 Subject: [PATCH 336/959] Doc: mention IMGUI_USE_WCHAR32 in fonts documentation (#3562) --- docs/FONTS.md | 1 + imconfig.h | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/FONTS.md b/docs/FONTS.md index 87e6ee04..96573402 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -157,6 +157,7 @@ Some solutions: 3. Set `io.Fonts.TexDesiredWidth` to specify a texture width to minimize texture height (see comment in `ImFontAtlas::Build()` function). 4. Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. 5. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample). +6. To support the extended range of unicode beyond 0xFFFF (e.g. emoticons, dingbats, symbols, shapes, ancient languages, etc...) add `#define IMGUI_USE_WCHAR32`in your `imconfig.h` ##### [Return to Index](#index) diff --git a/imconfig.h b/imconfig.h index 280d1436..015540f3 100644 --- a/imconfig.h +++ b/imconfig.h @@ -49,7 +49,7 @@ //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) //#define IMGUI_USE_BGRA_PACKED_COLOR -//---- Use 32-bit for ImWchar (default is 16-bit) to support full unicode code points. +//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) //#define IMGUI_USE_WCHAR32 //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version From 044ed22379a068498482c7f0d76f9952908d5cc5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 Oct 2020 22:40:44 +0100 Subject: [PATCH 337/959] Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer + omitting trailing empty ImDrawCmd in count + relying on IdxOffset value. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 49 +++++++++++++++++++++++----------------------- imgui_widgets.cpp | 2 +- 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ce65396a..5118fece 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -61,6 +61,7 @@ Other Changes: or CollapsingHeader() while dragging. (#1738) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] +- Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] diff --git a/imgui.cpp b/imgui.cpp index af632a8e..a8599afb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -76,7 +76,7 @@ CODE // [SECTION] LOGGING/CAPTURING // [SECTION] SETTINGS // [SECTION] PLATFORM DEPENDENT HELPERS -// [SECTION] METRICS/DEBUG WINDOW +// [SECTION] METRICS/DEBUGGER WINDOW */ @@ -10328,10 +10328,11 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} #endif //----------------------------------------------------------------------------- -// [SECTION] METRICS/DEBUG WINDOW +// [SECTION] METRICS/DEBUGGER WINDOW //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_METRICS_WINDOW + // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. static void MetricsHelpMarker(const char* desc) { @@ -10401,26 +10402,23 @@ void ImGui::ShowMetricsWindow(bool* p_open) return ImRect(); } - static void NodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, int elem_offset, bool show_mesh, bool show_aabb) + static void NodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb) { IM_ASSERT(show_mesh || show_aabb); ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset; // Draw wire-frame version of all triangles ImRect clip_rect = draw_cmd->ClipRect; ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); ImDrawListFlags backup_flags = fg_draw_list->Flags; fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. - for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + draw_cmd->ElemCount); base_idx += 3) + for (unsigned int idx_n = draw_cmd->IdxOffset; idx_n < draw_cmd->IdxOffset + draw_cmd->ElemCount; ) { ImVec2 triangle[3]; - for (int n = 0; n < 3; n++) - { - ImVec2 p = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos; - triangle[n] = p; - vtxs_rect.Add(p); - } + for (int n = 0; n < 3; n++, idx_n++) + vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos)); if (show_mesh) fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); // In yellow: mesh triangles } @@ -10435,7 +10433,10 @@ void ImGui::ShowMetricsWindow(bool* p_open) static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label) { - bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); + int cmd_count = draw_list->CmdBuffer.Size; + if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL) + cmd_count--; + bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); @@ -10453,36 +10454,34 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (window && !window->WasActive) ImGui::TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!"); - unsigned int elem_offset = 0; - for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++) { - if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0) - continue; if (pcmd->UserCallback) { ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); continue; } - ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; char buf[300]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d triangles, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (ImGui::IsItemHovered() && (show_drawcmd_mesh || show_drawcmd_aabb) && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, show_drawcmd_mesh, show_drawcmd_aabb); + NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, show_drawcmd_mesh, show_drawcmd_aabb); if (!pcmd_node_open) continue; // Calculate approximate coverage area (touched pixel count) // This will be in pixels squared as long there's no post-scaling happening to the renderer output. + const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset; float total_area = 0.0f; - for (unsigned int base_idx = elem_offset; base_idx < (elem_offset + pcmd->ElemCount); base_idx += 3) + for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; ) { ImVec2 triangle[3]; - for (int n = 0; n < 3; n++) - triangle[n] = draw_list->VtxBuffer[idx_buffer ? idx_buffer[base_idx + n] : (base_idx + n)].pos; + for (int n = 0; n < 3; n++, idx_n++) + triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos; total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]); } @@ -10490,19 +10489,19 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); ImGui::Selectable(buf); if (ImGui::IsItemHovered() && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, elem_offset, true, false); + NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, true, false); // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. ImGuiListClipper clipper; clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) - for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) + for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) { char* buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangle[3]; for (int n = 0; n < 3; n++, idx_i++) { - ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[idx_i] : idx_i]; + const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i]; triangle[n] = v.pos; buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); @@ -10774,7 +10773,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { - ImGui::InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, 0.0f), ImGuiInputTextFlags_ReadOnly); + ImGui::InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); ImGui::TreePop(); } ImGui::TreePop(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index fe892451..9b440878 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6539,7 +6539,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) // If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin(). // We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame. - // If somehow this is ever becoming a problem we can switch to use e.g. a ImGuiStorager mapping key to last frame used. + // If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used. if (g.MenusIdSubmittedThisFrame.contains(id)) { if (menu_is_open) From 047d4c4500fc08b64d800eceae9951fc01c0a78b Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 30 Oct 2020 23:02:54 +0100 Subject: [PATCH 338/959] Metrics: Extracted most functions. + avoid using full namesapce prefix --- imgui.cpp | 755 ++++++++++++++++++++++++----------------------- imgui_internal.h | 33 +++ 2 files changed, 419 insertions(+), 369 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index a8599afb..0effb3b4 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10330,6 +10330,17 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} //----------------------------------------------------------------------------- // [SECTION] METRICS/DEBUGGER WINDOW //----------------------------------------------------------------------------- +// - MetricsHelpMarker() [Internal] +// - ShowMetricsWindow() +// - DebugNodeColumns() [Internal] +// - DebugNodeDrawList() [Internal] +// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal] +// - DebugNodeStorage() [Internal] +// - DebugNodeTabBar() [Internal] +// - DebugNodeWindow() [Internal] +// - DebugNodeWindowSettings() [Internal] +// - DebugNodeWindowsList() [Internal] +//----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_METRICS_WINDOW @@ -10349,30 +10360,17 @@ static void MetricsHelpMarker(const char* desc) void ImGui::ShowMetricsWindow(bool* p_open) { - if (!ImGui::Begin("Dear ImGui Metrics", p_open)) + if (!Begin("Dear ImGui Metrics", p_open)) { - ImGui::End(); + End(); return; } - // Debugging enums - enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type - const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" }; - enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type - const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; - - // State - static bool show_windows_rects = false; - static int show_windows_rect_type = WRT_WorkRect; - static bool show_windows_begin_order = false; - static bool show_tables_rects = false; - static int show_tables_rect_type = TRT_WorkRect; - static bool show_drawcmd_mesh = true; - static bool show_drawcmd_aabb = true; + ImGuiContext& g = *GImGui; + ImGuiIO& io = g.IO; + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; // Basic info - ImGuiContext& g = *GImGui; - ImGuiIO& io = ImGui::GetIO(); ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); @@ -10380,13 +10378,16 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Text("%d active allocations", io.MetricsActiveAllocations); ImGui::Separator(); - // Helper functions to display common structures: - // - NodeDrawList() - // - NodeColumns() - // - NodeWindow() - // - NodeWindows() - // - NodeTabBar() - // - NodeStorage() + // Debugging enums + enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type + const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" }; + enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type + const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; + if (cfg->ShowWindowsRectsType < 0) + cfg->ShowWindowsRectsType = WRT_WorkRect; + if (cfg->ShowTablesRectsType < 0) + cfg->ShowWindowsRectsType = TRT_WorkRect; + struct Funcs { static ImRect GetWindowRect(ImGuiWindow* window, int rect_type) @@ -10401,422 +10402,174 @@ void ImGui::ShowMetricsWindow(bool* p_open) IM_ASSERT(0); return ImRect(); } - - static void NodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb) - { - IM_ASSERT(show_mesh || show_aabb); - ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list - ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; - ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset; - - // Draw wire-frame version of all triangles - ImRect clip_rect = draw_cmd->ClipRect; - ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); - ImDrawListFlags backup_flags = fg_draw_list->Flags; - fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. - for (unsigned int idx_n = draw_cmd->IdxOffset; idx_n < draw_cmd->IdxOffset + draw_cmd->ElemCount; ) - { - ImVec2 triangle[3]; - for (int n = 0; n < 3; n++, idx_n++) - vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos)); - if (show_mesh) - fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); // In yellow: mesh triangles - } - // Draw bounding boxes - if (show_aabb) - { - fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU - fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles - } - fg_draw_list->Flags = backup_flags; - } - - static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label) - { - int cmd_count = draw_list->CmdBuffer.Size; - if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL) - cmd_count--; - bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count); - if (draw_list == ImGui::GetWindowDrawList()) - { - ImGui::SameLine(); - ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) - if (node_open) ImGui::TreePop(); - return; - } - - ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list - if (window && IsItemHovered()) - fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); - if (!node_open) - return; - - if (window && !window->WasActive) - ImGui::TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!"); - - for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++) - { - if (pcmd->UserCallback) - { - ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); - continue; - } - - char buf[300]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", - pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId, - pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); - bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); - if (ImGui::IsItemHovered() && (show_drawcmd_mesh || show_drawcmd_aabb) && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, show_drawcmd_mesh, show_drawcmd_aabb); - if (!pcmd_node_open) - continue; - - // Calculate approximate coverage area (touched pixel count) - // This will be in pixels squared as long there's no post-scaling happening to the renderer output. - const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; - const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset; - float total_area = 0.0f; - for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; ) - { - ImVec2 triangle[3]; - for (int n = 0; n < 3; n++, idx_n++) - triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos; - total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]); - } - - // Display vertex information summary. Hover to get all triangles drawn in wire-frame - ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); - ImGui::Selectable(buf); - if (ImGui::IsItemHovered() && fg_draw_list) - NodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, true, false); - - // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. - ImGuiListClipper clipper; - clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. - while (clipper.Step()) - for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) - { - char* buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); - ImVec2 triangle[3]; - for (int n = 0; n < 3; n++, idx_i++) - { - const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i]; - triangle[n] = v.pos; - buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", - (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); - } - - ImGui::Selectable(buf, false); - if (fg_draw_list && ImGui::IsItemHovered()) - { - ImDrawListFlags backup_flags = fg_draw_list->Flags; - fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. - fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255,255,0,255), true, 1.0f); - fg_draw_list->Flags = backup_flags; - } - } - ImGui::TreePop(); - } - ImGui::TreePop(); - } - - static void NodeColumns(const ImGuiColumns* columns) - { - if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) - return; - ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); - for (int column_n = 0; column_n < columns->Columns.Size; column_n++) - ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm)); - ImGui::TreePop(); - } - - static void NodeWindows(ImVector& windows, const char* label) - { - if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) - return; - ImGui::Text("(In front-to-back order:)"); - for (int i = windows.Size - 1; i >= 0; i--) // Iterate front to back - { - ImGui::PushID(windows[i]); - Funcs::NodeWindow(windows[i], "Window"); - ImGui::PopID(); - } - ImGui::TreePop(); - } - - static void NodeWindow(ImGuiWindow* window, const char* label) - { - if (window == NULL) - { - ImGui::BulletText("%s: NULL", label); - return; - } - - ImGuiContext& g = *GImGui; - const bool is_active = window->WasActive; - ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; - if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } - const bool open = ImGui::TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*"); - if (!is_active) { PopStyleColor(); } - if (ImGui::IsItemHovered() && is_active) - ImGui::GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); - if (!open) - return; - - if (window->MemoryCompacted) - ImGui::TextDisabled("Note: some memory buffers have been compacted/freed."); - - ImGuiWindowFlags flags = window->Flags; - NodeDrawList(window, window->DrawList, "DrawList"); - ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y); - ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, - (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", - (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", - (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); - ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : ""); - ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); - ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); - ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); - ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); - if (!window->NavRectRel[0].IsInverted()) - ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y); - else - ImGui::BulletText("NavRectRel[0]: "); - if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); - if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow"); - if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); - if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) - { - for (int n = 0; n < window->ColumnsStorage.Size; n++) - NodeColumns(&window->ColumnsStorage[n]); - ImGui::TreePop(); - } - NodeStorage(&window->StateStorage, "Storage"); - ImGui::TreePop(); - } - - static void NodeWindowSettings(ImGuiWindowSettings* settings) - { - ImGui::Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d", - settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed); - } - - static void NodeTabBar(ImGuiTabBar* tab_bar) - { - // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. - char buf[256]; - char* p = buf; - const char* buf_end = buf + IM_ARRAYSIZE(buf); - const bool is_active = (tab_bar->PrevFrameVisible >= ImGui::GetFrameCount() - 2); - p += ImFormatString(p, buf_end - p, "Tab Bar 0x%08X (%d tabs)%s", tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); - IM_UNUSED(p); - if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } - bool open = ImGui::TreeNode(tab_bar, "%s", buf); - if (!is_active) { PopStyleColor(); } - if (is_active && ImGui::IsItemHovered()) - { - ImDrawList* draw_list = ImGui::GetForegroundDrawList(); - draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); - draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); - draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); - } - if (open) - { - for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) - { - const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; - ImGui::PushID(tab); - if (ImGui::SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); - if (ImGui::SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } ImGui::SameLine(); - ImGui::Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "", tab->Offset, tab->Width, tab->ContentWidth); - ImGui::PopID(); - } - ImGui::TreePop(); - } - } - - static void NodeStorage(ImGuiStorage* storage, const char* label) - { - if (!ImGui::TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes())) - return; - for (int n = 0; n < storage->Data.Size; n++) - { - const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n]; - ImGui::BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer. - } - ImGui::TreePop(); - } }; // Tools - if (ImGui::TreeNode("Tools")) + if (TreeNode("Tools")) { // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted. - if (ImGui::Button("Item Picker..")) - ImGui::DebugStartItemPicker(); - ImGui::SameLine(); + if (Button("Item Picker..")) + DebugStartItemPicker(); + SameLine(); MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash."); - ImGui::Checkbox("Show windows begin order", &show_windows_begin_order); - ImGui::Checkbox("Show windows rectangles", &show_windows_rects); - ImGui::SameLine(); - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count, WRT_Count); - if (show_windows_rects && g.NavWindow) + Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder); + ImGui::Checkbox("Show windows rectangles", &cfg->ShowWindowsRects); + SameLine(); + SetNextItemWidth(GetFontSize() * 12); + cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count); + if (cfg->ShowWindowsRects && g.NavWindow != NULL) { - ImGui::BulletText("'%s':", g.NavWindow->Name); - ImGui::Indent(); + BulletText("'%s':", g.NavWindow->Name); + Indent(); for (int rect_n = 0; rect_n < WRT_Count; rect_n++) { ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n); - ImGui::Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]); + Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]); } - ImGui::Unindent(); + Unindent(); } - ImGui::Checkbox("Show mesh when hovering ImDrawCmd", &show_drawcmd_mesh); - ImGui::Checkbox("Show bounding boxes when hovering ImDrawCmd", &show_drawcmd_aabb); - ImGui::TreePop(); + Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh); + Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes); + TreePop(); } // Contents - Funcs::NodeWindows(g.Windows, "Windows"); - //Funcs::NodeWindows(g.WindowsFocusOrder, "WindowsFocusOrder"); - if (ImGui::TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) + DebugNodeWindowsList(&g.Windows, "Windows"); + //DebugNodeWindowList(&g.WindowsFocusOrder, "WindowsFocusOrder"); + if (TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) { for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++) - Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList"); - ImGui::TreePop(); + DebugNodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList"); + TreePop(); } // Details for Popups - if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) + if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) { for (int i = 0; i < g.OpenPopupStack.Size; i++) { ImGuiWindow* window = g.OpenPopupStack[i].Window; - ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); + BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); } - ImGui::TreePop(); + TreePop(); } // Details for TabBars - if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize())) + if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize())) { for (int n = 0; n < g.TabBars.GetSize(); n++) - Funcs::NodeTabBar(g.TabBars.GetByIndex(n)); - ImGui::TreePop(); + DebugNodeTabBar(g.TabBars.GetByIndex(n), "TabBar"); + TreePop(); } // Details for Tables IM_UNUSED(trt_rects_names); - IM_UNUSED(show_tables_rects); - IM_UNUSED(show_tables_rect_type); #ifdef IMGUI_HAS_TABLE - if (ImGui::TreeNode("Tables", "Tables (%d)", g.Tables.GetSize())) + if (TreeNode("Tables", "Tables (%d)", g.Tables.GetSize())) { for (int n = 0; n < g.Tables.GetSize(); n++) - Funcs::NodeTable(g.Tables.GetByIndex(n)); - ImGui::TreePop(); + DebugNodeTable(g.Tables.GetByIndex(n)); + TreePop(); } #endif // #ifdef IMGUI_HAS_TABLE // Details for Docking #ifdef IMGUI_HAS_DOCK - if (ImGui::TreeNode("Dock nodes")) + if (TreeNode("Docking")) { - ImGui::TreePop(); + TreePop(); } #endif // #ifdef IMGUI_HAS_DOCK // Settings - if (ImGui::TreeNode("Settings")) - { - if (ImGui::SmallButton("Clear")) - ImGui::ClearIniSettings(); - ImGui::SameLine(); - if (ImGui::SmallButton("Save to memory")) - ImGui::SaveIniSettingsToMemory(); - ImGui::SameLine(); - if (ImGui::SmallButton("Save to disk")) - ImGui::SaveIniSettingsToDisk(g.IO.IniFilename); - ImGui::SameLine(); + if (TreeNode("Settings")) + { + if (SmallButton("Clear")) + ClearIniSettings(); + SameLine(); + if (SmallButton("Save to memory")) + SaveIniSettingsToMemory(); + SameLine(); + if (SmallButton("Save to disk")) + SaveIniSettingsToDisk(g.IO.IniFilename); + SameLine(); if (g.IO.IniFilename) - ImGui::Text("\"%s\"", g.IO.IniFilename); + Text("\"%s\"", g.IO.IniFilename); else - ImGui::TextUnformatted(""); - ImGui::Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer); - if (ImGui::TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) + TextUnformatted(""); + Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer); + if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) { for (int n = 0; n < g.SettingsHandlers.Size; n++) - ImGui::BulletText("%s", g.SettingsHandlers[n].TypeName); - ImGui::TreePop(); + BulletText("%s", g.SettingsHandlers[n].TypeName); + TreePop(); } - if (ImGui::TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) + if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) { for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) - Funcs::NodeWindowSettings(settings); - ImGui::TreePop(); + DebugNodeWindowSettings(settings); + TreePop(); } #ifdef IMGUI_HAS_TABLE - if (ImGui::TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) + if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) { for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) - Funcs::NodeTableSettings(settings); - ImGui::TreePop(); + DebugNodeTableSettings(settings); + TreePop(); } #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK #endif // #ifdef IMGUI_HAS_DOCK - if (ImGui::TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) + if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { - ImGui::InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); - ImGui::TreePop(); + InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); + TreePop(); } - ImGui::TreePop(); + TreePop(); } // Misc Details - if (ImGui::TreeNode("Internal state")) + if (TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); - ImGui::Text("WINDOWING"); - ImGui::Indent(); - ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); - ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); - ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); - ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); - ImGui::Unindent(); - - ImGui::Text("ITEMS"); - ImGui::Indent(); - ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); - ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); - ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not - ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); - ImGui::Unindent(); - - ImGui::Text("NAV,FOCUS"); - ImGui::Indent(); - ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); - ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); - ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]); - ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); - ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); - ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); - ImGui::Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId); - ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); - ImGui::Unindent(); - - ImGui::TreePop(); + Text("WINDOWING"); + Indent(); + Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); + Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); + Unindent(); + + Text("ITEMS"); + Indent(); + Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); + Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); + Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); + Unindent(); + + Text("NAV,FOCUS"); + Indent(); + Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); + Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); + Text("NavInputSource: %s", input_source_names[g.NavInputSource]); + Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); + Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); + Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); + Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId); + Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); + Unindent(); + + TreePop(); } // Overlay: Display windows Rectangles and Begin Order - if (show_windows_rects || show_windows_begin_order) + if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder) { for (int n = 0; n < g.Windows.Size; n++) { @@ -10824,16 +10577,16 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (!window->WasActive) continue; ImDrawList* draw_list = GetForegroundDrawList(window); - if (show_windows_rects) + if (cfg->ShowWindowsRects) { - ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type); + ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } - if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow)) + if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow)) { char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); - float font_size = ImGui::GetFontSize(); + float font_size = GetFontSize(); draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf); } @@ -10861,9 +10614,273 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::End(); } +// [DEBUG] Display contents of Columns +void ImGui::DebugNodeColumns(ImGuiColumns* columns) +{ + if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) + return; + BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); + for (int column_n = 0; column_n < columns->Columns.Size; column_n++) + BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm)); + TreePop(); +} + +// [DEBUG] Display contents of ImDrawList +void ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label) +{ + ImGuiContext& g = *GImGui; + ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; + int cmd_count = draw_list->CmdBuffer.Size; + if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL) + cmd_count--; + bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count); + if (draw_list == GetWindowDrawList()) + { + SameLine(); + TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + if (node_open) + TreePop(); + return; + } + + ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list + if (window && IsItemHovered()) + fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!node_open) + return; + + if (window && !window->WasActive) + TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!"); + + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++) + { + if (pcmd->UserCallback) + { + BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + + char buf[300]; + ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId, + pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); + if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list) + DebugNodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes); + if (!pcmd_node_open) + continue; + + // Calculate approximate coverage area (touched pixel count) + // This will be in pixels squared as long there's no post-scaling happening to the renderer output. + const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset; + float total_area = 0.0f; + for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; ) + { + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_n++) + triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos; + total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]); + } + + // Display vertex information summary. Hover to get all triangles drawn in wire-frame + ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); + Selectable(buf); + if (IsItemHovered() && fg_draw_list) + DebugNodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, true, false); + + // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. + ImGuiListClipper clipper; + clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) + { + char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf); + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_i++) + { + const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i]; + triangle[n] = v.pos; + buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", + (n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + + Selectable(buf, false); + if (fg_draw_list && IsItemHovered()) + { + ImDrawListFlags backup_flags = fg_draw_list->Flags; + fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); + fg_draw_list->Flags = backup_flags; + } + } + TreePop(); + } + TreePop(); +} + +// [DEBUG] Display mesh/aabb of a ImDrawCmd +void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb) +{ + IM_ASSERT(show_mesh || show_aabb); + ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list + ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset; + + // Draw wire-frame version of all triangles + ImRect clip_rect = draw_cmd->ClipRect; + ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + ImDrawListFlags backup_flags = fg_draw_list->Flags; + fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. + for (unsigned int idx_n = draw_cmd->IdxOffset; idx_n < draw_cmd->IdxOffset + draw_cmd->ElemCount; ) + { + ImVec2 triangle[3]; + for (int n = 0; n < 3; n++, idx_n++) + vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos)); + if (show_mesh) + fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); // In yellow: mesh triangles + } + // Draw bounding boxes + if (show_aabb) + { + fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU + fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles + } + fg_draw_list->Flags = backup_flags; +} + +// [DEBUG] Display contents of ImGuiStorage +void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label) +{ + if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes())) + return; + for (int n = 0; n < storage->Data.Size; n++) + { + const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n]; + BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer. + } + TreePop(); +} + +// [DEBUG] Display contents of ImGuiTabBar +void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label) +{ + // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. + char buf[256]; + char* p = buf; + const char* buf_end = buf + IM_ARRAYSIZE(buf); + const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2); + p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); + IM_UNUSED(p); + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + bool open = TreeNode(tab_bar, "%s", buf); + if (!is_active) { PopStyleColor(); } + if (is_active && IsItemHovered()) + { + ImDrawList* draw_list = GetForegroundDrawList(); + draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); + } + if (open) + { + for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) + { + const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; + PushID(tab); + if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2); + if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine(); + Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", + tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "", tab->Offset, tab->Width, tab->ContentWidth); + PopID(); + } + TreePop(); + } +} + +void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) +{ + if (window == NULL) + { + BulletText("%s: NULL", label); + return; + } + + ImGuiContext& g = *GImGui; + const bool is_active = window->WasActive; + ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } + const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*"); + if (!is_active) { PopStyleColor(); } + if (IsItemHovered() && is_active) + GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); + if (!open) + return; + + if (window->MemoryCompacted) + TextDisabled("Note: some memory buffers have been compacted/freed."); + + ImGuiWindowFlags flags = window->Flags; + DebugNodeDrawList(window, window->DrawList, "DrawList"); + BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y); + BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, + (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", + (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", + (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); + BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : ""); + BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); + BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); + BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); + BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); + if (!window->NavRectRel[0].IsInverted()) + BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y); + else + BulletText("NavRectRel[0]: "); + if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); } + if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); } + if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); } + if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) + { + for (int n = 0; n < window->ColumnsStorage.Size; n++) + DebugNodeColumns(&window->ColumnsStorage[n]); + TreePop(); + } + DebugNodeStorage(&window->StateStorage, "Storage"); + TreePop(); +} + +void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings) +{ + Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d", + settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed); +} + + +void ImGui::DebugNodeWindowsList(ImVector* windows, const char* label) +{ + if (!TreeNode(label, "%s (%d)", label, windows->Size)) + return; + Text("(In front-to-back order:)"); + for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back + { + PushID((*windows)[i]); + DebugNodeWindow((*windows)[i], "Window"); + PopID(); + } + TreePop(); +} + #else -void ImGui::ShowMetricsWindow(bool*) { } +void ImGui::ShowMetricsWindow(bool*) {} +void ImGui::DebugNodeColumns(ImGuiColumns*) {} +void ImGui::DebugNodeDrawList(ImGuiWindow*, ImDrawList*, const char*) {} +void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} +void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} +void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} +void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {} +void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {} +void ImGui::DebugNodeWindowsList(ImVector*, const char*) {} #endif diff --git a/imgui_internal.h b/imgui_internal.h index 215f414e..11740019 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -101,6 +101,7 @@ struct ImGuiInputTextState; // Internal state of the currently focused/e struct ImGuiLastItemDataBackup; // Backup and restore IsItemHovered() internal data struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiNavMoveResult; // Result of a gamepad/keyboard directional navigation move query result +struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions struct ImGuiNextWindowData; // Storage for SetNextWindow** functions struct ImGuiNextItemData; // Storage for SetNextItem** functions struct ImGuiPopupData; // Storage for current popup stack @@ -1101,6 +1102,28 @@ struct ImGuiSettingsHandler ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } }; +struct ImGuiMetricsConfig +{ + bool ShowWindowsRects; + bool ShowWindowsBeginOrder; + bool ShowTablesRects; + bool ShowDrawCmdMesh; + bool ShowDrawCmdBoundingBoxes; + int ShowWindowsRectsType; + int ShowTablesRectsType; + + ImGuiMetricsConfig() + { + ShowWindowsRects = false; + ShowWindowsBeginOrder = false; + ShowTablesRects = false; + ShowDrawCmdMesh = true; + ShowDrawCmdBoundingBoxes = true; + ShowWindowsRectsType = -1; + ShowTablesRectsType = -1; + } +}; + //----------------------------------------------------------------------------- // [SECTION] Generic context hooks //----------------------------------------------------------------------------- @@ -1336,6 +1359,7 @@ struct ImGuiContext // Debug Tools bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker()) ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this id + ImGuiMetricsConfig DebugMetricsConfig; // Misc float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds. @@ -2070,6 +2094,15 @@ namespace ImGui inline void DebugDrawItemRect(ImU32 col = IM_COL32(255,0,0,255)) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; GetForegroundDrawList(window)->AddRect(window->DC.LastItemRect.Min, window->DC.LastItemRect.Max, col); } inline void DebugStartItemPicker() { ImGuiContext& g = *GImGui; g.DebugItemPickerActive = true; } + IMGUI_API void DebugNodeColumns(ImGuiColumns* columns); + IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label); + IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); + IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); + IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); + IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label); + IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings); + IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label); + } // namespace ImGui // ImFontAtlas internals From 3777fbbd81514695fb540e3b0c12330d1525b0bd Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Nov 2020 14:28:41 +0100 Subject: [PATCH 339/959] Renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 5 +++-- imgui.h | 4 ++-- imgui_demo.cpp | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 5118fece..cc8d2f52 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Breaking Changes: - If you were still using the old names, while you are cleaning up, considering enabling IMGUI_DISABLE_OBSOLETE_FUNCTIONS in imconfig.h even temporarily to have a pass at finding and removing up old API calls, if any remaining. +- Renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply + to other data structures. (#2636) Other Changes: diff --git a/imgui.cpp b/imgui.cpp index 0effb3b4..d347c531 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -371,6 +371,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend @@ -1037,7 +1038,7 @@ ImGuiIO::ImGuiIO() ConfigInputTextCursorBlink = true; ConfigWindowsResizeFromEdges = true; ConfigWindowsMoveFromTitleBarOnly = false; - ConfigWindowsMemoryCompactTimer = 60.0f; + ConfigMemoryCompactTimer = 60.0f; // Platform Functions BackendPlatformName = BackendRendererName = NULL; @@ -3894,7 +3895,7 @@ void ImGui::NewFrame() // Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); - const float memory_compact_start_time = (g.IO.ConfigWindowsMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigWindowsMemoryCompactTimer : FLT_MAX; + const float memory_compact_start_time = (g.IO.ConfigMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigMemoryCompactTimer : FLT_MAX; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; diff --git a/imgui.h b/imgui.h index a54e3f9e..a1b3e162 100644 --- a/imgui.h +++ b/imgui.h @@ -60,7 +60,7 @@ Index of this file: // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens) #define IMGUI_VERSION "1.80 WIP" -#define IMGUI_VERSION_NUM 17905 +#define IMGUI_VERSION_NUM 17906 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) @@ -1524,7 +1524,7 @@ struct ImGuiIO bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) bool ConfigWindowsMoveFromTitleBarOnly; // = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected. - float ConfigWindowsMemoryCompactTimer;// = 60.0f // [BETA] Compact window memory usage when unused. Set to -1.0f to disable. + float ConfigMemoryCompactTimer; // = 60.0f // [BETA] Free transient windows/tables memory buffers when unused for given amount of time. Set to -1.0f to disable. //------------------------------------------------------------------ // Platform Functions diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2ce3ddac..dd897236 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3686,7 +3686,7 @@ void ImGui::ShowAboutWindow(bool* p_open) if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink"); if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges"); if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly"); - if (io.ConfigWindowsMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigWindowsMemoryCompactTimer = %.1ff", io.ConfigWindowsMemoryCompactTimer); + if (io.ConfigMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigMemoryCompactTimer = %.1f", io.ConfigMemoryCompactTimer); ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags); if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad"); if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors"); From 9cca1b2e9795bcebb3054621788d5eb414080273 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Tue, 3 Nov 2020 14:32:44 +0100 Subject: [PATCH 340/959] Replace UTF-8 decoder with one based on branchless version by Christopher Wellons. (not branchless anymore tho) Decoding performance increase ~30% --- docs/CHANGELOG.txt | 3 ++ imgui.cpp | 106 +++++++++++++++++++++------------------------ 2 files changed, 52 insertions(+), 57 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index cc8d2f52..6d21f86a 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,6 +64,9 @@ Other Changes: - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. +- Misc: Replaced UTF-8 decoder by branchless one by Christopher Wellons (30~40% faster). [@rokups] + Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder + returns IM_UNICODE_CODEPOINT_INVALID and consume remaining bytes (vs old decoded consumed only 1 byte). - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] diff --git a/imgui.cpp b/imgui.cpp index d347c531..3aeb948c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1554,66 +1554,58 @@ void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_f //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bit character, process single character input. -// Based on stb_from_utf8() from github.com/nothings/stb/ +// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8). // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { - unsigned int c = (unsigned int)-1; - const unsigned char* str = (const unsigned char*)in_text; - if (!(*str & 0x80)) - { - c = (unsigned int)(*str++); - *out_char = c; - return 1; - } - if ((*str & 0xe0) == 0xc0) - { - *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string - if (in_text_end && in_text_end - (const char*)str < 2) return 1; - if (*str < 0xc2) return 2; - c = (unsigned int)((*str++ & 0x1f) << 6); - if ((*str & 0xc0) != 0x80) return 2; - c += (*str++ & 0x3f); - *out_char = c; - return 2; - } - if ((*str & 0xf0) == 0xe0) - { - *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string - if (in_text_end && in_text_end - (const char*)str < 3) return 1; - if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; - if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x0f) << 12); - if ((*str & 0xc0) != 0x80) return 3; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 3; - c += (*str++ & 0x3f); - *out_char = c; - return 3; - } - if ((*str & 0xf8) == 0xf0) - { - *out_char = IM_UNICODE_CODEPOINT_INVALID; // will be invalid but not end of string - if (in_text_end && in_text_end - (const char*)str < 4) return 1; - if (*str > 0xf4) return 4; - if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; - if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x07) << 18); - if ((*str & 0xc0) != 0x80) return 4; - c += (unsigned int)((*str++ & 0x3f) << 12); - if ((*str & 0xc0) != 0x80) return 4; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 4; - c += (*str++ & 0x3f); - // utf-8 encodings of values used in surrogate pairs are invalid - if ((c & 0xFFFFF800) == 0xD800) return 4; - // If codepoint does not fit in ImWchar, use replacement character U+FFFD instead - if (c > IM_UNICODE_CODEPOINT_MAX) c = IM_UNICODE_CODEPOINT_INVALID; - *out_char = c; - return 4; - } - *out_char = 0; - return 0; + static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 }; + static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 }; + static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 }; + static const int shiftc[] = { 0, 18, 12, 6, 0 }; + static const int shifte[] = { 0, 6, 4, 2, 0 }; + int len = lengths[*(const unsigned char*)in_text >> 3]; + int wanted = len + !len; + + if (in_text_end == NULL) + in_text_end = in_text + wanted; // Max length, nulls will be taken into account. + + // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here, + // so it is fast even with excessive branching. + unsigned char s[4]; + s[0] = in_text + 0 < in_text_end ? in_text[0] : 0; + s[1] = in_text + 1 < in_text_end ? in_text[1] : 0; + s[2] = in_text + 2 < in_text_end ? in_text[2] : 0; + s[3] = in_text + 3 < in_text_end ? in_text[3] : 0; + + // Assume a four-byte character and load four bytes. Unused bits are shifted out. + *out_char = (uint32_t)(s[0] & masks[len]) << 18; + *out_char |= (uint32_t)(s[1] & 0x3f) << 12; + *out_char |= (uint32_t)(s[2] & 0x3f) << 6; + *out_char |= (uint32_t)(s[3] & 0x3f) << 0; + *out_char >>= shiftc[len]; + + // Accumulate the various error conditions. + int e = 0; + e = (*out_char < mins[len]) << 6; // non-canonical encoding + e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half? + e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range? + e |= (s[1] & 0xc0) >> 2; + e |= (s[2] & 0xc0) >> 4; + e |= (s[3] ) >> 6; + e ^= 0x2a; // top two bits of each tail byte correct? + e >>= shifte[len]; + + if (e) + { + // No bytes are consumed when *in_text == 0 || in_text == in_text_end. + // One byte is consumed in case of invalid first byte of in_text. + // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. + // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s. + wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]); + *out_char = IM_UNICODE_CODEPOINT_INVALID; + } + + return wanted; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) From b934b9bb8695c745c0e0b1b19994f4f5eb6a4da9 Mon Sep 17 00:00:00 2001 From: Albin Odervall Date: Fri, 23 Oct 2020 18:57:35 +0200 Subject: [PATCH 341/959] Backends: OSX, Metal: Fix -Wshadow, -Wimplicit-float-conversion, and -Wsign-conversion warnings. (#3555) --- backends/imgui_impl_metal.mm | 22 +++++++++++----------- backends/imgui_impl_osx.mm | 19 +++++++++---------- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 3b0d34c6..8a6f7e7d 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -234,8 +234,8 @@ void ImGui_ImplMetal_DestroyDeviceObjects() int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm - width:width - height:height + width:(NSUInteger)width + height:(NSUInteger)height mipmapped:NO]; textureDescriptor.usage = MTLTextureUsageShaderRead; #if TARGET_OS_OSX @@ -244,7 +244,7 @@ void ImGui_ImplMetal_DestroyDeviceObjects() textureDescriptor.storageMode = MTLStorageModeShared; #endif id texture = [device newTextureWithDescriptor:textureDescriptor]; - [texture replaceRegion:MTLRegionMake2D(0, 0, width, height) mipmapLevel:0 withBytes:pixels bytesPerRow:width * 4]; + [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4]; self.fontTexture = texture; } @@ -435,8 +435,8 @@ void ImGui_ImplMetal_DestroyDeviceObjects() float R = drawData->DisplayPos.x + drawData->DisplaySize.x; float T = drawData->DisplayPos.y; float B = drawData->DisplayPos.y + drawData->DisplaySize.y; - float N = viewport.znear; - float F = viewport.zfar; + float N = (float)viewport.znear; + float F = (float)viewport.zfar; const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, @@ -464,8 +464,8 @@ void ImGui_ImplMetal_DestroyDeviceObjects() id renderPipelineState = [self renderPipelineStateForFrameAndDevice:commandBuffer.device]; - size_t vertexBufferLength = drawData->TotalVtxCount * sizeof(ImDrawVert); - size_t indexBufferLength = drawData->TotalIdxCount * sizeof(ImDrawIdx); + size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert); + size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx); MetalBuffer* vertexBuffer = [self dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; MetalBuffer* indexBuffer = [self dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; @@ -482,8 +482,8 @@ void ImGui_ImplMetal_DestroyDeviceObjects() { const ImDrawList* cmd_list = drawData->CmdLists[n]; - memcpy((char *)vertexBuffer.buffer.contents + vertexBufferOffset, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); - memcpy((char *)indexBuffer.buffer.contents + indexBufferOffset, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + memcpy((char *)vertexBuffer.buffer.contents + vertexBufferOffset, cmd_list->VtxBuffer.Data, (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); + memcpy((char *)indexBuffer.buffer.contents + indexBufferOffset, cmd_list->IdxBuffer.Data, (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { @@ -533,8 +533,8 @@ void ImGui_ImplMetal_DestroyDeviceObjects() } } - vertexBufferOffset += cmd_list->VtxBuffer.Size * sizeof(ImDrawVert); - indexBufferOffset += cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx); + vertexBufferOffset += (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert); + indexBufferOffset += (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx); } __weak id weakSelf = self; diff --git a/backends/imgui_impl_osx.mm b/backends/imgui_impl_osx.mm index fc347a40..4c137f6c 100644 --- a/backends/imgui_impl_osx.mm +++ b/backends/imgui_impl_osx.mm @@ -171,7 +171,7 @@ void ImGui_ImplOSX_NewFrame(NSView* view) ImGuiIO& io = ImGui::GetIO(); if (view) { - const float dpi = [view.window backingScaleFactor]; + const float dpi = (float)[view.window backingScaleFactor]; io.DisplaySize = ImVec2((float)view.bounds.size.width, (float)view.bounds.size.height); io.DisplayFramebufferScale = ImVec2(dpi, dpi); } @@ -180,7 +180,7 @@ void ImGui_ImplOSX_NewFrame(NSView* view) if (g_Time == 0.0) g_Time = CFAbsoluteTimeGetCurrent(); CFAbsoluteTime current_time = CFAbsoluteTimeGetCurrent(); - io.DeltaTime = current_time - g_Time; + io.DeltaTime = (float)(current_time - g_Time); g_Time = current_time; ImGui_ImplOSX_UpdateMouseCursorAndButtons(); @@ -231,7 +231,7 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) NSPoint mousePoint = event.locationInWindow; mousePoint = [view convertPoint:mousePoint fromView:nil]; mousePoint = NSMakePoint(mousePoint.x, view.bounds.size.height - mousePoint.y); - io.MousePos = ImVec2(mousePoint.x, mousePoint.y); + io.MousePos = ImVec2((float)mousePoint.x, (float)mousePoint.y); } if (event.type == NSEventTypeScrollWheel) @@ -258,9 +258,9 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) } if (fabs(wheel_dx) > 0.0) - io.MouseWheelH += wheel_dx * 0.1f; + io.MouseWheelH += (float)wheel_dx * 0.1f; if (fabs(wheel_dy) > 0.0) - io.MouseWheel += wheel_dy * 0.1f; + io.MouseWheel += (float)wheel_dy * 0.1f; return io.WantCaptureMouse; } @@ -268,8 +268,8 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) if (event.type == NSEventTypeKeyDown) { NSString* str = [event characters]; - int len = (int)[str length]; - for (int i = 0; i < len; i++) + NSUInteger len = [str length]; + for (NSUInteger i = 0; i < len; i++) { int c = [str characterAtIndex:i]; if (!io.KeyCtrl && !(c >= 0xF700 && c <= 0xFFFF) && c != 127) @@ -288,8 +288,8 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) if (event.type == NSEventTypeKeyUp) { NSString* str = [event characters]; - int len = (int)[str length]; - for (int i = 0; i < len; i++) + NSUInteger len = [str length]; + for (NSUInteger i = 0; i < len; i++) { int c = [str characterAtIndex:i]; int key = mapCharacterToKey(c); @@ -301,7 +301,6 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) if (event.type == NSEventTypeFlagsChanged) { - ImGuiIO& io = ImGui::GetIO(); unsigned int flags = [event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask; bool oldKeyCtrl = io.KeyCtrl; From 2fa00656a40fca5c1d5b3c19c51f13632d41c35e Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 3 Nov 2020 15:46:29 +0100 Subject: [PATCH 342/959] Fix for IMGUI_DISABLE_METRICS_WINDOW --- imgui.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui.cpp b/imgui.cpp index 3aeb948c..7f2bd0ae 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10867,7 +10867,7 @@ void ImGui::DebugNodeWindowsList(ImVector* windows, const char* la void ImGui::ShowMetricsWindow(bool*) {} void ImGui::DebugNodeColumns(ImGuiColumns*) {} -void ImGui::DebugNodeDrawList(ImGuiWindow*, ImDrawList*, const char*) {} +void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {} void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} From d6a2f7e95e98b93973a23005bc0b31d5c7953ee5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Nov 2020 13:49:16 +0100 Subject: [PATCH 343/959] Reduced padding + unused storage in ImDrawList (224->192 bytes) + zero-init ImDrawListSplitter and ImDrawList + Readme tweak --- docs/README.md | 2 +- imgui.h | 18 +++++++++++++----- imgui_internal.h | 2 +- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/README.md b/docs/README.md index 35b08f9c..30151a91 100644 --- a/docs/README.md +++ b/docs/README.md @@ -196,7 +196,7 @@ Ongoing Dear ImGui development is financially supported by users and private spo - [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui/) *Double-chocolate and Salty caramel sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [RAD Game Tools](http://www.radgametools.com/), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) +- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Arkane Studios](https://www.arkane-studios.com), [Dotemu](http://www.dotemu.com), [Framefield](http://framefield.com), [Grinding Gear Games](https://www.grindinggear.com), [Hexagon](https://hexagonxalt.com/the-technology/xalt-visualization), [Kylotonn](https://www.kylotonn.com), [Media Molecule](http://www.mediamolecule.com), [Mesh Consultants](https://www.meshconsultants.ca), [Mobigame](http://www.mobigame.net), [Nadeo](https://www.nadeo.com), [Next Level Games](https://www.nextlevelgames.com), [RAD Game Tools](http://www.radgametools.com/), [Supercell](http://www.supercell.com), [Remedy Entertainment](https://www.remedygames.com/), [Unit 2 Games](https://unit2games.com/) From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors). diff --git a/imgui.h b/imgui.h index a1b3e162..bbedcfc8 100644 --- a/imgui.h +++ b/imgui.h @@ -2006,7 +2006,15 @@ struct ImDrawVert IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif -// For use by ImDrawListSplitter. +// [Internal] For use by ImDrawList +struct ImDrawCmdHeader +{ + ImVec4 ClipRect; + ImTextureID TextureId; + unsigned int VtxOffset; +}; + +// [Internal] For use by ImDrawListSplitter struct ImDrawChannel { ImVector _CmdBuffer; @@ -2021,7 +2029,7 @@ struct ImDrawListSplitter int _Count; // Number of active channels (1+) ImVector _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) - inline ImDrawListSplitter() { Clear(); } + inline ImDrawListSplitter() { memset(this, 0, sizeof(*this)); } inline ~ImDrawListSplitter() { ClearFreeMemory(); } inline void Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame IMGUI_API void ClearFreeMemory(); @@ -2072,19 +2080,19 @@ struct ImDrawList ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. // [Internal, used while building lists] + unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) const char* _OwnerName; // Pointer to owner window's name for debugging - unsigned int _VtxCurrentIdx; // [Internal] Generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. 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) ImVector _ClipRectStack; // [Internal] ImVector _TextureIdStack; // [Internal] ImVector _Path; // [Internal] current path building - ImDrawCmd _CmdHeader; // [Internal] Template of active commands. Fields should match those of CmdBuffer.back(). + 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!) // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) - ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; Flags = ImDrawListFlags_None; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _OwnerName = NULL; } + ImDrawList(const ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; } ~ImDrawList() { _ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, 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) diff --git a/imgui_internal.h b/imgui_internal.h index 11740019..7fa13392 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1692,9 +1692,9 @@ struct IMGUI_API ImGuiWindow ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space - bool MemoryCompacted; // Set when window extraneous data have been garbage collected int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy int MemoryDrawListVtxCapacity; + bool MemoryCompacted; // Set when window extraneous data have been garbage collected public: ImGuiWindow(ImGuiContext* context, const char* name); From 2bf5ca7ef2f01a30758bb2a7060d902c22b33e9e Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Nov 2020 17:50:30 +0100 Subject: [PATCH 344/959] ImDrawListClipper: avoid over reserving memory. --- imgui_draw.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8ce1739f..3dd0a360 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1429,7 +1429,10 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) IM_ASSERT(_Current == 0 && _Count <= 1 && "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter."); int old_channels_count = _Channels.Size; if (old_channels_count < channels_count) + { + _Channels.reserve(channels_count); // Avoid over reserving since this is likely to stay stable _Channels.resize(channels_count); + } _Count = channels_count; // Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer From 7a27b2a28232b8b0f1738fdbad6cc28efe09a2e4 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Nov 2020 20:11:05 +0100 Subject: [PATCH 345/959] Update Readme, links to Useful Widgets, updated a gif. --- docs/README.md | 9 +++++++-- docs/TODO.txt | 3 ++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/README.md b/docs/README.md index 30151a91..a5555883 100644 --- a/docs/README.md +++ b/docs/README.md @@ -81,7 +81,7 @@ ImGui::EndChild(); ImGui::End(); ``` Result: -
![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_03_color.gif) +
![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v180/code_sample_04_color.gif) Dear ImGui allows you to **create elaborate tools** as well as very short-lived ones. On the extreme side of short-livedness: using the Edit&Continue (hot code reload) feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! Dear ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, an entire game making editor/framework, etc. @@ -119,11 +119,14 @@ Officially maintained backends/bindings (in repository): - Platforms: GLFW, SDL2, Win32, Glut, OSX. - Frameworks: Emscripten, Allegro5, Marmalade. -Third-party backends/bindings (see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings/) page): +[Third-party backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) wiki page: - Languages: C, C# and: Beef, ChaiScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... - Frameworks: AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, nCine, Nim Game Lib, Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SFML, Sokol, Unity, Unreal Engine 4, vtk, Win32 GDI, WxWidgets. - Note that C bindings ([cimgui](https://github.com/cimgui/cimgui)) are auto-generated, you can use its json/lua output to generate bindings for other languages. +[Useful widgets and extensions](https://github.com/ocornut/imgui/wiki/Useful-Widgets) wiki page: +- Text editors, node editors, timeline editors, plotting, software renderers, remote network access, memory editors, gizmos etc. + Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. ### Upcoming Changes @@ -140,6 +143,8 @@ Some of the goals for 2020 are: For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/3488)! +For a list of third-party widgets and extensions, check out the [Useful Widgets](https://github.com/ocornut/imgui/wiki/Useful-Widgets) wiki page. + Custom engine [![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) diff --git a/docs/TODO.txt b/docs/TODO.txt index 8473d720..fa299c96 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -167,7 +167,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - dock: dock out from a collapsing header? would work nicely but need emitting window to keep submitting the code. - tabs: "there is currently a problem because TabItem() will try to submit their own tooltip after 0.50 second, and this will have the effect of making your tooltip flicker once." -> tooltip priority work - - tabs: close button tends to overlap unsaved-document star + - tabs: close button tends to overlap unsaved-document star - tabs: consider showing the star at the same spot as the close button, like VS Code does. - tabs: make EndTabBar fail if users doesn't respect BeginTabBar return value, for consistency/future-proofing. - tabs: persistent order/focus in BeginTabBar() api (#261, #351) @@ -271,6 +271,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb) - drag and drop: fix/support/options for overlapping drag sources. + - drag and drop: focus drag target window on hold (even without open) - drag and drop: releasing a drop shows the "..." tooltip for one frame - since e13e598 (#1725) - drag and drop: drag source on a group object (would need e.g. an invisible button covering group in EndGroup) https://twitter.com/paniq/status/1121446364909535233 - drag and drop: have some way to know when a drag begin from BeginDragDropSource() pov. (see 2018/01/11 post in #143) From 046057cebbd7d22fb97c062f8c6907b0174aa7d5 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 4 Nov 2020 20:11:34 +0100 Subject: [PATCH 346/959] Selectable: Avoid pushing span-column background if clipped. --- imgui_widgets.cpp | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 9b440878..ca5c3b9a 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5909,10 +5909,6 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0; - if (span_all_columns && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped. - PushColumnsBackground(); - // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -5923,6 +5919,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // Fill horizontal space // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitely right-aligned sizes not visibly match other widgets. + const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0; const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x; const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x; if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth)) @@ -5947,6 +5944,15 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl } //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); } + // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackground for every Selectable.. + const float backup_clip_rect_min_x = window->ClipRect.Min.x; + const float backup_clip_rect_max_x = window->ClipRect.Max.x; + if (span_all_columns) + { + window->ClipRect.Min.x = window->ParentWorkRect.Min.x; + window->ClipRect.Max.x = window->ParentWorkRect.Max.x; + } + bool item_add; if (flags & ImGuiSelectableFlags_Disabled) { @@ -5959,13 +5965,21 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl { item_add = ItemAdd(bb, id); } - if (!item_add) + + if (span_all_columns) { - if (span_all_columns && window->DC.CurrentColumns) - PopColumnsBackground(); - return false; + window->ClipRect.Min.x = backup_clip_rect_min_x; + window->ClipRect.Max.x = backup_clip_rect_max_x; } + if (!item_add) + return false; + + // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only, + // which would be advantageous since most selectable are not selected. + if (span_all_columns && window->DC.CurrentColumns) + PushColumnsBackground(); + // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries ImGuiButtonFlags button_flags = 0; if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; } From 5f97809cab996ed2b76ccc9097d2e84bd71985e6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Nov 2020 13:15:02 +0100 Subject: [PATCH 347/959] Misc tidying up (zero-clear structures, more unused default in ClipRetFullscreen, NavApplyItemToResult() coding style fix) Zero-clearing more structures Remove arbitrary default ClipRetFullscreen value in ImDrawListSharedData. Nav extracted NavApplyItemToResult() function. Coding style fixes in OSX Backends. --- examples/example_apple_metal/main.mm | 69 ++++++++++++++++---------- examples/example_apple_opengl2/main.mm | 2 +- imgui.cpp | 24 ++++----- imgui_draw.cpp | 11 +--- imgui_internal.h | 24 ++------- imgui_widgets.cpp | 7 --- 6 files changed, 62 insertions(+), 75 deletions(-) diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index ec6482ee..541dc5e1 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -1,3 +1,6 @@ +// Dear ImGui: standalone example application for OSX + Metal. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #import @@ -31,13 +34,15 @@ @implementation ViewController -- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil { +- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil +{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; _device = MTLCreateSystemDefaultDevice(); _commandQueue = [_device newCommandQueue]; - if (!self.device) { + if (!self.device) + { NSLog(@"Metal is not supported"); abort(); } @@ -75,11 +80,13 @@ return self; } -- (MTKView *)mtkView { +- (MTKView *)mtkView +{ return (MTKView *)self.view; } -- (void)loadView { +- (void)loadView +{ self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)]; } @@ -104,14 +111,13 @@ // window, we'd want to be much more careful than just ingesting the complete event stream, though we // do make an effort to be good citizens by passing along events when Dear ImGui doesn't want to capture. NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged | NSEventTypeScrollWheel; - [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) { + [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) + { BOOL wantsCapture = ImGui_ImplOSX_HandleEvent(event, self.view); - if (event.type == NSEventTypeKeyDown && wantsCapture) { + if (event.type == NSEventTypeKeyDown && wantsCapture) return nil; - } else { + else return event; - } - }]; ImGui_ImplOSX_Init(); @@ -174,15 +180,18 @@ // multitouch correctly at all. This causes the "cursor" to behave very erratically // when there are multiple active touches. But for demo purposes, single-touch // interaction actually works surprisingly well. -- (void)updateIOWithTouchEvent:(UIEvent *)event { +- (void)updateIOWithTouchEvent:(UIEvent *)event +{ UITouch *anyTouch = event.allTouches.anyObject; CGPoint touchLocation = [anyTouch locationInView:self.view]; ImGuiIO &io = ImGui::GetIO(); io.MousePos = ImVec2(touchLocation.x, touchLocation.y); BOOL hasActiveTouch = NO; - for (UITouch *touch in event.allTouches) { - if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled) { + for (UITouch *touch in event.allTouches) + { + if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled) + { hasActiveTouch = YES; break; } @@ -190,19 +199,23 @@ io.MouseDown[0] = hasActiveTouch; } -- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +{ [self updateIOWithTouchEvent:event]; } -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event +{ [self updateIOWithTouchEvent:event]; } -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event +{ [self updateIOWithTouchEvent:event]; } -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +{ [self updateIOWithTouchEvent:event]; } @@ -212,7 +225,7 @@ - (void)drawInMTKView:(MTKView*)view { - ImGuiIO &io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = view.bounds.size.width; io.DisplaySize.y = view.bounds.size.height; @@ -288,8 +301,8 @@ // Rendering ImGui::Render(); - ImDrawData* drawData = ImGui::GetDrawData(); - ImGui_ImplMetal_RenderDrawData(drawData, commandBuffer, renderEncoder); + ImDrawData* draw_data = ImGui::GetDrawData(); + ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder); [renderEncoder popDebugGroup]; [renderEncoder endEncoding]; @@ -316,8 +329,10 @@ @implementation AppDelegate -- (instancetype)init { - if (self = [super init]) { +- (instancetype)init +{ + if (self = [super init]) + { NSViewController *rootViewController = [[ViewController alloc] initWithNibName:nil bundle:nil]; self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable @@ -331,7 +346,8 @@ return self; } -- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { +- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender +{ return YES; } @@ -363,14 +379,17 @@ #if TARGET_OS_OSX -int main(int argc, const char * argv[]) { +int main(int argc, const char * argv[]) +{ return NSApplicationMain(argc, argv); } #else -int main(int argc, char * argv[]) { - @autoreleasepool { +int main(int argc, char * argv[]) +{ + @autoreleasepool + { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index c3f43bdb..5bcc9ea4 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -139,7 +139,7 @@ animationTimer = nil; } -// Forward Mouse/Keyboard events to dear imgui OSX backend. It returns true when imgui is expecting to use the event. +// Forward Mouse/Keyboard events to Dear ImGui OSX backend. -(void)keyUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } -(void)keyDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } -(void)flagsChanged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } diff --git a/imgui.cpp b/imgui.cpp index 7f2bd0ae..427806d8 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -862,6 +862,7 @@ static float NavUpdatePageUpPageDown(); static inline void NavUpdateAnyRequestFlag(); static void NavEndFrame(); static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand); +static void NavApplyItemToResult(ImGuiNavMoveResult* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel); static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id); static ImVec2 NavCalcPreferredRefPos(); static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); @@ -8377,6 +8378,14 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) return new_best; } +static void ImGui::NavApplyItemToResult(ImGuiNavMoveResult* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel) +{ + result->Window = window; + result->ID = id; + result->FocusScopeId = window->DC.NavFocusScopeIdCurrent; + result->RectRel = nav_bb_rel; +} + // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id) { @@ -8417,25 +8426,14 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); #endif if (new_best) - { - result->Window = window; - result->ID = id; - result->FocusScopeId = window->DC.NavFocusScopeIdCurrent; - result->RectRel = nav_bb_rel; - } + NavApplyItemToResult(result, window, id, nav_bb_rel); // Features like PageUp/PageDown need to maintain a separate score for the visible set of items. const float VISIBLE_RATIO = 0.70f; if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb)) if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb)) - { - result = &g.NavMoveResultLocalVisibleSet; - result->Window = window; - result->ID = id; - result->FocusScopeId = window->DC.NavFocusScopeIdCurrent; - result->RectRel = nav_bb_rel; - } + NavApplyItemToResult(&g.NavMoveResultLocalVisibleSet, window, id, nav_bb_rel); } // Update window-relative bounding box of navigated item diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 3dd0a360..8a102220 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -344,21 +344,12 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) ImDrawListSharedData::ImDrawListSharedData() { - Font = NULL; - FontSize = 0.0f; - CurveTessellationTol = 0.0f; - CircleSegmentMaxError = 0.0f; - ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f); - InitialFlags = ImDrawListFlags_None; - - // Lookup tables + memset(this, 0, sizeof(*this)); for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++) { const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx); ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a)); } - memset(CircleSegmentCounts, 0, sizeof(CircleSegmentCounts)); // This will be set by SetCircleSegmentMaxError() - TexUvLines = NULL; } void ImDrawListSharedData::SetCircleSegmentMaxError(float max_error) diff --git a/imgui_internal.h b/imgui_internal.h index 7fa13392..ff8dbe6f 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -844,7 +844,7 @@ struct IMGUI_API ImGuiMenuColumns float Width, NextWidth; float Pos[3], NextWidths[3]; - ImGuiMenuColumns(); + ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); } void Update(int count, float spacing, bool clear); float DeclColumns(float w0, float w1, float w2); float CalcExtraSpace(float avail_w) const; @@ -897,7 +897,7 @@ struct ImGuiPopupData ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup - ImGuiPopupData() { PopupId = 0; Window = SourceWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; } + ImGuiPopupData() { memset(this, 0, sizeof(*this)); OpenFrameCount = -1; } }; struct ImGuiNavMoveResult @@ -1006,7 +1006,7 @@ struct ImGuiColumnData ImGuiColumnsFlags Flags; // Not exposed ImRect ClipRect; - ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; } + ImGuiColumnData() { memset(this, 0, sizeof(*this)); } }; struct ImGuiColumns @@ -1027,21 +1027,7 @@ struct ImGuiColumns ImVector Columns; ImDrawListSplitter Splitter; - ImGuiColumns() { Clear(); } - void Clear() - { - ID = 0; - Flags = ImGuiColumnsFlags_None; - IsFirstFrame = false; - IsBeingResized = false; - Current = 0; - Count = 1; - OffMinX = OffMaxX = 0.0f; - LineMinY = LineMaxY = 0.0f; - HostCursorPosY = 0.0f; - HostCursorMaxPosX = 0.0f; - Columns.clear(); - } + ImGuiColumns() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- @@ -1083,7 +1069,7 @@ struct ImGuiWindowSettings bool Collapsed; bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) - ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = WantApply = false; } + ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); } char* GetName() { return (char*)(this + 1); } }; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index ca5c3b9a..eed4a048 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -6388,13 +6388,6 @@ void ImGui::Value(const char* prefix, float v, const char* float_format) //------------------------------------------------------------------------- // Helpers for internal use -ImGuiMenuColumns::ImGuiMenuColumns() -{ - Spacing = Width = NextWidth = 0.0f; - memset(Pos, 0, sizeof(Pos)); - memset(NextWidths, 0, sizeof(NextWidths)); -} - void ImGuiMenuColumns::Update(int count, float spacing, bool clear) { IM_ASSERT(count == IM_ARRAYSIZE(Pos)); From 5789e69a6259f4cf91ed9a523604b911c4e41191 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Nov 2020 21:23:02 +0100 Subject: [PATCH 348/959] Checkbox: Added CheckboxFlags() helper with int* type. Demo: removed extraneous casts. --- docs/CHANGELOG.txt | 1 + imgui.h | 1 + imgui_demo.cpp | 67 +++++++++++++++++++++++----------------------- imgui_internal.h | 1 + imgui_widgets.cpp | 34 +++++++++++++++-------- 5 files changed, 59 insertions(+), 45 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 6d21f86a..7b8254ac 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -63,6 +63,7 @@ Other Changes: or CollapsingHeader() while dragging. (#1738) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] +- Checkbox: Added CheckboxFlags() helper with int* type. - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. - Misc: Replaced UTF-8 decoder by branchless one by Christopher Wellons (30~40% faster). [@rokups] Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder diff --git a/imgui.h b/imgui.h index bbedcfc8..f3dcac71 100644 --- a/imgui.h +++ b/imgui.h @@ -444,6 +444,7 @@ namespace ImGui IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); 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)); // <0 frame_padding uses default frame padding settings. 0 for no padding IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer diff --git a/imgui_demo.cpp b/imgui_demo.cpp index dd897236..07cd3a23 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -379,16 +379,15 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Configuration##2")) { - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); ImGui::SameLine(); HelpMarker("Required backend to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); - ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); + ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", &io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); - ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouse); - - // The "NoMouse" option above can get us stuck with a disable mouse! Provide an alternative way to fix it: + ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, ImGuiConfigFlags_NoMouse); if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) { + // The "NoMouse" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it: if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f) { ImGui::SameLine(); @@ -397,7 +396,7 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Space))) io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse; } - ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); + ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange); ImGui::SameLine(); HelpMarker("Instruct backend to not alter mouse cursor shape and visibility."); ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink); ImGui::SameLine(); HelpMarker("Set to false to disable blinking cursor, for users who consider it distracting"); @@ -419,10 +418,10 @@ void ImGui::ShowDemoWindow(bool* p_open) // Make a local copy to avoid modifying actual backend flags. ImGuiBackendFlags backend_flags = io.BackendFlags; - ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasGamepad); - ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasMouseCursors); - ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasSetMousePos); - ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int*)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); + ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", &backend_flags, ImGuiBackendFlags_HasGamepad); + ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &backend_flags, ImGuiBackendFlags_HasMouseCursors); + ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &backend_flags, ImGuiBackendFlags_HasSetMousePos); + ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &backend_flags, ImGuiBackendFlags_RendererHasVtxOffset); ImGui::TreePop(); ImGui::Separator(); } @@ -710,10 +709,10 @@ static void ShowDemoWindowWidgets() static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth; static bool align_label_with_current_x_position = false; static bool test_drag_and_drop = false; - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", &base_flags, ImGuiTreeNodeFlags_OpenOnArrow); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node."); + ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth); 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!"); @@ -970,11 +969,11 @@ static void ShowDemoWindowWidgets() { // Expose flags as checkbox for the demo static ImGuiComboFlags flags = 0; - ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", (unsigned int*)&flags, ImGuiComboFlags_PopupAlignLeft); + ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", &flags, ImGuiComboFlags_PopupAlignLeft); ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo"); - if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", (unsigned int*)&flags, ImGuiComboFlags_NoArrowButton)) + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", &flags, ImGuiComboFlags_NoArrowButton)) flags &= ~ImGuiComboFlags_NoPreview; // Clear the other flag, as we cannot combine both - if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", (unsigned int*)&flags, ImGuiComboFlags_NoPreview)) + if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", &flags, ImGuiComboFlags_NoPreview)) flags &= ~ImGuiComboFlags_NoArrowButton; // Clear the other flag, as we cannot combine both // Using the generic BeginCombo() API, you have full control over how to display the combo contents. @@ -1165,9 +1164,9 @@ static void ShowDemoWindowWidgets() static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)"); - ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly); - ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput); - ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine); + ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); + ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); + ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); ImGui::TreePop(); } @@ -1565,13 +1564,13 @@ static void ShowDemoWindowWidgets() { // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! static ImGuiSliderFlags flags = ImGuiSliderFlags_None; - ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", (unsigned int*)&flags, ImGuiSliderFlags_AlwaysClamp); + ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp); ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click."); - ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&flags, ImGuiSliderFlags_Logarithmic); + ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic); ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&flags, ImGuiSliderFlags_NoRoundToFormat); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat); ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits)."); - ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&flags, ImGuiSliderFlags_NoInput); + ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput); ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget."); // Drags @@ -2324,15 +2323,15 @@ static void ShowDemoWindowLayout() { // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable; - ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_Reorderable); - ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); - ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); - ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs); + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton); if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_; - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); // Tab Bar @@ -2380,10 +2379,10 @@ static void ShowDemoWindowLayout() // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown; - ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) + ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton); + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown)) tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown); - if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) + if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll)) tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll); if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) diff --git a/imgui_internal.h b/imgui_internal.h index ff8dbe6f..6b701a0b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2044,6 +2044,7 @@ namespace ImGui template IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags); template IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); template IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); + template IMGUI_API bool CheckboxFlagsT(const char* label, T* flags, T flags_value); // Data type helpers IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index eed4a048..2c5e1814 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -408,6 +408,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) // - Image() // - ImageButton() // - Checkbox() +// - CheckboxFlagsT() [Internal] // - CheckboxFlags() // - RadioButton() // - ProgressBar() @@ -1075,6 +1076,7 @@ bool ImGui::Checkbox(const char* label, bool* v) if (mixed_value) { // Undocumented tristate/mixed/indeterminate checkbox (#2644) + // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox) ImVec2 pad(ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)), ImMax(1.0f, IM_FLOOR(square_sz / 3.6f))); window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); } @@ -1093,35 +1095,45 @@ bool ImGui::Checkbox(const char* label, bool* v) return pressed; } -bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +template +bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value) { - bool v = ((*flags & flags_value) == flags_value); + bool all_on = (*flags & flags_value) == flags_value; + bool any_on = (*flags & flags_value) != 0; bool pressed; - if (v == false && (*flags & flags_value) != 0) + if (!all_on && any_on) { - // Mixed value (FIXME: find a way to expose neatly to Checkbox?) ImGuiWindow* window = GetCurrentWindow(); - const ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; + ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_MixedValue; - pressed = Checkbox(label, &v); + pressed = Checkbox(label, &all_on); window->DC.ItemFlags = backup_item_flags; } else { - // Regular checkbox - pressed = Checkbox(label, &v); + pressed = Checkbox(label, &all_on); + } if (pressed) { - if (v) + if (all_on) *flags |= flags_value; else *flags &= ~flags_value; } - return pressed; } +bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + +bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +{ + return CheckboxFlagsT(label, flags, flags_value); +} + bool ImGui::RadioButton(const char* label, bool active) { ImGuiWindow* window = GetCurrentWindow(); @@ -5434,7 +5446,7 @@ void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags fl if (allow_opt_alpha_bar) { if (allow_opt_picker) Separator(); - CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar); + CheckboxFlags("Alpha Bar", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar); } EndPopup(); } From 2785ac0ee342d5cbcab0d546d773e7492a1e3cfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A1=BE=E8=B5=B7=E5=A8=81?= Date: Wed, 11 Nov 2020 11:35:47 +0100 Subject: [PATCH 349/959] InputText: Fixed updating cursor/selection position when a callback alters the buffer in a way where the byte count is unchanged but the decoded character count changes. (#3587) --- docs/CHANGELOG.txt | 4 +++- imgui_widgets.cpp | 9 +++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7b8254ac..8dc2aa48 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -64,9 +64,11 @@ Other Changes: - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging into a full-window-sized dockspace inside a zero-padded window. (#3519, #2717) [@Black-Cat] - Checkbox: Added CheckboxFlags() helper with int* type. +- InputText: Fixed updating cursor/selection position when a callback altered the buffer in a way + where the byte count is unchanged but the decoded character count changes. (#3587) [@gqw] - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. - Misc: Replaced UTF-8 decoder by branchless one by Christopher Wellons (30~40% faster). [@rokups] - Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder + Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder returns IM_UNICODE_CODEPOINT_INVALID and consume remaining bytes (vs old decoded consumed only 1 byte). - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2c5e1814..d8f88f9e 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4273,10 +4273,11 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(callback_data.Buf == state->TextA.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == state->BufCapacityA); IM_ASSERT(callback_data.Flags == flags); - if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } - if (callback_data.SelectionStart != utf8_selection_start) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } - if (callback_data.SelectionEnd != utf8_selection_end) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } - if (callback_data.BufDirty) + const bool buf_dirty = callback_data.BufDirty; + if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } + if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } + if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } + if (buf_dirty) { IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! if (callback_data.BufTextLen > backup_current_text_length && is_resizable) From 61825c7735ada0797a536bbd74d5c93d9e23cef3 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Nov 2020 12:04:35 +0100 Subject: [PATCH 350/959] Tab Bar: Fixed minor/unlikely bug skipping over a button when scrolling left with arrows + InputText: minor optimization. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 8dc2aa48..ad6b11c4 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -59,6 +59,7 @@ Other Changes: - Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. - Tab Bar: Fixed using more than 128 tabs in a tab bar (scrolling policy recommended). - Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) +- Tab Bar: Fixed minor/unlikely bug skipping over a button when scrolling left with arrows. - Drag and Drop: Fix losing drop source ActiveID (and often source tooltip) when opening a TreeNode() or CollapsingHeader() while dragging. (#1738) - Drag and Drop: Fix drag and drop to tie same-size drop targets by choosen the later one. Fixes dragging diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index d8f88f9e..8fe841e1 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -4275,8 +4275,8 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(callback_data.Flags == flags); const bool buf_dirty = callback_data.BufDirty; if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } - if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } - if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } + if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb.select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb.cursor : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } + if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb.select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb.select_start : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } if (buf_dirty) { IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! @@ -7388,7 +7388,7 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) { target_order += select_dir; selected_order += select_dir; - tab_to_scroll_to = (target_order <= 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL; + tab_to_scroll_to = (target_order < 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL; } } } From 6a0e85c561cba43ceb4c401917756bd9d2c735d0 Mon Sep 17 00:00:00 2001 From: Brandon DeRosier Date: Sat, 7 Nov 2020 07:32:48 -0800 Subject: [PATCH 351/959] Backends: Vulkan: Add override for the subpass to reference during VkPipeline creation. (#3579) This allows for binding the pipeline/sending draw commands (via `ImGui_ImplVulkan_RenderDrawData`) against any subpass, rather than being restricted to only the first subpass. Without this, attempting to bind the pipeline against a subpass other than the first one results in validation layer errors and, at worst, some drivers failing if the subpass attachments differ. --- backends/imgui_impl_vulkan.cpp | 11 ++++++++--- backends/imgui_impl_vulkan.h | 1 + docs/CHANGELOG.txt | 1 + 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index 7e8a1a76..46062390 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -22,6 +22,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-11-11: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation. // 2020-09-07: Vulkan: Added VkPipeline parameter to ImGui_ImplVulkan_RenderDrawData (default to one passed to ImGui_ImplVulkan_Init). // 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices. // 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. @@ -81,6 +82,7 @@ static VkDescriptorSetLayout g_DescriptorSetLayout = VK_NULL_HANDLE; static VkPipelineLayout g_PipelineLayout = VK_NULL_HANDLE; static VkDescriptorSet g_DescriptorSet = VK_NULL_HANDLE; static VkPipeline g_Pipeline = VK_NULL_HANDLE; +static uint32_t g_Subpass = 0; static VkShaderModule g_ShaderModuleVert; static VkShaderModule g_ShaderModuleFrag; @@ -675,7 +677,7 @@ static void ImGui_ImplVulkan_CreatePipelineLayout(VkDevice device, const VkAlloc check_vk_result(err); } -static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline) +static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline, uint32_t subpass) { ImGui_ImplVulkan_CreateShaderModules(device, allocator); @@ -775,6 +777,7 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC info.pDynamicState = &dynamic_state; info.layout = g_PipelineLayout; info.renderPass = renderPass; + info.subpass = subpass; VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline); check_vk_result(err); } @@ -846,7 +849,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() check_vk_result(err); } - ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, g_RenderPass, v->MSAASamples, &g_Pipeline); + ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, g_RenderPass, v->MSAASamples, &g_Pipeline, g_Subpass); return true; } @@ -901,6 +904,8 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend g_VulkanInitInfo = *info; g_RenderPass = render_pass; + g_Subpass = info->Subpass; + ImGui_ImplVulkan_CreateDeviceObjects(); return true; @@ -1193,7 +1198,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V // We do not create a pipeline by default as this is also used by examples' main.cpp, // but secondary viewport in multi-viewport mode may want to create one with: - //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); + //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, g_Subpass); } // Create The Image Views diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 33dfe6ad..1e984b39 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -35,6 +35,7 @@ struct ImGui_ImplVulkan_InitInfo VkQueue Queue; VkPipelineCache PipelineCache; VkDescriptorPool DescriptorPool; + uint32_t Subpass; uint32_t MinImageCount; // >= 2 uint32_t ImageCount; // >= MinImageCount VkSampleCountFlagBits MSAASamples; // >= VK_SAMPLE_COUNT_1_BIT diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index ad6b11c4..1a320359 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -74,6 +74,7 @@ Other Changes: - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] +- Backends: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation. (@3579) [@bdero] - Backends: OSX: Fix keypad-enter key not working on MacOS. (#3554) [@rokups, @lfnoise] - Examples: Apple+Metal: Consolidated/simplified to get closer to other examples. (#3543) [@warrenm] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. From a3f79104dfab2224d29faa3309b7d529501e5437 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Wed, 28 Oct 2020 12:20:10 +0200 Subject: [PATCH 352/959] Examples: Apple+Metal: Forward events to OS key combinations like CMD+Q can work. (#3554) --- docs/CHANGELOG.txt | 1 + examples/example_apple_metal/main.mm | 29 +++++++++++++--------------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 1a320359..25e587a3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -77,6 +77,7 @@ Other Changes: - Backends: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation. (@3579) [@bdero] - Backends: OSX: Fix keypad-enter key not working on MacOS. (#3554) [@rokups, @lfnoise] - Examples: Apple+Metal: Consolidated/simplified to get closer to other examples. (#3543) [@warrenm] +- Examples: Apple+Metal: Forward events down so OS key combination like Cmd+Q can work. (#3554) [@rokups] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index 541dc5e1..015aee90 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -34,19 +34,19 @@ @implementation ViewController -- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil +- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; - + _device = MTLCreateSystemDefaultDevice(); _commandQueue = [_device newCommandQueue]; - if (!self.device) + if (!self.device) { NSLog(@"Metal is not supported"); abort(); } - + // Setup Dear ImGui context // FIXME: This example doesn't have proper cleanup... IMGUI_CHECKVERSION(); @@ -76,16 +76,16 @@ //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); - + return self; } -- (MTKView *)mtkView +- (MTKView *)mtkView { return (MTKView *)self.view; } -- (void)loadView +- (void)loadView { self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)]; } @@ -96,7 +96,7 @@ self.mtkView.device = self.device; self.mtkView.delegate = self; - + #if TARGET_OS_OSX // Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect @@ -108,20 +108,17 @@ // If we want to receive key events, we either need to be in the responder chain of the key view, // or else we can install a local monitor. The consequence of this heavy-handed approach is that // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our - // window, we'd want to be much more careful than just ingesting the complete event stream, though we - // do make an effort to be good citizens by passing along events when Dear ImGui doesn't want to capture. + // window, we'd want to be much more careful than just ingesting the complete event stream. + // To match the behavior of other backends, we pass every event down to the OS. NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged | NSEventTypeScrollWheel; [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) { - BOOL wantsCapture = ImGui_ImplOSX_HandleEvent(event, self.view); - if (event.type == NSEventTypeKeyDown && wantsCapture) - return nil; - else - return event; + ImGui_ImplOSX_HandleEvent(event, self.view); + return event; }]; ImGui_ImplOSX_Init(); - + #endif } From dcfb986fa84524845cd6bed036a95fd26f01d95a Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 11 Nov 2020 18:07:29 +0100 Subject: [PATCH 353/959] Made EndFrame() assertion for key modifiers being unchanged during the frame more lenient. (#3575) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 10 +++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 25e587a3..64308fff 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,9 @@ Other Changes: - Misc: Replaced UTF-8 decoder by branchless one by Christopher Wellons (30~40% faster). [@rokups] Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder returns IM_UNICODE_CODEPOINT_INVALID and consume remaining bytes (vs old decoded consumed only 1 byte). +- Misc: Made EndFrame() assertion for key modifiers being unchanged during the frame (added in 1.76) more + lenient, allowing full mid-frame releases. This is to accommodate the use of mid-frame modal native + windows calls, which leads backends such as GLFW to send key clearing events on focus loss. (#3575) - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] diff --git a/imgui.cpp b/imgui.cpp index 427806d8..4c372551 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6905,9 +6905,13 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame(). - const ImGuiKeyModFlags expected_key_mod_flags = GetMergedKeyModFlags(); - IM_ASSERT(g.IO.KeyMods == expected_key_mod_flags && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); - IM_UNUSED(expected_key_mod_flags); + // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will + // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs. + // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0), + // while still correctly asserting on mid-frame key press events. + const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags(); + IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); + IM_UNUSED(key_mod_flags); // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API). From 7a135a763c66e91cdf78d38ff343ffd06e39dec8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Nov 2020 11:56:04 +0100 Subject: [PATCH 354/959] Fix format warnings when using gnu printf extensions in a setup that supports them (gcc/mingw). (#3592) --- docs/CHANGELOG.txt | 3 ++- imgui.h | 17 ++++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 64308fff..2c85200e 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,9 +68,10 @@ Other Changes: - InputText: Fixed updating cursor/selection position when a callback altered the buffer in a way where the byte count is unchanged but the decoded character count changes. (#3587) [@gqw] - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. -- Misc: Replaced UTF-8 decoder by branchless one by Christopher Wellons (30~40% faster). [@rokups] +- Misc: Replaced UTF-8 decoder with one based on branchless one by Christopher Wellons. [@rokups] Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder returns IM_UNICODE_CODEPOINT_INVALID and consume remaining bytes (vs old decoded consumed only 1 byte). +- Misc: Fix format warnings when using gnu printf extensions in a setup that supports them (gcc/mingw). (#3592) - Misc: Made EndFrame() assertion for key modifiers being unchanged during the frame (added in 1.76) more lenient, allowing full mid-frame releases. This is to accommodate the use of mid-frame modal native windows calls, which leads backends such as GLFW to send key clearing events on focus loss. (#3575) diff --git a/imgui.h b/imgui.h index f3dcac71..b0a35138 100644 --- a/imgui.h +++ b/imgui.h @@ -78,13 +78,6 @@ Index of this file: #include #define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h #endif -#if !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__)) -#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // To apply printf-style warnings to our functions. -#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) -#else -#define IM_FMTARGS(FMT) -#define IM_FMTLIST(FMT) -#endif #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! #define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. #if (__cplusplus >= 201100) @@ -92,6 +85,16 @@ Index of this file: #else #define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Old style macro. #endif +#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__clang__) +#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // Apply printf-style warnings to our formatting functions. +#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) +#elif !defined(IMGUI_USE_STB_SPRINTF) && defined(__GNUC__) +#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) // Apply printf-style warnings to our formatting functions. +#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) +#else +#define IM_FMTARGS(FMT) +#define IM_FMTLIST(FMT) +#endif // Warnings #if defined(__clang__) From 13258f59575eae643affea976abe818417047777 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Nov 2020 12:01:49 +0100 Subject: [PATCH 355/959] Internals: zero-clearing ImGuiWindow / ImGuiWindowTempData for simplicity. (amend) All the non-zero fields previously initialized in ImGuiWindowTempData() are in fact setup in Begin: FocusCounterRegular, FocusCounterTabStop, TextWrapPos, LayoutType, ParentLayoutType --- imgui.cpp | 51 ++++-------------------------------------------- imgui_internal.h | 37 ++--------------------------------- 2 files changed, 6 insertions(+), 82 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4c372551..ca7afd36 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2774,70 +2774,27 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl //----------------------------------------------------------------------------- // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods -ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) - : DrawListInst(&context->DrawListSharedData) +ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL) { + memset(this, 0, sizeof(*this)); Name = ImStrdup(name); + NameBufLen = (int)strlen(name) + 1; ID = ImHashStr(name); IDStack.push_back(ID); - Flags = ImGuiWindowFlags_None; - Pos = ImVec2(0.0f, 0.0f); - Size = SizeFull = ImVec2(0.0f, 0.0f); - ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f); - WindowPadding = ImVec2(0.0f, 0.0f); - WindowRounding = 0.0f; - WindowBorderSize = 0.0f; - NameBufLen = (int)strlen(name) + 1; MoveId = GetID("#MOVE"); - ChildId = 0; - Scroll = ImVec2(0.0f, 0.0f); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); - ScrollbarSizes = ImVec2(0.0f, 0.0f); - ScrollbarX = ScrollbarY = false; - Active = WasActive = false; - WriteAccessed = false; - Collapsed = false; - WantCollapseToggle = false; - SkipItems = false; - Appearing = false; - Hidden = false; - IsFallbackWindow = false; - HasCloseButton = false; - ResizeBorderHeld = -1; - BeginCount = 0; - BeginOrderWithinParent = -1; - BeginOrderWithinContext = -1; - PopupId = 0; AutoFitFramesX = AutoFitFramesY = -1; - AutoFitChildAxises = 0x00; - AutoFitOnlyGrows = false; AutoPosLastDirection = ImGuiDir_None; - HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); - - InnerRect = ImRect(0.0f, 0.0f, 0.0f, 0.0f); // Clear so the InnerRect.GetSize() code in Begin() doesn't lead to overflow even if the result isn't used. - LastFrameActive = -1; LastTimeActive = -1.0f; - ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; SettingsOffset = -1; - DrawList = &DrawListInst; + DrawList->_Data = &context->DrawListSharedData; DrawList->_OwnerName = Name; - ParentWindow = NULL; - RootWindow = NULL; - RootWindowForTitleBarHighlight = NULL; - RootWindowForNav = NULL; - - NavLastIds[0] = NavLastIds[1] = 0; - NavRectRel[0] = NavRectRel[1] = ImRect(); - NavLastChildNavWindow = NULL; - - MemoryCompacted = false; - MemoryDrawListIdxCapacity = MemoryDrawListVtxCapacity = 0; } ImGuiWindow::~ImGuiWindow() diff --git a/imgui_internal.h b/imgui_internal.h index 6b701a0b..8e19894e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1503,7 +1503,8 @@ struct ImGuiContext //----------------------------------------------------------------------------- // Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. -// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered. +// (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) +// (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin) struct IMGUI_API ImGuiWindowTempData { // Layout @@ -1557,40 +1558,6 @@ struct IMGUI_API ImGuiWindowTempData ImVector TextWrapPosStack; ImVectorGroupStack; short StackSizesBackup[6]; // Store size of various stacks for asserting - - ImGuiWindowTempData() - { - CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); - CurrLineSize = PrevLineSize = ImVec2(0.0f, 0.0f); - CurrLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; - Indent = ImVec1(0.0f); - ColumnsOffset = ImVec1(0.0f); - GroupOffset = ImVec1(0.0f); - - LastItemId = 0; - LastItemStatusFlags = ImGuiItemStatusFlags_None; - LastItemRect = LastItemDisplayRect = ImRect(); - - NavLayerActiveMask = NavLayerActiveMaskNext = 0x00; - NavLayerCurrent = ImGuiNavLayer_Main; - NavFocusScopeIdCurrent = 0; - NavHideHighlightOneFrame = false; - NavHasScroll = false; - - MenuBarAppending = false; - MenuBarOffset = ImVec2(0.0f, 0.0f); - TreeDepth = 0; - TreeJumpToParentOnPopMask = 0x00; - StateStorage = NULL; - CurrentColumns = NULL; - LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical; - FocusCounterRegular = FocusCounterTabStop = -1; - - ItemFlags = ImGuiItemFlags_Default_; - ItemWidth = 0.0f; - TextWrapPos = -1.0f; - memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); - } }; // Storage for one window From 78f1d2d319b31fc5e78f154baf3746ec59a6c551 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Nov 2020 17:34:30 +0100 Subject: [PATCH 356/959] ImDrawListSplitter: create first draw cmd on demand + Internals: fix incorrect ImBitArraySetBitRange() (only used by tables) Make it cheaper to allocate unused draw cmd, can't measure perf difference other our stress tests. --- imgui_draw.cpp | 13 +++++-------- imgui_internal.h | 10 +++++----- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 8a102220..f922f689 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1417,6 +1417,7 @@ void ImDrawListSplitter::ClearFreeMemory() void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) { + IM_UNUSED(draw_list); IM_ASSERT(_Current == 0 && _Count <= 1 && "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter."); int old_channels_count = _Channels.Size; if (old_channels_count < channels_count) @@ -1441,12 +1442,6 @@ void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) _Channels[i]._CmdBuffer.resize(0); _Channels[i]._IdxBuffer.resize(0); } - if (_Channels[i]._CmdBuffer.Size == 0) - { - ImDrawCmd draw_cmd; - ImDrawCmd_HeaderCopy(&draw_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset - _Channels[i]._CmdBuffer.push_back(draw_cmd); - } } } @@ -1536,8 +1531,10 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx) draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size; // 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* curr_cmd = (draw_list->CmdBuffer.Size == 0) ? NULL : &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1]; + if (curr_cmd == NULL) + draw_list->AddDrawCmd(); + else if (curr_cmd->ElemCount == 0) ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0) draw_list->AddDrawCmd(); diff --git a/imgui_internal.h b/imgui_internal.h index 8e19894e..a661c3a9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -453,15 +453,15 @@ struct IMGUI_API ImRect }; // Helper: ImBitArray -inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; } -inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; } -inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; } -inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2) +inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; } +inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; } +inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; } +inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2) { while (n <= n2) { int a_mod = (n & 31); - int b_mod = ((n2 >= n + 31) ? 31 : (n2 & 31)) + 1; + int b_mod = (n2 > (n | 31) ? 31 : (n2 & 31)) + 1; ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1); arr[n >> 5] |= mask; n = (n + 32) & ~31; From a138855d569fd4f9490d7936b6b5ac26af259bcd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 12 Nov 2020 21:12:05 +0100 Subject: [PATCH 357/959] Hotfix for PushFocusScope() being utterly wrong (until we split the stacks), Added asserts on PopID to help catch bugs, Added GC trigger. --- imgui.cpp | 24 ++++++++++++++++-------- imgui_internal.h | 1 + imgui_widgets.cpp | 2 +- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ca7afd36..398e3900 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3845,7 +3845,7 @@ void ImGui::NewFrame() // Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); - const float memory_compact_start_time = (g.IO.ConfigMemoryCompactTimer >= 0.0f) ? (float)g.Time - g.IO.ConfigMemoryCompactTimer : FLT_MAX; + const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; @@ -3858,6 +3858,7 @@ void ImGui::NewFrame() if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time) GcCompactTransientWindowBuffers(window); } + g.GcCompactAll = false; // Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow && !g.NavWindow->WasActive) @@ -6650,12 +6651,14 @@ void ImGui::ActivateItem(ImGuiID id) g.NavNextActivateId = id; } -// Note: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there. +// FIXME: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there. Maybe play nice and a separate in-context stack. void ImGui::PushFocusScope(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + ImGuiID top_most_id = window->IDStack.back(); window->IDStack.push_back(window->DC.NavFocusScopeIdCurrent); + window->IDStack.push_back(top_most_id); window->DC.NavFocusScopeIdCurrent = id; } @@ -6665,6 +6668,8 @@ void ImGui::PopFocusScope() ImGuiWindow* window = g.CurrentWindow; window->DC.NavFocusScopeIdCurrent = window->IDStack.back(); window->IDStack.pop_back(); + IM_ASSERT(window->IDStack.Size > 1); // Too many PopID or PopFocusScope (or could be popping in a wrong/different window?) + window->IDStack.pop_back(); } void ImGui::SetKeyboardFocusHere(int offset) @@ -6763,6 +6768,7 @@ ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed) void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; + IM_ASSERT(window->IDStack.Size > 1); // Too many PopID or PopFocusScope (or could be popping in a wrong/different window?) window->IDStack.pop_back(); } @@ -10323,12 +10329,14 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; // Basic info - ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); - ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); - ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows); - ImGui::Text("%d active allocations", io.MetricsActiveAllocations); - ImGui::Separator(); + Text("Dear ImGui %s", ImGui::GetVersion()); + Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); + Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows); + Text("%d active allocations", io.MetricsActiveAllocations); + //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; } + + Separator(); // Debugging enums enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type diff --git a/imgui_internal.h b/imgui_internal.h index a661c3a9..b46d665a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1148,6 +1148,7 @@ struct ImGuiContext bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed bool WithinEndChild; // Set within EndChild() + bool GcCompactAll; // Request full GC bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() ImGuiID TestEngineHookIdInfo; // Will call test engine hooks: ImGuiTestEngineHook_IdInfo() from GetID() void* TestEngine; // Test engine user data diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 8fe841e1..4cb52b19 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7489,7 +7489,7 @@ void ImGui::EndTabItem() IM_ASSERT(tab_bar->LastTabItemIdx >= 0); ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) - window->IDStack.pop_back(); + PopID(); } bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) From a3e8dc3f34668457e43ab683b44221a4a6101d63 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Fri, 13 Nov 2020 12:07:32 +0200 Subject: [PATCH 358/959] CI: Fix deployment of PVS-Studio license + fix reported error. --- .github/workflows/static-analysis.yml | 5 ++--- imgui_internal.h | 1 + 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 0b7ef361..7a9b573e 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -3,8 +3,6 @@ name: static-analysis on: push: {} pull_request: {} - schedule: - - cron: '0 9 * * *' jobs: PVS-Studio: @@ -16,16 +14,17 @@ jobs: - name: Install Dependencies env: + # The Secret variable setup in GitHub must be in format: "name_or_email key", on a single line PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }} run: | if [[ "$PVS_STUDIO_LICENSE" != "" ]]; then - echo "$PVS_STUDIO_LICENSE" > pvs-studio.lic wget -q https://files.viva64.com/etc/pubkey.txt sudo apt-key add pubkey.txt sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list sudo apt-get update sudo apt-get install -y pvs-studio + pvs-studio-analyzer credentials -o pvs-studio.lic $PVS_STUDIO_LICENSE fi - name: PVS-Studio static analysis diff --git a/imgui_internal.h b/imgui_internal.h index b46d665a..c4d267e5 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1368,6 +1368,7 @@ struct ImGuiContext FrameCount = 0; FrameCountEnded = FrameCountRendered = -1; WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false; + GcCompactAll = false; TestEngineHookItems = false; TestEngineHookIdInfo = 0; TestEngine = NULL; From 12ba6f46066642efd02eac1becee660e1d4a5d79 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Nov 2020 14:09:09 +0100 Subject: [PATCH 359/959] Fix PushFocusScopeID() + using shared stack. Renamed GetFocusScopeID() to GetFocusedFocusScope() - the two existing functions name are very error prone. --- imgui.cpp | 21 ++++++++------------- imgui.h | 5 ++++- imgui_internal.h | 4 +++- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 398e3900..488ccccb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -5962,7 +5962,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; - window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // -V595 window->DC.NavHideHighlightOneFrame = false; window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f); @@ -6030,12 +6029,12 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetCurrentWindow(window); } + window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // -V595 + PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) - if (first_begin_of_the_frame) - window->WriteAccessed = false; - + window->WriteAccessed = false; window->BeginCount++; g.NextWindowData.ClearFlags(); @@ -6651,14 +6650,11 @@ void ImGui::ActivateItem(ImGuiID id) g.NavNextActivateId = id; } -// FIXME: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there. Maybe play nice and a separate in-context stack. void ImGui::PushFocusScope(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiID top_most_id = window->IDStack.back(); - window->IDStack.push_back(window->DC.NavFocusScopeIdCurrent); - window->IDStack.push_back(top_most_id); + g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent); window->DC.NavFocusScopeIdCurrent = id; } @@ -6666,10 +6662,9 @@ void ImGui::PopFocusScope() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - window->DC.NavFocusScopeIdCurrent = window->IDStack.back(); - window->IDStack.pop_back(); - IM_ASSERT(window->IDStack.Size > 1); // Too many PopID or PopFocusScope (or could be popping in a wrong/different window?) - window->IDStack.pop_back(); + IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ? + window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back(); + g.FocusScopeStack.pop_back(); } void ImGui::SetKeyboardFocusHere(int offset) @@ -6768,7 +6763,7 @@ ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed) void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; - IM_ASSERT(window->IDStack.Size > 1); // Too many PopID or PopFocusScope (or could be popping in a wrong/different window?) + IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window? window->IDStack.pop_back(); } diff --git a/imgui.h b/imgui.h index b0a35138..75e045fa 100644 --- a/imgui.h +++ b/imgui.h @@ -291,7 +291,10 @@ namespace ImGui // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. - // Always call a matching EndChild() for each BeginChild() call, regardless of its return value [as with Begin: this is due to legacy reason and inconsistent with most BeginXXX functions apart from the regular Begin() which behaves like BeginChild().] + // Always call a matching EndChild() for each BeginChild() call, regardless of its return value. + // [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu, + // BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function + // returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0); IMGUI_API void EndChild(); diff --git a/imgui_internal.h b/imgui_internal.h index c4d267e5..26f47883 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1207,6 +1207,7 @@ struct ImGuiContext ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() ImVector FontStack; // Stack for PushFont()/PopFont() + ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() ImVectorOpenPopupStack; // Which popups are open (persistent) ImVectorBeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) @@ -1910,7 +1911,8 @@ namespace ImGui // patterns generally need to react (e.g. clear selection) when landing on an item of the set. IMGUI_API void PushFocusScope(ImGuiID id); IMGUI_API void PopFocusScope(); - inline ImGuiID GetFocusScopeID() { ImGuiContext& g = *GImGui; return g.NavFocusScopeId; } + inline ImGuiID GetFocusedFocusScope() { ImGuiContext& g = *GImGui; return g.NavFocusScopeId; } // Focus scope which is actually active + inline ImGuiID GetFocusScope() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.NavFocusScopeIdCurrent; } // Focus scope we are outputting into, set by PushFocusScope() // Inputs // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. From 6e94013a3db1867f3cb421ccbbcea7a0f065a35e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Nov 2020 14:36:32 +0100 Subject: [PATCH 360/959] Made ItemFlagsStack and GroupStack shared stacks. --- docs/CHANGELOG.txt | 3 ++ imgui.cpp | 77 ++++++++++++++++++++++++++++------------------ imgui.h | 8 ++--- imgui_internal.h | 11 ++++--- imgui_widgets.cpp | 6 ++-- 5 files changed, 65 insertions(+), 40 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2c85200e..89506712 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -68,6 +68,9 @@ Other Changes: - InputText: Fixed updating cursor/selection position when a callback altered the buffer in a way where the byte count is unchanged but the decoded character count changes. (#3587) [@gqw] - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. +- Misc: Made the ItemFlags stack shared, so effectively the ButtonRepeat/AllowKeyboardFocus states + (and others exposed in internals such as PushItemFlag) are inherited by stacked Begin/End pairs, + vs previously a non-child stacked Begin() would reset those flags back to zero for the stacked window. - Misc: Replaced UTF-8 decoder with one based on branchless one by Christopher Wellons. [@rokups] Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder returns IM_UNICODE_CODEPOINT_INVALID and consume remaining bytes (vs old decoded consumed only 1 byte). diff --git a/imgui.cpp b/imgui.cpp index 488ccccb..aa07c3f6 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -872,7 +872,7 @@ static int FindWindowFocusIndex(ImGuiWindow* window); // Error Checking static void ErrorCheckNewFrameSanityChecks(); static void ErrorCheckEndFrameSanityChecks(); -static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write); +static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool begin); // Misc static void UpdateSettings(); @@ -2892,6 +2892,13 @@ static void SetCurrentWindow(ImGuiWindow* window) g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } +void ImGui::GcCompactTransientMiscBuffers() +{ + ImGuiContext& g = *GImGui; + g.ItemFlagsStack.clear(); + g.GroupStack.clear(); +} + // Free up/compact internal window buffers, we can use this when a window becomes unused. // This is currently unused by the library, but you may call this yourself for easy GC. // Not freed: @@ -2906,10 +2913,8 @@ void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window) window->IDStack.clear(); window->DrawList->_ClearFreeMemory(); window->DC.ChildWindows.clear(); - window->DC.ItemFlagsStack.clear(); window->DC.ItemWidthStack.clear(); window->DC.TextWrapPosStack.clear(); - window->DC.GroupStack.clear(); } void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window) @@ -3858,6 +3863,8 @@ void ImGui::NewFrame() if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time) GcCompactTransientWindowBuffers(window); } + if (g.GcCompactAll) + GcCompactTransientMiscBuffers(); g.GcCompactAll = false; // Closing the focused window restore focus to the first active root window in descending z-order @@ -3868,6 +3875,9 @@ void ImGui::NewFrame() // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); g.BeginPopupStack.resize(0); + g.ItemFlagsStack.resize(0); + g.ItemFlagsStack.push_back(ImGuiItemFlags_Default_); + g.GroupStack.resize(0); ClosePopupsOverWindow(g.NavWindow, false); // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. @@ -5978,13 +5988,8 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled - window->DC.ItemFlagsStack.resize(0); window->DC.ItemWidthStack.resize(0); window->DC.TextWrapPosStack.resize(0); - window->DC.GroupStack.resize(0); - window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_; - if (parent_window) - window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); if (window->AutoFitFramesX > 0) window->AutoFitFramesX--; @@ -6029,7 +6034,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) SetCurrentWindow(window); } - window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // -V595 + // Pull/inherit current state + window->DC.ItemFlags = g.ItemFlagsStack.back(); // Inherit from shared stack + window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // Inherit from parent only // -V595 PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); @@ -6257,19 +6264,25 @@ void ImGui::PopFont() void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiItemFlags item_flags = window->DC.ItemFlags; + IM_ASSERT(item_flags == g.ItemFlagsStack.back()); if (enabled) - window->DC.ItemFlags |= option; + item_flags |= option; else - window->DC.ItemFlags &= ~option; - window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); + item_flags &= ~option; + window->DC.ItemFlags = item_flags; + g.ItemFlagsStack.push_back(item_flags); } void ImGui::PopItemFlag() { - ImGuiWindow* window = GetCurrentWindow(); - window->DC.ItemFlagsStack.pop_back(); - window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack. + g.ItemFlagsStack.pop_back(); + window->DC.ItemFlags = g.ItemFlagsStack.back(); } // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system. @@ -6886,27 +6899,29 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?"); } } + + IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!"); } // Save and compare stack sizes on Begin()/End() to detect usage errors // Begin() calls this with write=true // End() calls this with write=false -static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool write) +static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool begin) { ImGuiContext& g = *GImGui; short* p = &window->DC.StackSizesBackup[0]; // Window stacks - // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) - { int n = window->IDStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "PushID/PopID or TreeNode/TreePop Mismatch!"); p++; } // Too few or too many PopID()/TreePop() - { int n = window->DC.GroupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup() + // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) + { IM_ASSERT(window->IDStack.Size == 1 && "PushID/PopID or TreeNode/TreePop Mismatch!"); } // Too few or too many PopID()/TreePop(); // Global stacks // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them. - { int n = g.BeginPopupStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup() - { int n = g.ColorModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor() - { int n = g.StyleModifiers.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar() - { int n = g.FontStack.Size; if (write) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont() + { int n = g.GroupStack.Size; if (begin) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup() + { int n = g.BeginPopupStack.Size; if (begin) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup() + { int n = g.ColorModifiers.Size; if (begin) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor() + { int n = g.StyleModifiers.Size; if (begin) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar() + { int n = g.FontStack.Size; if (begin) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont() IM_ASSERT(p == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } @@ -7310,8 +7325,9 @@ void ImGui::BeginGroup() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); - ImGuiGroupData& group_data = window->DC.GroupStack.back(); + g.GroupStack.resize(g.GroupStack.Size + 1); + ImGuiGroupData& group_data = g.GroupStack.back(); + group_data.WindowID = window->ID; group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.BackupIndent = window->DC.Indent; @@ -7334,9 +7350,10 @@ void ImGui::EndGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(window->DC.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls + IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls - ImGuiGroupData& group_data = window->DC.GroupStack.back(); + ImGuiGroupData& group_data = g.GroupStack.back(); + IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window? ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos)); @@ -7351,7 +7368,7 @@ void ImGui::EndGroup() if (!group_data.EmitItem) { - window->DC.GroupStack.pop_back(); + g.GroupStack.pop_back(); return; } @@ -7380,7 +7397,7 @@ void ImGui::EndGroup() if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame) window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated; - window->DC.GroupStack.pop_back(); + g.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] } diff --git a/imgui.h b/imgui.h index 75e045fa..c472d9a2 100644 --- a/imgui.h +++ b/imgui.h @@ -358,6 +358,10 @@ namespace ImGui IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. 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 @@ -373,10 +377,6 @@ namespace ImGui IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); - IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets - IMGUI_API void PopAllowKeyboardFocus(); - IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. - IMGUI_API void PopButtonRepeat(); // Cursor / Layout // - By "cursor" we mean the current output position. diff --git a/imgui_internal.h b/imgui_internal.h index 26f47883..fb990db3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -826,6 +826,7 @@ struct ImGuiStyleMod // Stacked storage data for BeginGroup()/EndGroup() struct ImGuiGroupData { + ImGuiID WindowID; ImVec2 BackupCursorPos; ImVec2 BackupCursorMaxPos; ImVec1 BackupIndent; @@ -1208,6 +1209,8 @@ struct ImGuiContext ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() ImVector FontStack; // Stack for PushFont()/PopFont() ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() + ImVectorItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() + ImVectorGroupStack; // Stack for BeginGroup()/EndGroup() ImVectorOpenPopupStack; // Which popups are open (persistent) ImVectorBeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) @@ -1553,14 +1556,12 @@ struct IMGUI_API ImGuiWindowTempData // Local parameters stacks // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. - ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default] + ImGuiItemFlags ItemFlags; // == g.ItemFlagsStack.back() float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] - ImVectorItemFlagsStack; ImVector ItemWidthStack; ImVector TextWrapPosStack; - ImVectorGroupStack; - short StackSizesBackup[6]; // Store size of various stacks for asserting + short StackSizesBackup[5]; // Store size of various stacks for asserting }; // Storage for one window @@ -1849,6 +1850,7 @@ namespace ImGui inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemStatusFlags; } inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } + inline ImGuiItemFlags GetItemsFlags() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.ItemFlags; } IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window); IMGUI_API void ClearActiveID(); @@ -2045,6 +2047,7 @@ namespace ImGui IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp); // Garbage collection + IMGUI_API void GcCompactTransientMiscBuffers(); IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window); IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 4cb52b19..b8e7591f 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1346,7 +1346,9 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) // Horizontal Separator float x1 = window->Pos.x; float x2 = window->Pos.x + window->Size.x; - if (!window->DC.GroupStack.empty()) + + // FIXME-WORKRECT: old hack (#205) until we decide of consistent behavior with WorkRect/Indent and Separator + if (g.GroupStack.Size > 0 && g.GroupStack.back().WindowID == window->ID) x1 += window->DC.Indent.x; ImGuiColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL; @@ -6500,7 +6502,7 @@ void ImGui::EndMenuBar() PopClipRect(); PopID(); window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->MenuBarRect().Min.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. - window->DC.GroupStack.back().EmitItem = false; + g.GroupStack.back().EmitItem = false; EndGroup(); // Restore position on layer 0 window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; From 8119759329e9c9096b4a5f62c8ce3e8db49325eb Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Nov 2020 16:26:43 +0100 Subject: [PATCH 361/959] Internals: extracted stack checking code into a ImGuiStackSizes helper struct + added test for FocusScope + renamed g.ColorModifiers > g.ColorStack, g.StyleModifiers > g.StyleVarStack --- imgui.cpp | 63 +++++++++++++++++++++++++++++------------------- imgui_internal.h | 35 +++++++++++++++++++++------ 2 files changed, 66 insertions(+), 32 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index aa07c3f6..3a00b310 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -872,7 +872,6 @@ static int FindWindowFocusIndex(ImGuiWindow* window); // Error Checking static void ErrorCheckNewFrameSanityChecks(); static void ErrorCheckEndFrameSanityChecks(); -static void ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool begin); // Misc static void UpdateSettings(); @@ -2352,7 +2351,7 @@ void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col) ImGuiColorMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; - g.ColorModifiers.push_back(backup); + g.ColorStack.push_back(backup); g.Style.Colors[idx] = ColorConvertU32ToFloat4(col); } @@ -2362,7 +2361,7 @@ void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) ImGuiColorMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; - g.ColorModifiers.push_back(backup); + g.ColorStack.push_back(backup); g.Style.Colors[idx] = col; } @@ -2371,9 +2370,9 @@ void ImGui::PopStyleColor(int count) ImGuiContext& g = *GImGui; while (count > 0) { - ImGuiColorMod& backup = g.ColorModifiers.back(); + ImGuiColorMod& backup = g.ColorStack.back(); g.Style.Colors[backup.Col] = backup.BackupValue; - g.ColorModifiers.pop_back(); + g.ColorStack.pop_back(); count--; } } @@ -2427,7 +2426,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { ImGuiContext& g = *GImGui; float* pvar = (float*)var_info->GetVarPtr(&g.Style); - g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } @@ -2441,7 +2440,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { ImGuiContext& g = *GImGui; ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); - g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } @@ -2454,12 +2453,12 @@ void ImGui::PopStyleVar(int count) while (count > 0) { // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it. - ImGuiStyleMod& backup = g.StyleModifiers.back(); + ImGuiStyleMod& backup = g.StyleVarStack.back(); const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); void* data = info->GetVarPtr(&g.Style); if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } - g.StyleModifiers.pop_back(); + g.StyleVarStack.pop_back(); count--; } } @@ -3996,8 +3995,8 @@ void ImGui::Shutdown(ImGuiContext* context) g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; g.MovingWindow = NULL; - g.ColorModifiers.clear(); - g.StyleModifiers.clear(); + g.ColorStack.clear(); + g.StyleVarStack.clear(); g.FontStack.clear(); g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); @@ -5515,8 +5514,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Add to stack // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow() g.CurrentWindowStack.push_back(window); + g.CurrentWindow = window; + window->DC.StackSizesOnBegin.SetToCurrentState(); g.CurrentWindow = NULL; - ErrorCheckBeginEndCompareStacksSize(window, true); + if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; @@ -6112,7 +6113,7 @@ void ImGui::End() g.CurrentWindowStack.pop_back(); if (window->Flags & ImGuiWindowFlags_Popup) g.BeginPopupStack.pop_back(); - ErrorCheckBeginEndCompareStacksSize(window, false); + window->DC.StackSizesOnBegin.CompareWithCurrentState(); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } @@ -6903,26 +6904,38 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!"); } -// Save and compare stack sizes on Begin()/End() to detect usage errors -// Begin() calls this with write=true -// End() calls this with write=false -static void ImGui::ErrorCheckBeginEndCompareStacksSize(ImGuiWindow* window, bool begin) +// Save current stack sizes for later compare +void ImGuiStackSizes::SetToCurrentState() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + SizeOfIDStack = (short)window->IDStack.Size; + SizeOfColorStack = (short)g.ColorStack.Size; + SizeOfStyleVarStack = (short)g.StyleVarStack.Size; + SizeOfFontStack = (short)g.FontStack.Size; + SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size; + SizeOfGroupStack = (short)g.GroupStack.Size; + SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size; +} + +// Compare to detect usage errors +void ImGuiStackSizes::CompareWithCurrentState() { ImGuiContext& g = *GImGui; - short* p = &window->DC.StackSizesBackup[0]; + ImGuiWindow* window = g.CurrentWindow; // Window stacks // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) - { IM_ASSERT(window->IDStack.Size == 1 && "PushID/PopID or TreeNode/TreePop Mismatch!"); } // Too few or too many PopID()/TreePop(); + IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!"); // Global stacks // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them. - { int n = g.GroupStack.Size; if (begin) *p = (short)n; else IM_ASSERT(*p == n && "BeginGroup/EndGroup Mismatch!"); p++; } // Too few or too many EndGroup() - { int n = g.BeginPopupStack.Size; if (begin) *p = (short)n; else IM_ASSERT(*p == n && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch!"); p++; }// Too few or too many EndMenu()/EndPopup() - { int n = g.ColorModifiers.Size; if (begin) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleColor/PopStyleColor Mismatch!"); p++; } // Too few or too many PopStyleColor() - { int n = g.StyleModifiers.Size; if (begin) *p = (short)n; else IM_ASSERT(*p >= n && "PushStyleVar/PopStyleVar Mismatch!"); p++; } // Too few or too many PopStyleVar() - { int n = g.FontStack.Size; if (begin) *p = (short)n; else IM_ASSERT(*p >= n && "PushFont/PopFont Mismatch!"); p++; } // Too few or too many PopFont() - IM_ASSERT(p == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); + IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!"); + IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!"); + IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!"); + IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!"); + IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!"); + IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!"); } diff --git a/imgui_internal.h b/imgui_internal.h index fb990db3..7a190969 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -23,6 +23,7 @@ Index of this file: // [SECTION] Docking support // [SECTION] Viewport support // [SECTION] Settings support +// [SECTION] Metrics, Debug // [SECTION] Generic context hooks // [SECTION] ImGuiContext (main imgui context) // [SECTION] ImGuiWindowTempData, ImGuiWindow @@ -106,6 +107,7 @@ struct ImGuiNextWindowData; // Storage for SetNextWindow** functions struct ImGuiNextItemData; // Storage for SetNextItem** functions struct ImGuiPopupData; // Storage for current popup stack struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file +struct ImGuiStackSizes; // Storage of stack sizes for debugging/asserting struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it struct ImGuiTabBar; // Storage for a tab bar struct ImGuiTabItem; // Storage for a tab item (within a tab bar) @@ -1089,6 +1091,10 @@ struct ImGuiSettingsHandler ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } }; +//----------------------------------------------------------------------------- +// [SECTION] Metrics, Debug +//----------------------------------------------------------------------------- + struct ImGuiMetricsConfig { bool ShowWindowsRects; @@ -1111,6 +1117,21 @@ struct ImGuiMetricsConfig } }; +struct IMGUI_API ImGuiStackSizes +{ + short SizeOfIDStack; + short SizeOfColorStack; + short SizeOfStyleVarStack; + short SizeOfFontStack; + short SizeOfFocusScopeStack; + short SizeOfGroupStack; + short SizeOfBeginPopupStack; + + ImGuiStackSizes() { memset(this, 0, sizeof(*this)); } + IMGUI_API void SetToCurrentState(); + IMGUI_API void CompareWithCurrentState(); +}; + //----------------------------------------------------------------------------- // [SECTION] Generic context hooks //----------------------------------------------------------------------------- @@ -1205,12 +1226,12 @@ struct ImGuiContext ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions // Shared stacks - ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() - ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() - ImVector FontStack; // Stack for PushFont()/PopFont() - ImVector FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - ImVectorItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - ImVectorGroupStack; // Stack for BeginGroup()/EndGroup() + 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 FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - not inherited by Begin(), unless child window + ImVectorItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() + ImVectorGroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() ImVectorOpenPopupStack; // Which popups are open (persistent) ImVectorBeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) @@ -1561,7 +1582,7 @@ struct IMGUI_API ImGuiWindowTempData float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] ImVector ItemWidthStack; ImVector TextWrapPosStack; - short StackSizesBackup[5]; // Store size of various stacks for asserting + ImGuiStackSizes StackSizesOnBegin; // Store size of various stacks for asserting }; // Storage for one window From e736039538182d50d41e011e3fc246df396fa229 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Nov 2020 20:59:59 +0100 Subject: [PATCH 362/959] Nav: Fixed IsItemFocused() from returning false when Nav highlight is hidden because mouse has moved. (#787) --- docs/CHANGELOG.txt | 3 +++ imgui.cpp | 7 +++---- imgui.h | 4 ++-- imgui_demo.cpp | 5 +++-- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 89506712..f967bebb 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -67,6 +67,9 @@ Other Changes: - Checkbox: Added CheckboxFlags() helper with int* type. - InputText: Fixed updating cursor/selection position when a callback altered the buffer in a way where the byte count is unchanged but the decoded character count changes. (#3587) [@gqw] +- Nav: Fixed IsItemFocused() from returning false when Nav highlight is hidden because mouse has moved. + It's essentially been always the case but it doesn't make much sense. Instead we will aim at exposing + feedback and control of keyboard/gamepad navigation highlight and mouse hover disable flag. (#787, #2048) - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. - Misc: Made the ItemFlags stack shared, so effectively the ButtonRepeat/AllowKeyboardFocus states (and others exposed in internals such as PushItemFlag) are inherited by stacked Begin/End pairs, diff --git a/imgui.cpp b/imgui.cpp index 3a00b310..ea1b12c3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2899,10 +2899,8 @@ void ImGui::GcCompactTransientMiscBuffers() } // Free up/compact internal window buffers, we can use this when a window becomes unused. -// This is currently unused by the library, but you may call this yourself for easy GC. // Not freed: -// - ImGuiWindow, ImGuiWindowSettings, Name -// - StateStorage, ColumnsStorage (may hold useful data) +// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data) // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window) { @@ -4642,12 +4640,13 @@ bool ImGui::IsItemDeactivatedAfterEdit() return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore)); } +// == GetItemID() == GetFocusID() bool ImGui::IsItemFocused() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId) + if (g.NavId != window->DC.LastItemId || g.NavId == 0) return false; return true; } diff --git a/imgui.h b/imgui.h index c472d9a2..4586fa0a 100644 --- a/imgui.h +++ b/imgui.h @@ -390,8 +390,8 @@ namespace ImGui IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context. IMGUI_API void Spacing(); // add vertical spacing. IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. - IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0 - IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0 + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 IMGUI_API void BeginGroup(); // lock horizontal starting position IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 07cd3a23..14aaff61 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -380,8 +380,9 @@ void ImGui::ShowDemoWindow(bool* p_open) if (ImGui::TreeNode("Configuration##2")) { ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard); + ImGui::SameLine(); HelpMarker("Enable keyboard controls."); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad); - ImGui::SameLine(); HelpMarker("Required backend to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); + ImGui::SameLine(); HelpMarker("Enable gamepad controls. Require backend to set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details."); ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", &io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos); ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos."); ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, ImGuiConfigFlags_NoMouse); @@ -3568,7 +3569,7 @@ static void ShowDemoWindowMisc() char label[32]; sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]); ImGui::Bullet(); ImGui::Selectable(label, false); - if (ImGui::IsItemHovered() || ImGui::IsItemFocused()) + if (ImGui::IsItemHovered()) ImGui::SetMouseCursor(i); } ImGui::TreePop(); From 71cc636696bd17c81514da49707e909958c14632 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Nov 2020 21:17:46 +0100 Subject: [PATCH 363/959] Metrics: Rebranded as "Dear ImGui Metrics/Debugger". Fix Show Window Rectangle. Fix Clang OSX warnings. Amend #3592 for Mingw only. --- docs/CHANGELOG.txt | 1 + imconfig.h | 2 +- imgui.cpp | 12 ++++++------ imgui.h | 4 ++-- imgui_demo.cpp | 4 ++-- imgui_draw.cpp | 3 +++ imgui_internal.h | 2 +- 7 files changed, 16 insertions(+), 12 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index f967bebb..0098b612 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -71,6 +71,7 @@ Other Changes: It's essentially been always the case but it doesn't make much sense. Instead we will aim at exposing feedback and control of keyboard/gamepad navigation highlight and mouse hover disable flag. (#787, #2048) - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. +- Metrics: Rebranded as "Dear ImGui Metrics/Debugger" to clarify its purpose. - Misc: Made the ItemFlags stack shared, so effectively the ButtonRepeat/AllowKeyboardFocus states (and others exposed in internals such as PushItemFlag) are inherited by stacked Begin/End pairs, vs previously a non-child stacked Begin() would reset those flags back to zero for the stacked window. diff --git a/imconfig.h b/imconfig.h index 015540f3..736958b3 100644 --- a/imconfig.h +++ b/imconfig.h @@ -31,7 +31,7 @@ // It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp. //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. -//#define IMGUI_DISABLE_METRICS_WINDOW // Disable debug/metrics window: ShowMetricsWindow() will be empty. +//#define IMGUI_DISABLE_METRICS_WINDOW // Disable metrics/debugger window: ShowMetricsWindow() will be empty. //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. diff --git a/imgui.cpp b/imgui.cpp index ea1b12c3..dad7ff7b 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4058,7 +4058,7 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list) { // Remove trailing command if unused. - // Technically we could return directly instead of popping, but this make things looks neat in Metrics window as well. + // Technically we could return directly instead of popping, but this make things looks neat in Metrics/Debugger window as well. draw_list->_PopUnusedDrawCmd(); if (draw_list->CmdBuffer.Size == 0) return; @@ -4073,7 +4073,7 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) // If this assert triggers because you are drawing lots of stuff manually: // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds. - // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics window to inspect draw list contents. + // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents. // - If you want large meshes with more than 64K vertices, you can either: // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. // Most example backends already support this from 1.71. Pre-1.71 backends won't. @@ -10342,7 +10342,7 @@ static void MetricsHelpMarker(const char* desc) void ImGui::ShowMetricsWindow(bool* p_open) { - if (!Begin("Dear ImGui Metrics", p_open)) + if (!Begin("Dear ImGui Metrics/Debugger", p_open)) { End(); return; @@ -10370,7 +10370,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) if (cfg->ShowWindowsRectsType < 0) cfg->ShowWindowsRectsType = WRT_WorkRect; if (cfg->ShowTablesRectsType < 0) - cfg->ShowWindowsRectsType = TRT_WorkRect; + cfg->ShowTablesRectsType = TRT_WorkRect; struct Funcs { @@ -10398,7 +10398,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash."); Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder); - ImGui::Checkbox("Show windows rectangles", &cfg->ShowWindowsRects); + Checkbox("Show windows rectangles", &cfg->ShowWindowsRects); SameLine(); SetNextItemWidth(GetFontSize() * 12); cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count); @@ -10595,7 +10595,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) } #endif // #ifdef IMGUI_HAS_DOCK - ImGui::End(); + End(); } // [DEBUG] Display contents of Columns diff --git a/imgui.h b/imgui.h index 4586fa0a..6d2b54cd 100644 --- a/imgui.h +++ b/imgui.h @@ -88,7 +88,7 @@ Index of this file: #if !defined(IMGUI_USE_STB_SPRINTF) && defined(__clang__) #define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // Apply printf-style warnings to our formatting functions. #define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) -#elif !defined(IMGUI_USE_STB_SPRINTF) && defined(__GNUC__) +#elif !defined(IMGUI_USE_STB_SPRINTF) && defined(__GNUC__) && defined(__MINGW32__) #define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) // Apply printf-style warnings to our formatting functions. #define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) #else @@ -260,7 +260,7 @@ namespace ImGui // Demo, Debug, Information IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information. - IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Debug/Metrics window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc. IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 14aaff61..045ae509 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -340,7 +340,7 @@ void ImGui::ShowDemoWindow(bool* p_open) } if (ImGui::BeginMenu("Tools")) { - ImGui::MenuItem("Metrics", NULL, &show_app_metrics); + ImGui::MenuItem("Metrics/Debugger", NULL, &show_app_metrics); ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor); ImGui::MenuItem("About Dear ImGui", NULL, &show_app_about); ImGui::EndMenu(); @@ -357,7 +357,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::BulletText("Sections below are demonstrating many aspects of the library."); ImGui::BulletText("The \"Examples\" menu above leads to more demo contents."); ImGui::BulletText("The \"Tools\" menu above gives access to: About Box, Style Editor,\n" - "and Metrics (general purpose Dear ImGui debugging tool)."); + "and Metrics/Debugger (general purpose Dear ImGui debugging tool)."); ImGui::Separator(); ImGui::Text("PROGRAMMER GUIDE:"); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index f922f689..306c296e 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -60,6 +60,9 @@ Index of this file: #if __has_warning("-Wunknown-warning-option") #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! #endif +#if __has_warning("-Walloca") +#pragma clang diagnostic ignored "-Walloca" // warning: use of function '__builtin_alloca' is discouraged +#endif #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. diff --git a/imgui_internal.h b/imgui_internal.h index 7a190969..55b2e641 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1639,7 +1639,7 @@ struct IMGUI_API ImGuiWindow ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. - // The best way to understand what those rectangles are is to use the 'Metrics -> Tools -> Show windows rectangles' viewer. + // The best way to understand what those rectangles are is to use the 'Metrics->Tools->Show Windows Rectangles' viewer. // The main 'OuterRect', omitted as a field, is window->Rect(). ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar) From 2e64ee050d4ee142ac7c22df7cce99e9dfc1cb53 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Nov 2020 19:28:30 +0100 Subject: [PATCH 364/959] Removed duplicate typedef for ImGuiButtonFlags https://github.com/cimgui/cimgui/issues/166 --- imgui_internal.h | 1 - 1 file changed, 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 55b2e641..86816c51 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -117,7 +117,6 @@ struct ImGuiWindowSettings; // Storage for a window .ini settings (we ke // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical -typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior() typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: BeginColumns() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags From fcc2b717246c9256b43ed80dd2f4ac4de4691e8a Mon Sep 17 00:00:00 2001 From: Borislav Stanimirov Date: Wed, 18 Nov 2020 22:05:52 +0200 Subject: [PATCH 365/959] CI: Fix testing for Windows DLL builds + fix broken DLL build. (#3603, #3601) --- .github/workflows/build.yml | 19 ++++++++++--------- docs/CHANGELOG.txt | 1 + imgui_internal.h | 4 ++-- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a8db3199..dca1be02 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -49,7 +49,8 @@ jobs: shell: cmd run: | cd examples\example_null - "%VS_PATH%\VC\Auxiliary\Build\vcvarsall.bat" x64 && .\build_win32.bat /W4 + call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" + .\build_win32.bat /W4 - name: Build example_null (single file build) shell: bash @@ -71,14 +72,14 @@ jobs: - name: Build example_null (as DLL) shell: cmd run: | - "%VS_PATH%\VC\Auxiliary\Build\vcvarsall.bat" x64 - echo '#ifdef _EXPORT' > example_single_file.cpp - echo '# define IMGUI_API __declspec(dllexport)' >> example_single_file.cpp - echo '#else' >> example_single_file.cpp - echo '# define IMGUI_API __declspec(dllimport)' >> example_single_file.cpp - echo '#endif' >> example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" + echo #ifdef _EXPORT > example_single_file.cpp + echo # define IMGUI_API __declspec(dllexport) >> example_single_file.cpp + echo #else >> example_single_file.cpp + echo # define IMGUI_API __declspec(dllimport) >> example_single_file.cpp + echo #endif >> example_single_file.cpp + echo #define IMGUI_IMPLEMENTATION >> example_single_file.cpp + echo #include "misc/single_file/imgui_single_file.h" >> example_single_file.cpp cl.exe /D_USRDLL /D_WINDLL /D_EXPORT /I. example_single_file.cpp /LD /FeImGui.dll /link cl.exe /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 0098b612..7564fae1 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -89,6 +89,7 @@ Other Changes: - Backends: OSX: Fix keypad-enter key not working on MacOS. (#3554) [@rokups, @lfnoise] - Examples: Apple+Metal: Consolidated/simplified to get closer to other examples. (#3543) [@warrenm] - Examples: Apple+Metal: Forward events down so OS key combination like Cmd+Q can work. (#3554) [@rokups] +- CI: Fix testing for Windows DLL builds. (#3603, #3601) [@iboB] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. diff --git a/imgui_internal.h b/imgui_internal.h index 86816c51..afae7778 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1127,8 +1127,8 @@ struct IMGUI_API ImGuiStackSizes short SizeOfBeginPopupStack; ImGuiStackSizes() { memset(this, 0, sizeof(*this)); } - IMGUI_API void SetToCurrentState(); - IMGUI_API void CompareWithCurrentState(); + void SetToCurrentState(); + void CompareWithCurrentState(); }; //----------------------------------------------------------------------------- From 72de6f336070bb28281b758609f4097a58adf901 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Nov 2020 22:40:27 +0100 Subject: [PATCH 366/959] Columns/Internals: (Breaking) renamed ImGuiColumnsFlags_* to ImGuiOldColumnFlags_*. (#125, #513, #913, #1204, #1444, #2142, #2707) Affected: ImGuiColumnsFlags_None, ImGuiColumnsFlags_NoBorder, ImGuiColumnsFlags_NoResize, ImGuiColumnsFlags_NoPreserveWidths, ImGuiColumnsFlags_NoForceWithinWindow, ImGuiColumnsFlags_GrowParentContentsSize. Added redirection enums. Did not add redirection type. --- docs/CHANGELOG.txt | 2 ++ imgui.cpp | 1 + imgui_internal.h | 36 +++++++++++++++++++++++------------- imgui_widgets.cpp | 23 +++++++++++------------ 4 files changed, 37 insertions(+), 25 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7564fae1..2d4122d3 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -50,6 +50,8 @@ Breaking Changes: - If you were still using the old names, while you are cleaning up, considering enabling IMGUI_DISABLE_OBSOLETE_FUNCTIONS in imconfig.h even temporarily to have a pass at finding and removing up old API calls, if any remaining. +- Columns: renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of + incoming Tables API. Keep redirection enums (will obsolete). (#125, #513, #913, #1204, #1444, #2142, #2707) - Renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures. (#2636) diff --git a/imgui.cpp b/imgui.cpp index dad7ff7b..1743d34f 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -371,6 +371,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API. - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): diff --git a/imgui_internal.h b/imgui_internal.h index afae7778..ee2931b7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -117,9 +117,9 @@ struct ImGuiWindowSettings; // Storage for a window .ini settings (we ke // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical -typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: BeginColumns() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag() typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags +typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns() typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d() typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests @@ -990,22 +990,32 @@ struct ImGuiPtrOrIndex // [SECTION] Columns support //----------------------------------------------------------------------------- -enum ImGuiColumnsFlags_ +// Flags for internal's BeginColumns(). Prefix using BeginTable() nowadays! +enum ImGuiOldColumnFlags_ { - // Default: 0 - ImGuiColumnsFlags_None = 0, - ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers - ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers - ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns - ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window - ImGuiColumnsFlags_GrowParentContentsSize= 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. + ImGuiOldColumnFlags_None = 0, + ImGuiOldColumnFlags_NoBorder = 1 << 0, // Disable column dividers + ImGuiOldColumnFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers + ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns + ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window + ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. + + // Obsolete names (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + , ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None, + ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder, + ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize, + ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths, + ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow, + ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize +#endif }; struct ImGuiColumnData { float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) float OffsetNormBeforeResize; - ImGuiColumnsFlags Flags; // Not exposed + ImGuiOldColumnFlags Flags; // Not exposed ImRect ClipRect; ImGuiColumnData() { memset(this, 0, sizeof(*this)); } @@ -1014,7 +1024,7 @@ struct ImGuiColumnData struct ImGuiColumns { ImGuiID ID; - ImGuiColumnsFlags Flags; + ImGuiOldColumnFlags Flags; bool IsFirstFrame; bool IsBeingResized; int Current; @@ -1954,8 +1964,8 @@ namespace ImGui // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect); - IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). - IMGUI_API void EndColumns(); // close columns + IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). + IMGUI_API void EndColumns(); // close columns IMGUI_API void PushColumnClipRect(int column_index); IMGUI_API void PushColumnsBackground(); IMGUI_API void PopColumnsBackground(); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index b8e7591f..42135651 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7930,7 +7930,7 @@ static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); - if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) + if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths)) x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); return x; @@ -7989,10 +7989,10 @@ void ImGui::SetColumnOffset(int column_index, float offset) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); - const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count - 1); + const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1); const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; - if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) + if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow)) offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX); @@ -8074,7 +8074,7 @@ ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) return id; } -void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) +void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); @@ -8220,16 +8220,16 @@ void ImGui::EndColumns() columns->Splitter.Merge(window->DrawList); } - const ImGuiColumnsFlags flags = columns->Flags; + const ImGuiOldColumnFlags flags = columns->Flags; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = columns->LineMaxY; - if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize)) + if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize)) window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent // Draw columns borders and handle resize // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy bool is_being_resized = false; - if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) + if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems) { // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); @@ -8247,12 +8247,12 @@ void ImGui::EndColumns() continue; bool hovered = false, held = false; - if (!(flags & ImGuiColumnsFlags_NoResize)) + if (!(flags & ImGuiOldColumnFlags_NoResize)) { ButtonBehavior(column_hit_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; - if (held && !(column->Flags & ImGuiColumnsFlags_NoResize)) + if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize)) dragging_column = n; } @@ -8282,14 +8282,13 @@ void ImGui::EndColumns() window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); } -// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] void ImGui::Columns(int columns_count, const char* id, bool border) { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); - ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); - //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior + ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder); + //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior ImGuiColumns* columns = window->DC.CurrentColumns; if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) return; From c0ac4fb78863303338e04b6d2e6c51e7b98e62e0 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 18 Nov 2020 23:42:44 +0100 Subject: [PATCH 367/959] Columns/Internals: (Breaking): Renamed data structures. (#125, #513, #913, #1204, #1444, #2142, #2707) --- imgui.cpp | 8 ++++---- imgui_internal.h | 26 ++++++++++++------------- imgui_widgets.cpp | 48 +++++++++++++++++++++++------------------------ 3 files changed, 41 insertions(+), 41 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 1743d34f..784fa722 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2188,7 +2188,7 @@ static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height) window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y); window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. - if (ImGuiColumns* columns = window->DC.CurrentColumns) + if (ImGuiOldColumns* columns = window->DC.CurrentColumns) columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } @@ -2802,7 +2802,7 @@ ImGuiWindow::~ImGuiWindow() IM_ASSERT(DrawList == &DrawListInst); IM_DELETE(Name); for (int i = 0; i != ColumnsStorage.Size; i++) - ColumnsStorage[i].~ImGuiColumns(); + ColumnsStorage[i].~ImGuiOldColumns(); } ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) @@ -10600,7 +10600,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) } // [DEBUG] Display contents of Columns -void ImGui::DebugNodeColumns(ImGuiColumns* columns) +void ImGui::DebugNodeColumns(ImGuiOldColumns* columns) { if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) return; @@ -10858,7 +10858,7 @@ void ImGui::DebugNodeWindowsList(ImVector* windows, const char* la #else void ImGui::ShowMetricsWindow(bool*) {} -void ImGui::DebugNodeColumns(ImGuiColumns*) {} +void ImGui::DebugNodeColumns(ImGuiOldColumns*) {} void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {} void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} diff --git a/imgui_internal.h b/imgui_internal.h index ee2931b7..aceeab87 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -92,8 +92,6 @@ struct ImRect; // An axis-aligned rectangle (2 points) struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it -struct ImGuiColumnData; // Storage data for a single column -struct ImGuiColumns; // Storage data for a columns set struct ImGuiContext; // Main Dear ImGui context struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum @@ -105,6 +103,8 @@ struct ImGuiNavMoveResult; // Result of a gamepad/keyboard directional struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions struct ImGuiNextWindowData; // Storage for SetNextWindow** functions struct ImGuiNextItemData; // Storage for SetNextItem** functions +struct ImGuiOldColumnData; // Storage data for a single column for legacy Columns() api +struct ImGuiOldColumns; // Storage data for a columns set for legacy Columns() api struct ImGuiPopupData; // Storage for current popup stack struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file struct ImGuiStackSizes; // Storage of stack sizes for debugging/asserting @@ -1011,17 +1011,17 @@ enum ImGuiOldColumnFlags_ #endif }; -struct ImGuiColumnData +struct ImGuiOldColumnData { float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) float OffsetNormBeforeResize; ImGuiOldColumnFlags Flags; // Not exposed ImRect ClipRect; - ImGuiColumnData() { memset(this, 0, sizeof(*this)); } + ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); } }; -struct ImGuiColumns +struct ImGuiOldColumns { ImGuiID ID; ImGuiOldColumnFlags Flags; @@ -1036,10 +1036,10 @@ struct ImGuiColumns ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() ImRect HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns() - ImVector Columns; + ImVector Columns; ImDrawListSplitter Splitter; - ImGuiColumns() { memset(this, 0, sizeof(*this)); } + ImGuiOldColumns() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- @@ -1578,7 +1578,7 @@ struct IMGUI_API ImGuiWindowTempData ImU32 TreeJumpToParentOnPopMask; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary. ImVector ChildWindows; ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) - ImGuiColumns* CurrentColumns; // Current columns set + ImGuiOldColumns* CurrentColumns; // Current columns set ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() int FocusCounterRegular; // (Legacy Focus/Tabbing system) Sequential counter, start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign) @@ -1664,7 +1664,7 @@ struct IMGUI_API ImGuiWindow float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) float ItemWidthDefault; ImGuiStorage StateStorage; - ImVector ColumnsStorage; + ImVector ColumnsStorage; float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) @@ -1970,9 +1970,9 @@ namespace ImGui IMGUI_API void PushColumnsBackground(); IMGUI_API void PopColumnsBackground(); IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count); - IMGUI_API ImGuiColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); - IMGUI_API float GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm); - IMGUI_API float GetColumnNormFromOffset(const ImGuiColumns* columns, float offset); + IMGUI_API ImGuiOldColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); + IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm); + IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); // Tab Bars IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); @@ -2085,7 +2085,7 @@ namespace ImGui inline void DebugDrawItemRect(ImU32 col = IM_COL32(255,0,0,255)) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; GetForegroundDrawList(window)->AddRect(window->DC.LastItemRect.Min, window->DC.LastItemRect.Max, col); } inline void DebugStartItemPicker() { ImGuiContext& g = *GImGui; g.DebugItemPickerActive = true; } - IMGUI_API void DebugNodeColumns(ImGuiColumns* columns); + IMGUI_API void DebugNodeColumns(ImGuiOldColumns* columns); IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label); IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 42135651..2dcc7af5 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1351,7 +1351,7 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) if (g.GroupStack.Size > 0 && g.GroupStack.back().WindowID == window->ID) x1 += window->DC.Indent.x; - ImGuiColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL; + ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL; if (columns) PushColumnsBackground(); @@ -7907,19 +7907,19 @@ int ImGui::GetColumnsCount() return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; } -float ImGui::GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm) +float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm) { return offset_norm * (columns->OffMaxX - columns->OffMinX); } -float ImGui::GetColumnNormFromOffset(const ImGuiColumns* columns, float offset) +float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset) { return offset / (columns->OffMaxX - columns->OffMinX); } static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; -static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) +static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. @@ -7939,7 +7939,7 @@ static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) float ImGui::GetColumnOffset(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; if (columns == NULL) return 0.0f; @@ -7952,7 +7952,7 @@ float ImGui::GetColumnOffset(int column_index) return x_offset; } -static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false) +static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false) { if (column_index < 0) column_index = columns->Current; @@ -7969,7 +7969,7 @@ float ImGui::GetColumnWidth(int column_index) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; if (columns == NULL) return GetContentRegionAvail().x; @@ -7982,7 +7982,7 @@ void ImGui::SetColumnOffset(int column_index, float offset) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) @@ -8003,7 +8003,7 @@ void ImGui::SetColumnOffset(int column_index, float offset) void ImGui::SetColumnWidth(int column_index, float width) { ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) @@ -8014,11 +8014,11 @@ void ImGui::SetColumnWidth(int column_index, float width) void ImGui::PushColumnClipRect(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; if (column_index < 0) column_index = columns->Current; - ImGuiColumnData* column = &columns->Columns[column_index]; + ImGuiOldColumnData* column = &columns->Columns[column_index]; PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); } @@ -8026,7 +8026,7 @@ void ImGui::PushColumnClipRect(int column_index) void ImGui::PushColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; @@ -8039,7 +8039,7 @@ void ImGui::PushColumnsBackground() void ImGui::PopColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) return; @@ -8048,15 +8048,15 @@ void ImGui::PopColumnsBackground() columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); } -ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) +ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) { // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. for (int n = 0; n < window->ColumnsStorage.Size; n++) if (window->ColumnsStorage[n].ID == id) return &window->ColumnsStorage[n]; - window->ColumnsStorage.push_back(ImGuiColumns()); - ImGuiColumns* columns = &window->ColumnsStorage.back(); + window->ColumnsStorage.push_back(ImGuiOldColumns()); + ImGuiOldColumns* columns = &window->ColumnsStorage.back(); columns->ID = id; return columns; } @@ -8084,7 +8084,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFl // Acquire storage for the columns set ImGuiID id = GetColumnsID(str_id, columns_count); - ImGuiColumns* columns = FindOrCreateColumns(window, id); + ImGuiOldColumns* columns = FindOrCreateColumns(window, id); IM_ASSERT(columns->ID == id); columns->Current = 0; columns->Count = columns_count; @@ -8118,7 +8118,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFl columns->Columns.reserve(columns_count + 1); for (int n = 0; n < columns_count + 1; n++) { - ImGuiColumnData column; + ImGuiOldColumnData column; column.OffsetNorm = n / (float)columns_count; columns->Columns.push_back(column); } @@ -8127,7 +8127,7 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFl for (int n = 0; n < columns_count; n++) { // Compute clipping rectangle - ImGuiColumnData* column = &columns->Columns[n]; + ImGuiOldColumnData* column = &columns->Columns[n]; float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n)); float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f); column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); @@ -8158,7 +8158,7 @@ void ImGui::NextColumn() return; ImGuiContext& g = *GImGui; - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) { @@ -8175,7 +8175,7 @@ void ImGui::NextColumn() // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), - ImGuiColumnData* column = &columns->Columns[columns->Current]; + ImGuiOldColumnData* column = &columns->Columns[columns->Current]; SetWindowClipRectBeforeSetChannel(window, column->ClipRect); columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); @@ -8210,7 +8210,7 @@ void ImGui::EndColumns() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); PopItemWidth(); @@ -8237,7 +8237,7 @@ void ImGui::EndColumns() int dragging_column = -1; for (int n = 1; n < columns->Count; n++) { - ImGuiColumnData* column = &columns->Columns[n]; + ImGuiOldColumnData* column = &columns->Columns[n]; float x = window->Pos.x + GetColumnOffset(n); const ImGuiID column_id = columns->ID + ImGuiID(n); const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; @@ -8289,7 +8289,7 @@ void ImGui::Columns(int columns_count, const char* id, bool border) ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder); //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior - ImGuiColumns* columns = window->DC.CurrentColumns; + ImGuiOldColumns* columns = window->DC.CurrentColumns; if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) return; From 9712bff0bb4b566fe1437f9dafac6c78cc9f4818 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Nov 2020 15:04:27 +0100 Subject: [PATCH 368/959] Internals: added experimental ErrorCheckEndFrameRecover() to unroll/end/pop. (#1651, #3600) --- imgui.cpp | 89 ++++++++++++++++++++++++++++++++++++++++++++---- imgui_internal.h | 3 ++ 2 files changed, 85 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 784fa722..29d592af 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6842,8 +6842,8 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means you assert macro is incorrectly defined! // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block. // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.) - // #define IM_ASSERT(EXPR) SomeCode(EXPR); SomeMoreCode(); // Wrong! - // #define IM_ASSERT(EXPR) do { SomeCode(EXPR); SomeMoreCode(); } while (0) // Correct! + // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong! + // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct! if (true) IM_ASSERT(1); else IM_ASSERT(0); // Check user data @@ -6852,21 +6852,21 @@ 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->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); - IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); + IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?"); + IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?"); IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!"); - IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!"); + 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 IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); - // Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP) + // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP) if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); - // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. + // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) g.IO.ConfigWindowsResizeFromEdges = false; } @@ -6885,6 +6885,9 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(key_mod_flags); + // Recover from errors + //ErrorCheckEndFrameRecover(); + // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API). if (g.CurrentWindowStack.Size != 1) @@ -6904,6 +6907,78 @@ static void ImGui::ErrorCheckEndFrameSanityChecks() IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!"); } +// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls. +// Must be called during or before EndFrame(). +// This is generally flawed as we are not necessarily End/Popping things in the right order. +// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet. +// FIXME: Can't recover from interleaved BeginTabBar/Begin +void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data) +{ + // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations" + ImGuiContext& g = *GImGui; + while (g.CurrentWindowStack.Size > 0) + { +#ifdef IMGUI_HAS_TABLE + while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow)) + { + if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name); + EndTable(); + } +#endif + ImGuiWindow* window = g.CurrentWindow; + while (g.CurrentTabBar != NULL) //-V1044 + { + if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name); + EndTabBar(); + } + while (g.CurrentWindow->DC.TreeDepth > 0) //-V1044 + { + if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name); + TreePop(); + } + while (g.GroupStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfGroupStack) //-V1044 + { + if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name); + EndGroup(); + } + while (g.CurrentWindow->IDStack.Size > 1) //-V1044 + { + if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name); + PopID(); + } + while (g.ColorStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfColorStack) //-V1044 + { + if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col)); + PopStyleColor(); + } + while (g.StyleVarStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfStyleVarStack) //-V1044 + { + if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name); + PopStyleVar(); + } + while (g.FocusScopeStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfFocusScopeStack) //-V1044 + { + if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name); + PopFocusScope(); + } + if (g.CurrentWindowStack.Size == 1) + { + IM_ASSERT(g.CurrentWindow->IsFallbackWindow); + break; + } + if (g.CurrentWindow->Flags & ImGuiWindowFlags_ChildWindow) + { + if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name); + EndChild(); + } + else + { + if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name); + End(); + } + } +} + // Save current stack sizes for later compare void ImGuiStackSizes::SetToCurrentState() { diff --git a/imgui_internal.h b/imgui_internal.h index aceeab87..2fe36fba 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -129,6 +129,8 @@ typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // F typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() +typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...); + //----------------------------------------------------------------------------- // [SECTION] Context pointer // See implementation of this variable in imgui.cpp for comments and details. @@ -2082,6 +2084,7 @@ namespace ImGui IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); // Debug Tools + IMGUI_API void ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL); inline void DebugDrawItemRect(ImU32 col = IM_COL32(255,0,0,255)) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; GetForegroundDrawList(window)->AddRect(window->DC.LastItemRect.Min, window->DC.LastItemRect.Max, col); } inline void DebugStartItemPicker() { ImGuiContext& g = *GImGui; g.DebugItemPickerActive = true; } From cecf6b4209b4494ade5c54eba8f645030e9a5baa Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Nov 2020 16:07:07 +0100 Subject: [PATCH 369/959] Viewports: made standalone modals appear in taskbar + new window perform z-check before merging in main host viewport. (#3511, #1542) This should fix a good amount of "lost modal" problems, however it is still possible to loose a modal in a host viewport if secondary viewports are configured as children above the host. --- imgui.cpp | 16 ++++++++++------ imgui.h | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7165637a..e86a4968 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6227,10 +6227,13 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Update common viewport flags const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; - const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; + const bool is_modal = (flags & ImGuiWindowFlags_Modal) != 0; + const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0 && !is_modal; if (flags & ImGuiWindowFlags_Tooltip) viewport_flags |= ImGuiViewportFlags_TopMost; - if (g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) + //if (flags & ImGuiWindowFlags_Modal) + // viewport_flags |= ImGuiViewportFlags_TopMost; // Not correct because other popups can be stack above a modal? + if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal) viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon; if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window) viewport_flags |= ImGuiViewportFlags_NoDecoration; @@ -6239,7 +6242,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere. - if (is_short_lived_floating_window && (flags & ImGuiWindowFlags_Modal) == 0) + if (is_short_lived_floating_window && !is_modal) viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick; // We can overwrite viewport flags using ImGuiWindowClass (advanced users) @@ -11426,10 +11429,11 @@ static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) UpdateTryMergeWindowIntoHostViewports(window); } - // Fallback to default viewport + // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport if (window->Viewport == NULL) - window->Viewport = main_viewport; - + if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport)) + window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); + // Mark window as allowed to protrude outside of its viewport and into the current monitor if (!lock_viewport) { diff --git a/imgui.h b/imgui.h index b40a2c14..6a54d30f 100644 --- a/imgui.h +++ b/imgui.h @@ -1609,7 +1609,7 @@ struct ImGuiIO // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) bool ConfigViewportsNoAutoMerge; // = false; // Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags_NoAutoMerge on individual viewport. bool ConfigViewportsNoTaskBarIcon; // = false // Disable default OS task bar icon flag for secondary viewports. When a viewport doesn't want a task bar icon, ImGuiViewportFlags_NoTaskBarIcon will be set on it. - bool ConfigViewportsNoDecoration; // = true // [BETA] 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 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. // Miscellaneous options From 97265602c43903577c3199d242be8561dc6dbabe Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Nov 2020 16:58:14 +0100 Subject: [PATCH 370/959] Internals: added IsWindowAbove() for use for modal/viewport bugfix. --- imgui.cpp | 26 +++++++++++++++----------- imgui_internal.h | 1 + 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 29d592af..d973b451 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3436,17 +3436,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() // Find the top-most window between HoveredWindow and the top-most Modal Window. // This is where we can trim the popup stack. ImGuiWindow* modal = GetTopMostPopupModal(); - bool hovered_window_above_modal = false; - if (modal == NULL) - hovered_window_above_modal = true; - for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--) - { - ImGuiWindow* window = g.Windows[i]; - if (window == modal) - break; - if (window == g.HoveredWindow) - hovered_window_above_modal = true; - } + bool hovered_window_above_modal = g.HoveredWindow && IsWindowAbove(g.HoveredWindow, modal); ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true); } } @@ -6334,6 +6324,20 @@ bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent) return false; } +bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below) +{ + ImGuiContext& g = *GImGui; + for (int i = g.Windows.Size - 1; i >= 0; i--) + { + ImGuiWindow* candidate_window = g.Windows[i]; + if (candidate_window == potential_above) + return true; + if (candidate_window == potential_below) + return false; + } + return false; +} + bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) { IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function diff --git a/imgui_internal.h b/imgui_internal.h index 2fe36fba..f3ab30e7 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1827,6 +1827,7 @@ namespace ImGui IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window); IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent); + IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below); IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); From d4f08d893e54a309d3b09059b6a3ffb959abd4a2 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Nov 2020 18:30:14 +0100 Subject: [PATCH 371/959] InputText: Fixed swiching from single to multi-line while preserving same ID. --- docs/CHANGELOG.txt | 1 + imgui_widgets.cpp | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 2d4122d3..a9ddcca9 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -69,6 +69,7 @@ Other Changes: - Checkbox: Added CheckboxFlags() helper with int* type. - InputText: Fixed updating cursor/selection position when a callback altered the buffer in a way where the byte count is unchanged but the decoded character count changes. (#3587) [@gqw] +- InputText: Fixed swiching from single to multi-line while preserving same ID. - Nav: Fixed IsItemFocused() from returning false when Nav highlight is hidden because mouse has moved. It's essentially been always the case but it doesn't make much sense. Instead we will aim at exposing feedback and control of keyboard/gamepad navigation highlight and mouse hover disable flag. (#787, #2048) diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2dcc7af5..08a741fb 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -3857,9 +3857,10 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX; + const bool init_changed_specs = (state != NULL && state->Stb.single_line != !is_multiline); const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start); const bool init_state = (init_make_active || user_scroll_active); - if (init_state && g.ActiveId != id) + if ((init_state && g.ActiveId != id) || init_changed_specs) { // Access state even if we don't own it yet. state = &g.InputTextState; @@ -3881,7 +3882,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Preserve cursor position and undo/redo stack if we come back to same widget // FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed. - const bool recycle_state = (state->ID == id); + const bool recycle_state = (state->ID == id && !init_changed_specs); if (recycle_state) { // Recycle existing cursor/selection/undo stack but clamp position From 3dcbcd8bf0d0331a7bc870bbf725145e6beed069 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Nov 2020 16:58:14 +0100 Subject: [PATCH 372/959] Internals: added IsWindowAbove() for use for modal/viewport bugfix. --- imgui.cpp | 26 +++++++++++++++----------- imgui_internal.h | 1 + 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e86a4968..83ed42f7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3571,17 +3571,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() // Find the top-most window between HoveredWindow and the top-most Modal Window. // This is where we can trim the popup stack. ImGuiWindow* modal = GetTopMostPopupModal(); - bool hovered_window_above_modal = false; - if (modal == NULL) - hovered_window_above_modal = true; - for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--) - { - ImGuiWindow* window = g.Windows[i]; - if (window == modal) - break; - if (window == g.HoveredWindow) - hovered_window_above_modal = true; - } + bool hovered_window_above_modal = g.HoveredWindow && IsWindowAbove(g.HoveredWindow, modal); ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true); } } @@ -6956,6 +6946,20 @@ bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent) return false; } +bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below) +{ + ImGuiContext& g = *GImGui; + for (int i = g.Windows.Size - 1; i >= 0; i--) + { + ImGuiWindow* candidate_window = g.Windows[i]; + if (candidate_window == potential_above) + return true; + if (candidate_window == potential_below) + return false; + } + return false; +} + bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) { IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function diff --git a/imgui_internal.h b/imgui_internal.h index f9ff8098..490fc2f3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2026,6 +2026,7 @@ namespace ImGui IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window); IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent); + IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below); IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window); IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); From 4da92b89ed5861d4630d4ed2c3c702ad962b2202 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 19 Nov 2020 17:03:56 +0100 Subject: [PATCH 373/959] Viewports: fix incorrect whitening of popups above a modal if both use their own viewport + fix pvs warning. --- imgui.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 83ed42f7..11cb361a 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -4385,6 +4385,8 @@ static void ImGui::EndFrameDrawDimmedBackgrounds() continue; if (g.NavWindowingTargetAnim && viewport == g.NavWindowingTargetAnim->Viewport) continue; + if (viewport->Window && modal_window && IsWindowAbove(viewport->Window, modal_window)) + continue; ImDrawList* draw_list = GetForegroundDrawList(viewport); const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col); @@ -6218,16 +6220,20 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; const bool is_modal = (flags & ImGuiWindowFlags_Modal) != 0; - const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0 && !is_modal; + const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; if (flags & ImGuiWindowFlags_Tooltip) viewport_flags |= ImGuiViewportFlags_TopMost; - //if (flags & ImGuiWindowFlags_Modal) - // viewport_flags |= ImGuiViewportFlags_TopMost; // Not correct because other popups can be stack above a modal? if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal) viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon; if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window) viewport_flags |= ImGuiViewportFlags_NoDecoration; + // Not correct to set modal as topmost because: + // - Because other popups can be stacked above a modal (e.g. combo box in a modal) + // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" + //if (flags & ImGuiWindowFlags_Modal) + // viewport_flags |= ImGuiViewportFlags_TopMost; + // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, From e0cae25c3c01c9be6aa9520a035e03c44835153e Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 20 Nov 2020 17:24:18 +0100 Subject: [PATCH 374/959] Clarify usage of right-aligned items in Layout>Widgets Width. Tweaks FAQ, added missing syntax coloring. --- docs/CHANGELOG.txt | 1 + docs/FAQ.md | 41 +++++++++++++------------- docs/FONTS.md | 60 +++++++++++++++++--------------------- imgui.cpp | 2 +- imgui_demo.cpp | 72 ++++++++++++++++++++++++++++++++++------------ 5 files changed, 102 insertions(+), 74 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index a9ddcca9..d335a07c 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -85,6 +85,7 @@ Other Changes: - Misc: Made EndFrame() assertion for key modifiers being unchanged during the frame (added in 1.76) more lenient, allowing full mid-frame releases. This is to accommodate the use of mid-frame modal native windows calls, which leads backends such as GLFW to send key clearing events on focus loss. (#3575) +- Demo: Clarify usage of right-aligned items in Demo>Layout>Widgets Width. - Backends: OpenGL3: Use glGetString(GL_VERSION) query instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] diff --git a/docs/FAQ.md b/docs/FAQ.md index d474607c..f47015d4 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -188,14 +188,14 @@ Unique ID are used internally to track active widgets and occasionally associate Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element. - Unique ID are often derived from a string label and at minimum scoped within their host window: -```c +```cpp Begin("MyWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK") Button("Cancel"); // Label = "Cancel", ID = hash of ("MyWindow", "Cancel") End(); ``` - Other elements such as tree nodes, etc. also pushes to the ID stack: -```c +```cpp Begin("MyWindow"); if (TreeNode("MyTreeNode")) { @@ -205,7 +205,7 @@ if (TreeNode("MyTreeNode")) End(); ``` - Two items labeled "OK" in different windows or different tree locations won't collide: -``` +```cpp Begin("MyFirstWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyFirstWindow", "OK") End(); @@ -217,7 +217,7 @@ End(); We used "..." above to signify whatever was already pushed to the ID stack previously: - If you have a same ID twice in the same location, you'll have a conflict: -```c +```cpp Button("OK"); Button("OK"); // ID collision! Interacting with either button will trigger the first one. ``` @@ -228,7 +228,7 @@ When passing a label you can optionally specify extra ID information within stri Use "##" to pass a complement to the ID that won't be visible to the end-user. This helps solving the simple collision cases when you know e.g. at compilation time which items are going to be created: -```c +```cpp Begin("MyWindow"); Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play") Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above @@ -236,15 +236,15 @@ Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo End(); ``` - If you want to completely hide the label, but still need an ID: -```c +```cpp Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox! ``` - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. For example you may want to include varying information in a window title bar, but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID: -```c +```cpp Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID") -Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even if the label looks different +Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same ID, different label sprintf(buf, "My game (%f FPS)###MyGame", fps); Begin(buf); // Variable title, ID = hash of "MyGame" @@ -256,7 +256,7 @@ creating many UI elements programmatically. You can push a pointer, a string or an integer value into the ID stack. Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack. At each level of the stack we store the seed used for items at this level of the ID stack. -```c +```cpp Begin("Window"); for (int i = 0; i < 100; i++) { @@ -281,7 +281,7 @@ for (int i = 0; i < 100; i++) End(); ``` - You can stack multiple prefixes into the ID stack: -```c +```cpp Button("Click"); // Label = "Click", ID = hash of (..., "Click") PushID("node"); Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") @@ -291,7 +291,7 @@ PushID("node"); PopID(); ``` - Tree nodes implicitly creates a scope for you by calling PushID(). -```c +```cpp Button("Click"); // Label = "Click", ID = hash of (..., "Click") if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag) { @@ -328,22 +328,22 @@ Long explanation: ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice. Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function. - In the [examples/](https://github.com/ocornut/imgui/tree/master/examples) backends, for each graphics API we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: -``` +```cpp OpenGL: - ImTextureID = GLuint - See ImGui_ImplOpenGL3_RenderDrawData() function in imgui_impl_opengl3.cpp ``` -``` +```cpp DirectX9: - ImTextureID = LPDIRECT3DTEXTURE9 - See ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp ``` -``` +```cpp DirectX11: - ImTextureID = ID3D11ShaderResourceView* - See ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp ``` -``` +```cpp DirectX12: - ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE - See ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp @@ -429,8 +429,7 @@ provide similar or better string helpers. ### Q: How can I display custom shapes? (using low-level ImDrawList API) - You can use the low-level `ImDrawList` api to render shapes within a window. - -``` +```cpp ImGui::Begin("My shapes"); ImDrawList* draw_list = ImGui::GetWindowDrawList(); @@ -466,9 +465,9 @@ ImGui::End(); ### Q: How should I handle DPI in my application? -The short answer is: obtain the desired DPI scale, load a suitable font resized with that scale (always round down font size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. +The short answer is: obtain the desired DPI scale, load your fonts resized with that scale (always round down fonts size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. -Your application may want to detect DPI change and reload the font and reset style being frames. +Your application may want to detect DPI change and reload the fonts and reset style between frames. Your ui code should avoid using hardcoded constants for size and positioning. Prefer to express values as multiple of reference values such as `ImGui::GetFontSize()` or `ImGui::GetFrameHeight()`. So e.g. instead of seeing a hardcoded height of 500 for a given item/window, you may want to use `30*ImGui::GetFontSize()` instead. @@ -507,7 +506,7 @@ backslash \ within a string literal, you need to write it double backslash "\\": ```cpp io.Fonts->AddFontFromFileTTF("MyFolder\MyFont.ttf", size); // WRONG (you are escaping the M here!) -io.Fonts->AddFontFromFileTTF("MyFolder\\MyFont.ttf", size; // CORRECT +io.Fonts->AddFontFromFileTTF("MyFolder\\MyFont.ttf", size; // CORRECT (Windows only) io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT ``` @@ -644,7 +643,7 @@ There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/ci # Q&A: Community ### Q: How can I help? -- Businesses: please reach out to `contact AT dearimgui.org` if you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project. +- Businesses: please reach out to `contact AT dearimgui.com` if you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project. - Individuals: you can support continued maintenance and development via PayPal donations. See [README](https://github.com/ocornut/imgui/blob/master/docs/README.md). - If you are experienced with Dear ImGui and C++, look at the [GitHub Issues](https://github.com/ocornut/imgui/issues), look at the [Wiki](https://github.com/ocornut/imgui/wiki), read [docs/TODO.txt](https://github.com/ocornut/imgui/blob/master/docs/TODO.txt) and see how you want to help and can help! - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. diff --git a/docs/FONTS.md b/docs/FONTS.md index 96573402..54b7c295 100644 --- a/docs/FONTS.md +++ b/docs/FONTS.md @@ -75,7 +75,7 @@ ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); // Select font at runtime -ImGui::Text("Hello"); // use the default font (which is the first loaded font) +ImGui::Text("Hello"); // use the default font (which is the first loaded font) ImGui::PushFont(font2); ImGui::Text("Hello with another font"); ImGui::PopFont(); @@ -311,39 +311,31 @@ In some situations, you may also use `/` path separator under Windows. Some fonts files are available in the `misc/fonts/` folder: -``` -Roboto-Medium.ttf - Apache License 2.0 - by Christian Robetson - https://fonts.google.com/specimen/Roboto - -Cousine-Regular.ttf - by Steve Matteson - Digitized data copyright (c) 2010 Google Corporation. - Licensed under the SIL Open Font License, Version 1.1 - https://fonts.google.com/specimen/Cousine - -DroidSans.ttf - Copyright (c) Steve Matteson - Apache License, version 2.0 - https://www.fontsquirrel.com/fonts/droid-sans - -ProggyClean.ttf - Copyright (c) 2004, 2005 Tristan Grimmer - MIT License - recommended loading setting: Size = 13.0, GlyphOffset.y = +1 - http://www.proggyfonts.net/ - -ProggyTiny.ttf - Copyright (c) 2004, 2005 Tristan Grimmer - MIT License - recommended loading setting: Size = 10.0, GlyphOffset.y = +1 - http://www.proggyfonts.net/ - -Karla-Regular.ttf - Copyright (c) 2012, Jonathan Pinhorn - SIL OPEN FONT LICENSE Version 1.1 -``` +**Roboto-Medium.ttf**, by Christian Robetson +
Apache License 2.0 +
https://fonts.google.com/specimen/Roboto + +**Cousine-Regular.ttf**, by Steve Matteson +
Digitized data copyright (c) 2010 Google Corporation. +
Licensed under the SIL Open Font License, Version 1.1 +
https://fonts.google.com/specimen/Cousine + +**DroidSans.ttf**, by Steve Matteson +
Apache License 2.0 +
https://www.fontsquirrel.com/fonts/droid-sans + +**ProggyClean.ttf**, by Tristan Grimmer +
MIT License +
(recommended loading setting: Size = 13.0, GlyphOffset.y = +1) +
http://www.proggyfonts.net/ + +**ProggyTiny.ttf**, by Tristan Grimmer +
MIT License +
(recommended loading setting: Size = 10.0, GlyphOffset.y = +1) +
http://www.proggyfonts.net/ + +**Karla-Regular.ttf**, by Jonathan Pinhorn +
SIL OPEN FONT LICENSE Version 1.1 ##### [Return to Index](#index) diff --git a/imgui.cpp b/imgui.cpp index d973b451..34c0da3c 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3410,7 +3410,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() if (root_window != NULL && !is_closed_popup) { - StartMouseMovingWindow(g.HoveredWindow); + StartMouseMovingWindow(g.HoveredWindow); //-V595 // Cancel moving if clicked outside of title bar if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 045ae509..71fe735f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -308,8 +308,8 @@ void ImGui::ShowDemoWindow(bool* p_open) // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. - // e.g. Use 2/3 of the space for widgets and 1/3 for labels (default) - //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); + // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align) + //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. ImGui::PushItemWidth(ImGui::GetFontSize() * -12); @@ -476,6 +476,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ShowDemoWindowMisc(); // End of ShowDemoWindow() + ImGui::PopItemWidth(); ImGui::End(); } @@ -2170,34 +2171,69 @@ static void ShowDemoWindowLayout() // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. static float f = 0.0f; + static bool show_indented_items = true; + ImGui::Checkbox("Show indented items", &show_indented_items); + ImGui::Text("SetNextItemWidth/PushItemWidth(100)"); ImGui::SameLine(); HelpMarker("Fixed width."); - ImGui::SetNextItemWidth(100); - ImGui::DragFloat("float##1", &f); + ImGui::PushItemWidth(100); + ImGui::DragFloat("float##1b", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##1b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); - ImGui::Text("SetNextItemWidth/PushItemWidth(GetWindowWidth() * 0.5f)"); - ImGui::SameLine(); HelpMarker("Half of window width."); - ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.5f); - ImGui::DragFloat("float##2", &f); + ImGui::Text("SetNextItemWidth/PushItemWidth(-100)"); + ImGui::SameLine(); HelpMarker("Align to right edge minus 100"); + ImGui::PushItemWidth(-100); + ImGui::DragFloat("float##2a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##2b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)"); ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); - ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.5f); - ImGui::DragFloat("float##3", &f); + ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::DragFloat("float##3a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##3b", &f); + ImGui::Unindent(); + } + ImGui::PopItemWidth(); - ImGui::Text("SetNextItemWidth/PushItemWidth(-100)"); - ImGui::SameLine(); HelpMarker("Align to right edge minus 100"); - ImGui::SetNextItemWidth(-100); - ImGui::DragFloat("float##4", &f); + ImGui::Text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)"); + ImGui::SameLine(); HelpMarker("Align to right edge minus half"); + ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f); + ImGui::DragFloat("float##4a", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##4b", &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(-1)"); + ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)"); ImGui::SameLine(); HelpMarker("Align to right edge"); - ImGui::PushItemWidth(-1); + ImGui::PushItemWidth(-FLT_MIN); ImGui::DragFloat("##float5a", &f); - ImGui::DragFloat("##float5b", &f); - ImGui::DragFloat("##float5c", &f); + if (show_indented_items) + { + ImGui::Indent(); + ImGui::DragFloat("float (indented)##5b", &f); + ImGui::Unindent(); + } ImGui::PopItemWidth(); ImGui::TreePop(); From 9801c8c1c5f8757e8eed43592beb0a5e215c4291 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 26 Nov 2020 19:35:56 +0100 Subject: [PATCH 375/959] Texture-based thick lines: comment out dead code (amend b5bae978). (#3245) --- imgui_draw.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 306c296e..e226146f 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -778,14 +778,14 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 { // If we're using textures we only need to emit the left/right edge vertices ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness]; - if (fractional_thickness != 0.0f) + /*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false! { const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1]; tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; - } + }*/ ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y); ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w); for (int i = 0; i < points_count; i++) From ae3e2406ec9aab04dfddce80ebf5672e0a0b1486 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 30 Nov 2020 12:40:49 +0100 Subject: [PATCH 376/959] Misc tweaks/fixes (see details). Combo: ultra minor fix for popup positioning policy mismatch depending on ImGuiComboFlags_PopupAlignLeft flag. Made ImHashXXX functions return ImGuiID. IsWindowNavFocusable use !WasActive.. it worked because it was only called in NewFrame()->NavUpdate() before the transition loop + EndFrame() only. Fix unused variable warning. --- imgui.cpp | 7 ++++--- imgui.h | 4 ++-- imgui_internal.h | 6 +++--- imgui_widgets.cpp | 8 ++++++-- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 34c0da3c..dd147223 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1433,7 +1433,7 @@ static const ImU32 GCrc32LookupTable[256] = // Known size hash // It is ok to call ImHashData on a string with known length but the ### operator won't be supported. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. -ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed) +ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed) { ImU32 crc = ~seed; const unsigned char* data = (const unsigned char*)data_p; @@ -1449,7 +1449,7 @@ ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed) // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build) // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. -ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed) +ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed) { seed = ~seed; ImU32 crc = seed; @@ -6405,7 +6405,7 @@ bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) // If you want a window to never be focused, you may use the e.g. NoInputs flag. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) { - return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); + return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); } float ImGui::GetWindowWidth() @@ -7002,6 +7002,7 @@ void ImGuiStackSizes::CompareWithCurrentState() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + IM_UNUSED(window); // Window stacks // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) diff --git a/imgui.h b/imgui.h index 6d2b54cd..1815db42 100644 --- a/imgui.h +++ b/imgui.h @@ -371,9 +371,9 @@ namespace ImGui IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied // Parameters stacks (current window) - IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side). 0.0f = default to ~2/3 of windows width, + IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). 0.0f = default to ~2/3 of windows width, IMGUI_API void PopItemWidth(); - IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) + IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side) IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); diff --git a/imgui_internal.h b/imgui_internal.h index f3ab30e7..33cc991e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -250,10 +250,10 @@ namespace ImStb //----------------------------------------------------------------------------- // Helpers: Hashing -IMGUI_API ImU32 ImHashData(const void* data, size_t data_size, ImU32 seed = 0); -IMGUI_API ImU32 ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0); +IMGUI_API ImGuiID ImHashData(const void* data, size_t data_size, ImU32 seed = 0); +IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -static inline ImU32 ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68] +static inline ImGuiID ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68] #endif // Helpers: Sorting diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 08a741fb..2ecb5656 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1590,13 +1590,17 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF char name[16]; ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth - // Peak into expected window size so we can position it + // Position the window given a custom constraint (peak into expected window size so we can position it) + // This might be easier to express with an hypothetical SetNextWindowPosConstraints() function. if (ImGuiWindow* popup_window = FindWindowByName(name)) if (popup_window->WasActive) { + // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us. ImVec2 size_expected = CalcWindowExpectedSize(popup_window); if (flags & ImGuiComboFlags_PopupAlignLeft) - popup_window->AutoPosLastDirection = ImGuiDir_Left; + popup_window->AutoPosLastDirection = ImGuiDir_Left; // "Below, Toward Left" + else + popup_window->AutoPosLastDirection = ImGuiDir_Down; // "Below, Toward Right (default)" ImRect r_outer = GetWindowAllowedExtentRect(popup_window); ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox); SetNextWindowPos(pos); From d20f2bc90a4d1d1422c092baae252a0d909c4599 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 2 Dec 2020 11:23:56 +0100 Subject: [PATCH 377/959] Rename example_emscripten/ to example_emscripten_opengl3/ (#3632) --- .github/workflows/build.yml | 8 +++---- .gitignore | 2 +- docs/BACKENDS.md | 22 +++++++++---------- docs/CHANGELOG.txt | 3 ++- docs/EXAMPLES.md | 22 +++++++++---------- .../Makefile | 8 +++---- .../README.md | 4 ++-- .../main.cpp | 0 .../shell_minimal.html | 0 9 files changed, 35 insertions(+), 34 deletions(-) rename examples/{example_emscripten => example_emscripten_opengl3}/Makefile (95%) rename examples/{example_emscripten => example_emscripten_opengl3}/README.md (89%) rename examples/{example_emscripten => example_emscripten_opengl3}/main.cpp (100%) rename examples/{example_emscripten => example_emscripten_opengl3}/shell_minimal.html (100%) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index dca1be02..adec4998 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -49,7 +49,7 @@ jobs: shell: cmd run: | cd examples\example_null - call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" + call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" .\build_win32.bat /W4 - name: Build example_null (single file build) @@ -72,7 +72,7 @@ jobs: - name: Build example_null (as DLL) shell: cmd run: | - call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" + call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" echo #ifdef _EXPORT > example_single_file.cpp echo # define IMGUI_API __declspec(dllexport) >> example_single_file.cpp echo #else >> example_single_file.cpp @@ -393,12 +393,12 @@ jobs: emsdk-master/emsdk install latest emsdk-master/emsdk activate latest - - name: Build example_emscripten + - name: Build example_emscripten_opengl3 run: | pushd emsdk-master source ./emsdk_env.sh popd - make -C examples/example_emscripten + make -C examples/example_emscripten_opengl3 Discord-CI: runs-on: ubuntu-18.04 diff --git a/.gitignore b/.gitignore index 84014850..1ef7b007 100644 --- a/.gitignore +++ b/.gitignore @@ -34,7 +34,7 @@ xcuserdata examples/*.o.tmp examples/*.out.js examples/*.out.wasm -examples/example_emscripten/example_emscripten.* +examples/example_emscripten_opengl3/example_emscripten_opengl3.* ## JetBrains IDE artifacts .idea diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 87d54542..835bf94e 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -42,7 +42,7 @@ It is important to understand the difference between the core Dear ImGui library and backends which we are describing here (backends/ folder). - Some issues may only be backend or platform specific. -- You should be able to write backends for pretty much any platform and any 3D graphics API. +- You should be able to write backends for pretty much any platform and any 3D graphics API. e.g. you can get creative and use software rendering or render remotely on a different machine. @@ -75,7 +75,7 @@ List of high-level Frameworks Backends (combining Platform + Renderer): imgui_impl_marmalade.cpp Emscripten is also supported. -The [example_emscripten](https://github.com/ocornut/imgui/tree/master/examples/example_emscripten) app uses imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp, but other combos are possible. +The [example_emscripten_opengl3](https://github.com/ocornut/imgui/tree/master/examples/example_emscripten_opengl3) app uses imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp, but other combos are possible. ### Backends for third-party frameworks, graphics API or other languages @@ -129,32 +129,32 @@ If you are new to Dear ImGui, first try using the existing backends as-is. You will save lots of time integrating the library. You can LATER decide to rewrite yourself a custom backend if you really need to. In most situations, custom backends have less features and more bugs than the standard backends we provide. -If you want portability, you can use multiple backends and choose between them either at compile time -or at runtime. +If you want portability, you can use multiple backends and choose between them either at compile time +or at runtime. **Example A**: your engine is built over Windows + DirectX11 but you have your own high-level rendering system layered over DirectX11.
Suggestion: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. -Once it works, if you really need it you can replace the imgui_impl_dx11.cpp code with a +Once it works, if you really need it you can replace the imgui_impl_dx11.cpp code with a custom renderer using your own rendering functions, and keep using the standard Win32 code etc. **Example B**: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, Vulkan respectively.
Suggestion: use multiple generic backends! Once it works, if you really need it you can replace parts of backends with your own abstractions. -**Example C**: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch), +**Example C**: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch), and you have high-level systems everywhere.
Suggestion: try using a non-portable backend first (e.g. win32 + underlying graphics API) to get your desktop builds working first. This will get you running faster and get your acquainted with how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API. Also: -The [multi-viewports feature](https://github.com/ocornut/imgui/issues/1542) of the 'docking' branch allows -Dear ImGui windows to be seamlessly detached from the main application window. This is achieved using an -extra layer to the Platform and Renderer backends, which allows Dear ImGui to communicate platform-specific -requests such as: "create an additional OS window", "create a render context", "get the OS position of this +The [multi-viewports feature](https://github.com/ocornut/imgui/issues/1542) of the 'docking' branch allows +Dear ImGui windows to be seamlessly detached from the main application window. This is achieved using an +extra layer to the Platform and Renderer backends, which allows Dear ImGui to communicate platform-specific +requests such as: "create an additional OS window", "create a render context", "get the OS position of this window" etc. See 'ImGuiPlatformIO' for details. -Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult +Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult than supporting single-viewport. If you decide to use unmodified imgui_impl_XXXX.cpp files, you can automatically benefit from improvements and fixes related to viewports and platform windows without extra work on your side. diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index d335a07c..950e9ad0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -76,7 +76,7 @@ Other Changes: - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. - Metrics: Rebranded as "Dear ImGui Metrics/Debugger" to clarify its purpose. - Misc: Made the ItemFlags stack shared, so effectively the ButtonRepeat/AllowKeyboardFocus states - (and others exposed in internals such as PushItemFlag) are inherited by stacked Begin/End pairs, + (and others exposed in internals such as PushItemFlag) are inherited by stacked Begin/End pairs, vs previously a non-child stacked Begin() would reset those flags back to zero for the stacked window. - Misc: Replaced UTF-8 decoder with one based on branchless one by Christopher Wellons. [@rokups] Super minor fix handling incomplete UTF-8 contents: if input does not contain enough bytes, decoder @@ -93,6 +93,7 @@ Other Changes: - Backends: OSX: Fix keypad-enter key not working on MacOS. (#3554) [@rokups, @lfnoise] - Examples: Apple+Metal: Consolidated/simplified to get closer to other examples. (#3543) [@warrenm] - Examples: Apple+Metal: Forward events down so OS key combination like Cmd+Q can work. (#3554) [@rokups] +- Examples: Emscripten: Renamed example_emscripten/ to example_emscripten_opengl3/. (#3632) - CI: Fix testing for Windows DLL builds. (#3603, #3601) [@iboB] - Docs: Split examples/README.txt into docs/BACKENDS.md and docs/EXAMPLES.md improved them. - Docs: Consistently renamed all occurences of "binding" and "back-end" to "backend" in comments and docs. diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md index d318bd35..d6fac021 100644 --- a/docs/EXAMPLES.md +++ b/docs/EXAMPLES.md @@ -2,7 +2,7 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/EXAMP ## Dear ImGui: Examples -**The [examples/](https://github.com/ocornut/imgui/blob/master/examples) folder example applications (standalone, ready-to-build) for variety of +**The [examples/](https://github.com/ocornut/imgui/blob/master/examples) folder example applications (standalone, ready-to-build) for variety of platforms and graphics APIs.** They all use standard backends from the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder. You can find Windows binaries for some of those example applications at: @@ -13,7 +13,7 @@ You can find Windows binaries for some of those example applications at: Integration in a typical existing application, should take <20 lines when using standard backends. - At initialization: + At initialization: call ImGui::CreateContext() call ImGui_ImplXXXX_Init() for each backend. @@ -35,11 +35,11 @@ Example (using [backends/imgui_impl_win32.cpp](https://github.com/ocornut/imgui/ ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable some options - + // Initialize Platform + Renderer backends (here: using imgui_impl_win32.cpp + imgui_impl_dx11.cpp) ImGui_ImplWin32_Init(my_hwnd); ImGui_ImplDX11_Init(my_d3d_device, my_d3d_device_context); - + // Application main loop while (true) { @@ -47,10 +47,10 @@ Example (using [backends/imgui_impl_win32.cpp](https://github.com/ocornut/imgui/ ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); - + // Any application code here ImGui::Text("Hello, world!"); - + // End of frame: render Dear ImGui ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); @@ -68,7 +68,7 @@ Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui Please read the comments and instruction at the top of each file. Please read FAQ at http://www.dearimgui.org/faq -If you are using of the backend provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) +If you are using of the backend provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual Changelog, so if you want to update them later it will be easier to catch up with what changed. @@ -82,8 +82,8 @@ Allegro 5 example.
[example_apple_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_metal/)
OSX & iOS + Metal example.
= main.m + imgui_impl_osx.mm + imgui_impl_metal.mm
-It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. -(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. +It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. +(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) [example_apple_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_apple_opengl2/)
@@ -92,7 +92,7 @@ OSX + OpenGL2 example.
(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) -[example_emscripten/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten/)
+[example_emscripten_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten_opengl3/)
Emcripten + SDL2 + OpenGL3+/ES2/ES3 example.
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp
Note that other examples based on SDL or GLFW + OpenGL could easily be modified to work with Emscripten. @@ -220,7 +220,7 @@ to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated path and will feel smoother than the majority of contents rendered via regular graphics API (including, -but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane +but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane as the mouse, that disconnect may be jarring to particularly sensitive users. You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a diff --git a/examples/example_emscripten/Makefile b/examples/example_emscripten_opengl3/Makefile similarity index 95% rename from examples/example_emscripten/Makefile rename to examples/example_emscripten_opengl3/Makefile index 967d61fb..06baf499 100644 --- a/examples/example_emscripten/Makefile +++ b/examples/example_emscripten_opengl3/Makefile @@ -7,15 +7,15 @@ # (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead) # # Running `make` will produce three files: -# - example_emscripten.html -# - example_emscripten.js -# - example_emscripten.wasm +# - example_emscripten_opengl3.html +# - example_emscripten_opengl3.js +# - example_emscripten_opengl3.wasm # # All three are needed to run the demo. CC = emcc CXX = em++ -EXE = example_emscripten.html +EXE = example_emscripten_opengl3.html IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten_opengl3/README.md similarity index 89% rename from examples/example_emscripten/README.md rename to examples/example_emscripten_opengl3/README.md index 01a4e35e..b6b8737d 100644 --- a/examples/example_emscripten/README.md +++ b/examples/example_emscripten_opengl3/README.md @@ -4,14 +4,14 @@ - You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions - You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. - Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools. -- Then build using `make` while in the `example_emscripten/` directory. +- Then build using `make` while in the `example_emscripten_opengl3/` directory. ## How to Run To run on a local machine: - Generally you may need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ -- Emscripten SDK has a handy `emrun` command: `emrun example_emscripten.html` which will spawn a temporary local webserver. See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. +- Emscripten SDK has a handy `emrun` command: `emrun example_emscripten_opengl3.html` which will spawn a temporary local webserver. See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. - Otherwise you may use Python builtin webserver: `python -m http.server` in Python 3 or `python -m SimpleHTTPServer` in Python 2. After doing that, you can visit http://localhost:8000/. ## Obsolete features: diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten_opengl3/main.cpp similarity index 100% rename from examples/example_emscripten/main.cpp rename to examples/example_emscripten_opengl3/main.cpp diff --git a/examples/example_emscripten/shell_minimal.html b/examples/example_emscripten_opengl3/shell_minimal.html similarity index 100% rename from examples/example_emscripten/shell_minimal.html rename to examples/example_emscripten_opengl3/shell_minimal.html From 2afdfa602fb0dd5ff1502910fede80b8779ebc2d Mon Sep 17 00:00:00 2001 From: vaiorabbit Date: Mon, 23 Nov 2020 17:19:56 +0900 Subject: [PATCH 378/959] Rebuild ImFontAtlas::GetGlyphRangesJapanese offset table (#3627) - GetGlyphRangesJapanese now supports - 2136 'Joyo (meaning "for regular use" or "for common use")' Kanji - 863 'Jinmeiyo" (meaning "for personal name")' Kanji --- docs/CHANGELOG.txt | 3 ++ imgui.h | 2 +- imgui_draw.cpp | 101 +++++++++++++++++++++++++++++---------------- 3 files changed, 70 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 950e9ad0..dfee0bcf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -75,6 +75,9 @@ Other Changes: feedback and control of keyboard/gamepad navigation highlight and mouse hover disable flag. (#787, #2048) - Metrics: Fixed mishandling of ImDrawCmd::VtxOffset in wireframe mesh renderer. - Metrics: Rebranded as "Dear ImGui Metrics/Debugger" to clarify its purpose. +- Fonts: Updated GetGlyphRangesJapanese() to include a larger 2999 ideograms selection of Joyo/Jinmeiyo + kanjis, from the previous 1946 ideograms selection. This will consume a some more memory but be generally + much more fitting for Japanese display, until we switch to a more dynamic atlas. (#3627) [@vaiorabbit] - Misc: Made the ItemFlags stack shared, so effectively the ButtonRepeat/AllowKeyboardFocus states (and others exposed in internals such as PushItemFlag) are inherited by stacked Begin/End pairs, vs previously a non-child stacked Begin() would reset those flags back to zero for the stacked window. diff --git a/imgui.h b/imgui.h index 1815db42..d1d42b3c 100644 --- a/imgui.h +++ b/imgui.h @@ -2343,7 +2343,7 @@ struct ImFontAtlas // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters - IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e226146f..93eb23f2 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -2616,45 +2616,76 @@ const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon() const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() { - // 1946 common ideograms code points for Japanese - // Sourced from http://theinstructionlimit.com/common-kanji-character-ranges-for-xna-spritefont-rendering - // FIXME: Source a list of the revised 2136 Joyo Kanji list from 2010 and rebuild this. + // 2999 ideograms code points for Japanese + // - 2136 Joyo (meaning "for regular use" or "for common use") Kanji code points + // - 863 Jinmeiyo (meaning "for personal name") Kanji code points + // - Sourced from the character information database of the Information-technology Promotion Agency, Japan + // - https://mojikiban.ipa.go.jp/mji/ + // - Available under the terms of the Creative Commons Attribution-ShareAlike 2.1 Japan (CC BY-SA 2.1 JP). + // - https://creativecommons.org/licenses/by-sa/2.1/jp/deed.en + // - https://creativecommons.org/licenses/by-sa/2.1/jp/legalcode + // - You can generate this code by the script at: + // - https://github.com/vaiorabbit/everyday_use_kanji + // - References: + // - List of Joyo Kanji + // - (Official list by the Agency for Cultural Affairs) https://www.bunka.go.jp/kokugo_nihongo/sisaku/joho/joho/kakuki/14/tosin02/index.html + // - (Wikipedia) https://en.wikipedia.org/wiki/List_of_j%C5%8Dy%C5%8D_kanji + // - List of Jinmeiyo Kanji + // - (Official list by the Ministry of Justice) http://www.moj.go.jp/MINJI/minji86.html + // - (Wikipedia) https://en.wikipedia.org/wiki/Jinmeiy%C5%8D_kanji + // - Missing 1 Joyo Kanji: U+20B9F (Kun'yomi: Shikaru, On'yomi: Shitsu,shichi), see https://github.com/ocornut/imgui/pull/3627 for details. // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters. // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.) static const short accumulative_offsets_from_0x4E00[] = { - 0,1,2,4,1,1,1,1,2,1,6,2,2,1,8,5,7,11,1,2,10,10,8,2,4,20,2,11,8,2,1,2,1,6,2,1,7,5,3,7,1,1,13,7,9,1,4,6,1,2,1,10,1,1,9,2,2,4,5,6,14,1,1,9,3,18, - 5,4,2,2,10,7,1,1,1,3,2,4,3,23,2,10,12,2,14,2,4,13,1,6,10,3,1,7,13,6,4,13,5,2,3,17,2,2,5,7,6,4,1,7,14,16,6,13,9,15,1,1,7,16,4,7,1,19,9,2,7,15, - 2,6,5,13,25,4,14,13,11,25,1,1,1,2,1,2,2,3,10,11,3,3,1,1,4,4,2,1,4,9,1,4,3,5,5,2,7,12,11,15,7,16,4,5,16,2,1,1,6,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1, - 2,1,12,3,3,9,5,8,1,11,1,2,3,18,20,4,1,3,6,1,7,3,5,5,7,2,2,12,3,1,4,2,3,2,3,11,8,7,4,17,1,9,25,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,6,16,1,2,1,1,3,12, - 20,2,5,20,8,7,6,2,1,1,1,1,6,2,1,2,10,1,1,6,1,3,1,2,1,4,1,12,4,1,3,1,1,1,1,1,10,4,7,5,13,1,15,1,1,30,11,9,1,15,38,14,1,32,17,20,1,9,31,2,21,9, - 4,49,22,2,1,13,1,11,45,35,43,55,12,19,83,1,3,2,3,13,2,1,7,3,18,3,13,8,1,8,18,5,3,7,25,24,9,24,40,3,17,24,2,1,6,2,3,16,15,6,7,3,12,1,9,7,3,3, - 3,15,21,5,16,4,5,12,11,11,3,6,3,2,31,3,2,1,1,23,6,6,1,4,2,6,5,2,1,1,3,3,22,2,6,2,3,17,3,2,4,5,1,9,5,1,1,6,15,12,3,17,2,14,2,8,1,23,16,4,2,23, - 8,15,23,20,12,25,19,47,11,21,65,46,4,3,1,5,6,1,2,5,26,2,1,1,3,11,1,1,1,2,1,2,3,1,1,10,2,3,1,1,1,3,6,3,2,2,6,6,9,2,2,2,6,2,5,10,2,4,1,2,1,2,2, - 3,1,1,3,1,2,9,23,9,2,1,1,1,1,5,3,2,1,10,9,6,1,10,2,31,25,3,7,5,40,1,15,6,17,7,27,180,1,3,2,2,1,1,1,6,3,10,7,1,3,6,17,8,6,2,2,1,3,5,5,8,16,14, - 15,1,1,4,1,2,1,1,1,3,2,7,5,6,2,5,10,1,4,2,9,1,1,11,6,1,44,1,3,7,9,5,1,3,1,1,10,7,1,10,4,2,7,21,15,7,2,5,1,8,3,4,1,3,1,6,1,4,2,1,4,10,8,1,4,5, - 1,5,10,2,7,1,10,1,1,3,4,11,10,29,4,7,3,5,2,3,33,5,2,19,3,1,4,2,6,31,11,1,3,3,3,1,8,10,9,12,11,12,8,3,14,8,6,11,1,4,41,3,1,2,7,13,1,5,6,2,6,12, - 12,22,5,9,4,8,9,9,34,6,24,1,1,20,9,9,3,4,1,7,2,2,2,6,2,28,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,8,8,3,2,1,5,1,2,2,3,1,11,11,7,3,6,10,8,6,16,16, - 22,7,12,6,21,5,4,6,6,3,6,1,3,2,1,2,8,29,1,10,1,6,13,6,6,19,31,1,13,4,4,22,17,26,33,10,4,15,12,25,6,67,10,2,3,1,6,10,2,6,2,9,1,9,4,4,1,2,16,2, - 5,9,2,3,8,1,8,3,9,4,8,6,4,8,11,3,2,1,1,3,26,1,7,5,1,11,1,5,3,5,2,13,6,39,5,1,5,2,11,6,10,5,1,15,5,3,6,19,21,22,2,4,1,6,1,8,1,4,8,2,4,2,2,9,2, - 1,1,1,4,3,6,3,12,7,1,14,2,4,10,2,13,1,17,7,3,2,1,3,2,13,7,14,12,3,1,29,2,8,9,15,14,9,14,1,3,1,6,5,9,11,3,38,43,20,7,7,8,5,15,12,19,15,81,8,7, - 1,5,73,13,37,28,8,8,1,15,18,20,165,28,1,6,11,8,4,14,7,15,1,3,3,6,4,1,7,14,1,1,11,30,1,5,1,4,14,1,4,2,7,52,2,6,29,3,1,9,1,21,3,5,1,26,3,11,14, - 11,1,17,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,7,7,5,17,3,3,3,1,23,10,4,4,6,3,1,16,17,22,3,10,21,16,16,6,4,10,2,1,1,2,8,8,6,5,3,3,3,39,25, - 15,1,1,16,6,7,25,15,6,6,12,1,22,13,1,4,9,5,12,2,9,1,12,28,8,3,5,10,22,60,1,2,40,4,61,63,4,1,13,12,1,4,31,12,1,14,89,5,16,6,29,14,2,5,49,18,18, - 5,29,33,47,1,17,1,19,12,2,9,7,39,12,3,7,12,39,3,1,46,4,12,3,8,9,5,31,15,18,3,2,2,66,19,13,17,5,3,46,124,13,57,34,2,5,4,5,8,1,1,1,4,3,1,17,5, - 3,5,3,1,8,5,6,3,27,3,26,7,12,7,2,17,3,7,18,78,16,4,36,1,2,1,6,2,1,39,17,7,4,13,4,4,4,1,10,4,2,4,6,3,10,1,19,1,26,2,4,33,2,73,47,7,3,8,2,4,15, - 18,1,29,2,41,14,1,21,16,41,7,39,25,13,44,2,2,10,1,13,7,1,7,3,5,20,4,8,2,49,1,10,6,1,6,7,10,7,11,16,3,12,20,4,10,3,1,2,11,2,28,9,2,4,7,2,15,1, - 27,1,28,17,4,5,10,7,3,24,10,11,6,26,3,2,7,2,2,49,16,10,16,15,4,5,27,61,30,14,38,22,2,7,5,1,3,12,23,24,17,17,3,3,2,4,1,6,2,7,5,1,1,5,1,1,9,4, - 1,3,6,1,8,2,8,4,14,3,5,11,4,1,3,32,1,19,4,1,13,11,5,2,1,8,6,8,1,6,5,13,3,23,11,5,3,16,3,9,10,1,24,3,198,52,4,2,2,5,14,5,4,22,5,20,4,11,6,41, - 1,5,2,2,11,5,2,28,35,8,22,3,18,3,10,7,5,3,4,1,5,3,8,9,3,6,2,16,22,4,5,5,3,3,18,23,2,6,23,5,27,8,1,33,2,12,43,16,5,2,3,6,1,20,4,2,9,7,1,11,2, - 10,3,14,31,9,3,25,18,20,2,5,5,26,14,1,11,17,12,40,19,9,6,31,83,2,7,9,19,78,12,14,21,76,12,113,79,34,4,1,1,61,18,85,10,2,2,13,31,11,50,6,33,159, - 179,6,6,7,4,4,2,4,2,5,8,7,20,32,22,1,3,10,6,7,28,5,10,9,2,77,19,13,2,5,1,4,4,7,4,13,3,9,31,17,3,26,2,6,6,5,4,1,7,11,3,4,2,1,6,2,20,4,1,9,2,6, - 3,7,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,5,13,8,4,11,23,1,10,6,2,1,3,21,2,2,4,24,31,4,10,10,2,5,192,15,4,16,7,9,51,1,2,1,1,5,1,1,2,1,3,5,3,1,3,4,1, - 3,1,3,3,9,8,1,2,2,2,4,4,18,12,92,2,10,4,3,14,5,25,16,42,4,14,4,2,21,5,126,30,31,2,1,5,13,3,22,5,6,6,20,12,1,14,12,87,3,19,1,8,2,9,9,3,3,23,2, - 3,7,6,3,1,2,3,9,1,3,1,6,3,2,1,3,11,3,1,6,10,3,2,3,1,2,1,5,1,1,11,3,6,4,1,7,2,1,2,5,5,34,4,14,18,4,19,7,5,8,2,6,79,1,5,2,14,8,2,9,2,1,36,28,16, - 4,1,1,1,2,12,6,42,39,16,23,7,15,15,3,2,12,7,21,64,6,9,28,8,12,3,3,41,59,24,51,55,57,294,9,9,2,6,2,15,1,2,13,38,90,9,9,9,3,11,7,1,1,1,5,6,3,2, - 1,2,2,3,8,1,4,4,1,5,7,1,4,3,20,4,9,1,1,1,5,5,17,1,5,2,6,2,4,1,4,5,7,3,18,11,11,32,7,5,4,7,11,127,8,4,3,3,1,10,1,1,6,21,14,1,16,1,7,1,3,6,9,65, - 51,4,3,13,3,10,1,1,12,9,21,110,3,19,24,1,1,10,62,4,1,29,42,78,28,20,18,82,6,3,15,6,84,58,253,15,155,264,15,21,9,14,7,58,40,39, + 0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1, + 1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3, + 2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8, + 2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5, + 2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1, + 1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30, + 2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3, + 13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4, + 5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14, + 2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1, + 1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1, + 7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1, + 1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1, + 6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2, + 10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7, + 2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5, + 3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1, + 6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7, + 4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2, + 4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5, + 1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6, + 12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2, + 1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16, + 22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11, + 2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18, + 18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9, + 14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3, + 1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6, + 40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1, + 12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8, + 2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1, + 1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10, + 1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5, + 3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2, + 14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5, + 12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1, + 2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5, + 1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4, + 3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7, + 2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5, + 13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13, + 18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21, + 37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1, + 5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38, + 32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4, + 1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4, + 4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1, + 3,2,1,1,1,1,2,1,1, }; static ImWchar base_ranges[] = // not zero-terminated { From 998d7303b1a3a0ae57b4599698b0c53e51be06cb Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 3 Dec 2020 15:14:32 +0100 Subject: [PATCH 379/959] Log/Capture: fix capture to work on clipped child windows. + Tweak ErrorCheckEndFrameRecover() to use local window pointer. --- docs/CHANGELOG.txt | 1 + imgui.cpp | 23 +++++++++++++---------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index dfee0bcf..392497e2 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -78,6 +78,7 @@ Other Changes: - Fonts: Updated GetGlyphRangesJapanese() to include a larger 2999 ideograms selection of Joyo/Jinmeiyo kanjis, from the previous 1946 ideograms selection. This will consume a some more memory but be generally much more fitting for Japanese display, until we switch to a more dynamic atlas. (#3627) [@vaiorabbit] +- Log/Capture: fix capture to work on clipped child windows. - Misc: Made the ItemFlags stack shared, so effectively the ButtonRepeat/AllowKeyboardFocus states (and others exposed in internals such as PushItemFlag) are inherited by stacked Begin/End pairs, vs previously a non-child stacked Begin() would reset those flags back to zero for the stacked window. diff --git a/imgui.cpp b/imgui.cpp index dd147223..6fdb3b95 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -6044,9 +6044,10 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); - if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) - if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) - window->HiddenFramesCanSkipItems = 1; + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow?? + if (!g.LogEnabled) + if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) + window->HiddenFramesCanSkipItems = 1; // Hide along with parent or if parent is collapsed if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) @@ -6930,37 +6931,38 @@ void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, voi } #endif ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(window != NULL); while (g.CurrentTabBar != NULL) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name); EndTabBar(); } - while (g.CurrentWindow->DC.TreeDepth > 0) //-V1044 + while (window->DC.TreeDepth > 0) { if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name); TreePop(); } - while (g.GroupStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfGroupStack) //-V1044 + while (g.GroupStack.Size > window->DC.StackSizesOnBegin.SizeOfGroupStack) { if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name); EndGroup(); } - while (g.CurrentWindow->IDStack.Size > 1) //-V1044 + while (window->IDStack.Size > 1) { if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name); PopID(); } - while (g.ColorStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfColorStack) //-V1044 + while (g.ColorStack.Size > window->DC.StackSizesOnBegin.SizeOfColorStack) { if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col)); PopStyleColor(); } - while (g.StyleVarStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfStyleVarStack) //-V1044 + while (g.StyleVarStack.Size > window->DC.StackSizesOnBegin.SizeOfStyleVarStack) { if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name); PopStyleVar(); } - while (g.FocusScopeStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfFocusScopeStack) //-V1044 + while (g.FocusScopeStack.Size > window->DC.StackSizesOnBegin.SizeOfFocusScopeStack) { if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name); PopFocusScope(); @@ -6970,7 +6972,8 @@ void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, voi IM_ASSERT(g.CurrentWindow->IsFallbackWindow); break; } - if (g.CurrentWindow->Flags & ImGuiWindowFlags_ChildWindow) + IM_ASSERT(window == g.CurrentWindow); + if (window->Flags & ImGuiWindowFlags_ChildWindow) { if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name); EndChild(); From 657589ab47b31e66804c71fbcdaf0f72e8e4f146 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 4 Dec 2020 11:29:53 +0100 Subject: [PATCH 380/959] Backends: Vulkan+Viewports: fixed build, removed extraneous pipeline creation (770c9953, e8447dea, 6a0e85c5) (#3459, #3579) --- backends/imgui_impl_vulkan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index e0e4cc4c..64c762f9 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -1285,7 +1285,7 @@ void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevic { (void)instance; ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); - ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline); + //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, g_VulkanInitInfo.Subpass); ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); } From f9b873662baac2388a4ca78c967e53eb5d83d2a1 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 4 Dec 2020 11:48:17 +0100 Subject: [PATCH 381/959] Backends: Win32: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed. GetClientRect() fails on closed hwnd which left the rectangle uninitialized and copied to DisplaySize. Ensure it is zero + similar failsafe in io.WantSetMousePos path. --- backends/imgui_impl_win32.cpp | 9 +++++---- docs/CHANGELOG.txt | 1 + 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/backends/imgui_impl_win32.cpp b/backends/imgui_impl_win32.cpp index 130f6730..f73d11e8 100644 --- a/backends/imgui_impl_win32.cpp +++ b/backends/imgui_impl_win32.cpp @@ -32,6 +32,7 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed. // 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs) // 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. // 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT. @@ -153,8 +154,8 @@ static void ImGui_ImplWin32_UpdateMousePos() if (io.WantSetMousePos) { POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y }; - ::ClientToScreen(g_hWnd, &pos); - ::SetCursorPos(pos.x, pos.y); + if (::ClientToScreen(g_hWnd, &pos)) + ::SetCursorPos(pos.x, pos.y); } // Set mouse position @@ -221,12 +222,12 @@ void ImGui_ImplWin32_NewFrame() IM_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) - RECT rect; + RECT rect = { 0, 0, 0, 0 }; ::GetClientRect(g_hWnd, &rect); io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Setup time step - INT64 current_time; + INT64 current_time = 0; ::QueryPerformanceCounter((LARGE_INTEGER*)¤t_time); io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond; g_Time = current_time; diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 392497e2..7ca42c4b 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -94,6 +94,7 @@ Other Changes: when the later returns zero (e.g. Desktop GL 2.x). (#3530) [@xndcn] - Backends: OpenGL3: Backup and restore GL_PRIMITIVE_RESTART state. (#3544) [@Xipiryon] - Backends: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation. (@3579) [@bdero] +- Backends: Win32: Fix setting of io.DisplaySize to invalid/uninitialized data after hwnd has been closed. - Backends: OSX: Fix keypad-enter key not working on MacOS. (#3554) [@rokups, @lfnoise] - Examples: Apple+Metal: Consolidated/simplified to get closer to other examples. (#3543) [@warrenm] - Examples: Apple+Metal: Forward events down so OS key combination like Cmd+Q can work. (#3554) [@rokups] From 9c8671e7b09fe8b11b418841e9baf81c9e2d46de Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 7 Oct 2020 12:04:28 +0200 Subject: [PATCH 382/959] Tables: Add empty file, skeleton. --- docs/CHANGELOG.txt | 1 + .../example_allegro5/example_allegro5.vcxproj | 1 + .../example_allegro5.vcxproj.filters | 3 + .../project.pbxproj | 15 ++-- .../project.pbxproj | 4 + examples/example_emscripten_opengl3/Makefile | 2 +- examples/example_glfw_metal/Makefile | 2 +- examples/example_glfw_opengl2/Makefile | 2 +- .../example_glfw_opengl2.vcxproj | 1 + .../example_glfw_opengl2.vcxproj.filters | 3 + examples/example_glfw_opengl3/Makefile | 2 +- .../example_glfw_opengl3.vcxproj | 1 + .../example_glfw_opengl3.vcxproj.filters | 3 + examples/example_glfw_vulkan/CMakeLists.txt | 2 +- .../example_glfw_vulkan.vcxproj | 1 + .../example_glfw_vulkan.vcxproj.filters | 3 + examples/example_glut_opengl2/Makefile | 2 +- .../example_glut_opengl2.vcxproj | 1 + .../example_glut_opengl2.vcxproj.filters | 3 + .../example_marmalade/marmalade_example.mkb | 1 + examples/example_null/Makefile | 2 +- .../example_sdl_directx11.vcxproj | 1 + .../example_sdl_directx11.vcxproj.filters | 3 + examples/example_sdl_metal/Makefile | 2 +- examples/example_sdl_opengl2/Makefile | 2 +- .../example_sdl_opengl2.vcxproj | 1 + .../example_sdl_opengl2.vcxproj.filters | 3 + examples/example_sdl_opengl3/Makefile | 2 +- .../example_sdl_opengl3.vcxproj | 3 +- .../example_sdl_opengl3.vcxproj.filters | 3 + .../example_sdl_vulkan.vcxproj | 3 +- .../example_win32_directx10.vcxproj | 3 +- .../example_win32_directx10.vcxproj.filters | 5 +- .../example_win32_directx11.vcxproj | 1 + .../example_win32_directx11.vcxproj.filters | 3 + .../example_win32_directx12.vcxproj | 3 +- .../example_win32_directx12.vcxproj.filters | 5 +- .../example_win32_directx9.vcxproj | 3 +- .../example_win32_directx9.vcxproj.filters | 5 +- imgui.cpp | 1 + imgui_tables.cpp | 73 +++++++++++++++++++ misc/single_file/imgui_single_file.h | 1 + 42 files changed, 158 insertions(+), 23 deletions(-) create mode 100644 imgui_tables.cpp diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 7ca42c4b..6b92eecf 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -37,6 +37,7 @@ HOW TO UPDATE? Breaking Changes: +- Added imgui_tables.cpp file! Manually constructed project files will need the new file added! - Backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. (#3513) - Removed redirecting functions/enums names that were marked obsolete in 1.60 (April 2017): - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend diff --git a/examples/example_allegro5/example_allegro5.vcxproj b/examples/example_allegro5/example_allegro5.vcxproj index d50318a9..c6c524aa 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj +++ b/examples/example_allegro5/example_allegro5.vcxproj @@ -158,6 +158,7 @@ + diff --git a/examples/example_allegro5/example_allegro5.vcxproj.filters b/examples/example_allegro5/example_allegro5.vcxproj.filters index 9abb67e7..00873a22 100644 --- a/examples/example_allegro5/example_allegro5.vcxproj.filters +++ b/examples/example_allegro5/example_allegro5.vcxproj.filters @@ -28,6 +28,9 @@ sources + + imgui + imgui diff --git a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj index f382520f..040fcd64 100644 --- a/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj +++ b/examples/example_apple_metal/example_apple_metal.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ 07A82ED82139413D0078D120 /* imgui_widgets.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07A82ED72139413C0078D120 /* imgui_widgets.cpp */; }; 07A82ED92139418F0078D120 /* imgui_widgets.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07A82ED72139413C0078D120 /* imgui_widgets.cpp */; }; + 5079822E257677DB0038A28D /* imgui_tables.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5079822D257677DB0038A28D /* imgui_tables.cpp */; }; 8309BD8F253CCAAA0045E2A1 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8309BD8E253CCAAA0045E2A1 /* UIKit.framework */; }; 8309BDA5253CCC070045E2A1 /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8309BDA0253CCBC10045E2A1 /* main.mm */; }; 8309BDA8253CCC080045E2A1 /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = 8309BDA0253CCBC10045E2A1 /* main.mm */; }; @@ -33,6 +34,7 @@ /* Begin PBXFileReference section */ 07A82ED62139413C0078D120 /* imgui_internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imgui_internal.h; path = ../../imgui_internal.h; sourceTree = ""; }; 07A82ED72139413C0078D120 /* imgui_widgets.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_widgets.cpp; path = ../../imgui_widgets.cpp; sourceTree = ""; }; + 5079822D257677DB0038A28D /* imgui_tables.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_tables.cpp; path = ../../imgui_tables.cpp; sourceTree = ""; }; 8307E7C420E9F9C900473790 /* example_apple_metal.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example_apple_metal.app; sourceTree = BUILT_PRODUCTS_DIR; }; 8307E7DA20E9F9C900473790 /* example_apple_metal.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example_apple_metal.app; sourceTree = BUILT_PRODUCTS_DIR; }; 8309BD8E253CCAAA0045E2A1 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; @@ -146,6 +148,7 @@ 83BBE9F020EB544400295997 /* imgui */ = { isa = PBXGroup; children = ( + 5079822D257677DB0038A28D /* imgui_tables.cpp */, 8309BDB5253CCC9D0045E2A1 /* imgui_impl_metal.mm */, 8309BDB6253CCC9D0045E2A1 /* imgui_impl_osx.mm */, 83BBEA0420EB54E700295997 /* imconfig.h */, @@ -259,10 +262,11 @@ buildActionMask = 2147483647; files = ( 8309BDBB253CCCAD0045E2A1 /* imgui_impl_metal.mm in Sources */, - 83BBEA0520EB54E700295997 /* imgui_draw.cpp in Sources */, 83BBEA0920EB54E700295997 /* imgui.cpp in Sources */, 83BBEA0720EB54E700295997 /* imgui_demo.cpp in Sources */, - 07A82ED82139413D0078D120 /* imgui_widgets.cpp in Sources */, + 83BBEA0520EB54E700295997 /* imgui_draw.cpp in Sources */, + 5079822E257677DB0038A28D /* imgui_tables.cpp in Sources */, + 07A82ED82139413D0078D120 /* imgui_widgets.cpp in Sources */, 8309BDA5253CCC070045E2A1 /* main.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -273,10 +277,11 @@ files = ( 8309BDBE253CCCB60045E2A1 /* imgui_impl_metal.mm in Sources */, 8309BDBF253CCCB60045E2A1 /* imgui_impl_osx.mm in Sources */, - 83BBEA0620EB54E700295997 /* imgui_draw.cpp in Sources */, + 83BBEA0A20EB54E700295997 /* imgui.cpp in Sources */, + 83BBEA0820EB54E700295997 /* imgui_demo.cpp in Sources */, + 83BBEA0620EB54E700295997 /* imgui_draw.cpp in Sources */, + 5079822E257677DB0038A28D /* imgui_tables.cpp in Sources */, 07A82ED92139418F0078D120 /* imgui_widgets.cpp in Sources */, - 83BBEA0A20EB54E700295997 /* imgui.cpp in Sources */, - 83BBEA0820EB54E700295997 /* imgui_demo.cpp in Sources */, 8309BDA8253CCC080045E2A1 /* main.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj index 204b68a9..42d6095d 100644 --- a/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj +++ b/examples/example_apple_opengl2/example_apple_opengl2.xcodeproj/project.pbxproj @@ -16,6 +16,7 @@ 4080A9B020B0347A0036BA46 /* imgui_impl_osx.mm in Sources */ = {isa = PBXBuildFile; fileRef = 4080A99F20B034280036BA46 /* imgui_impl_osx.mm */; }; 4080A9B320B034E40036BA46 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4080A9B220B034E40036BA46 /* Cocoa.framework */; }; 4080A9B520B034EA0036BA46 /* OpenGL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4080A9B420B034EA0036BA46 /* OpenGL.framework */; }; + 50798230257677FD0038A28D /* imgui_tables.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5079822F257677FC0038A28D /* imgui_tables.cpp */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -46,6 +47,7 @@ 4080A9AC20B0343C0036BA46 /* imconfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = imconfig.h; path = ../../imconfig.h; sourceTree = ""; }; 4080A9B220B034E40036BA46 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; 4080A9B420B034EA0036BA46 /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; }; + 5079822F257677FC0038A28D /* imgui_tables.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = imgui_tables.cpp; path = ../../imgui_tables.cpp; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -64,6 +66,7 @@ 4080A96220B029B00036BA46 = { isa = PBXGroup; children = ( + 5079822F257677FC0038A28D /* imgui_tables.cpp */, 4080A9AC20B0343C0036BA46 /* imconfig.h */, 4080A9A720B0343C0036BA46 /* imgui.cpp */, 4080A9A820B0343C0036BA46 /* imgui.h */, @@ -161,6 +164,7 @@ 4080A9A220B034280036BA46 /* imgui_impl_opengl2.cpp in Sources */, 4080A9B020B0347A0036BA46 /* imgui_impl_osx.mm in Sources */, 4080A9AE20B0343C0036BA46 /* imgui.cpp in Sources */, + 50798230257677FD0038A28D /* imgui_tables.cpp in Sources */, 07A82EDB213941D00078D120 /* imgui_widgets.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/examples/example_emscripten_opengl3/Makefile b/examples/example_emscripten_opengl3/Makefile index 06baf499..cde9ffa3 100644 --- a/examples/example_emscripten_opengl3/Makefile +++ b/examples/example_emscripten_opengl3/Makefile @@ -18,7 +18,7 @@ CXX = em++ EXE = example_emscripten_opengl3.html IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) diff --git a/examples/example_glfw_metal/Makefile b/examples/example_glfw_metal/Makefile index 4b7599eb..8f08b965 100644 --- a/examples/example_glfw_metal/Makefile +++ b/examples/example_glfw_metal/Makefile @@ -9,7 +9,7 @@ EXE = example_glfw_metal IMGUI_DIR = ../.. SOURCES = main.mm -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_metal.mm OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) diff --git a/examples/example_glfw_opengl2/Makefile b/examples/example_glfw_opengl2/Makefile index 6bcbca5e..a24a91f3 100644 --- a/examples/example_glfw_opengl2/Makefile +++ b/examples/example_glfw_opengl2/Makefile @@ -17,7 +17,7 @@ EXE = example_glfw_opengl2 IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index 35ffdfd9..2322ce25 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -158,6 +158,7 @@ + diff --git a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters index 4b4dd526..8327557c 100644 --- a/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters +++ b/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters @@ -22,6 +22,9 @@ imgui + + imgui + imgui diff --git a/examples/example_glfw_opengl3/Makefile b/examples/example_glfw_opengl3/Makefile index 1524ac6f..294d103d 100644 --- a/examples/example_glfw_opengl3/Makefile +++ b/examples/example_glfw_opengl3/Makefile @@ -17,7 +17,7 @@ EXE = example_glfw_opengl3 IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 9c823935..61184d87 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -158,6 +158,7 @@ + diff --git a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters index 000e8d28..6e3859c1 100644 --- a/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters +++ b/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters @@ -28,6 +28,9 @@ imgui + + imgui + imgui diff --git a/examples/example_glfw_vulkan/CMakeLists.txt b/examples/example_glfw_vulkan/CMakeLists.txt index 801aee4d..05eab3bc 100644 --- a/examples/example_glfw_vulkan/CMakeLists.txt +++ b/examples/example_glfw_vulkan/CMakeLists.txt @@ -39,5 +39,5 @@ include_directories(${GLFW_DIR}/deps) file(GLOB sources *.cpp) -add_executable(example_glfw_vulkan ${sources} ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp ${IMGUI_DIR}/backends/imgui_impl_vulkan.cpp ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_widgets.cpp) +add_executable(example_glfw_vulkan ${sources} ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp ${IMGUI_DIR}/backends/imgui_impl_vulkan.cpp ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_tables.cpp ${IMGUI_DIR}/imgui_widgets.cpp) target_link_libraries(example_glfw_vulkan ${LIBRARIES}) diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index d9418579..1667b5ab 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -158,6 +158,7 @@ + diff --git a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters index 43f5f5b6..943eb3dd 100644 --- a/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters +++ b/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters @@ -22,6 +22,9 @@ imgui + + imgui + imgui diff --git a/examples/example_glut_opengl2/Makefile b/examples/example_glut_opengl2/Makefile index 21984cec..952ca318 100644 --- a/examples/example_glut_opengl2/Makefile +++ b/examples/example_glut_opengl2/Makefile @@ -12,7 +12,7 @@ EXE = example_glut_opengl2 IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glut.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index 736e6e7a..f14ea156 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -158,6 +158,7 @@ + diff --git a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters index 8f8fd955..69882910 100644 --- a/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters +++ b/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters @@ -22,6 +22,9 @@ imgui + + imgui + imgui diff --git a/examples/example_marmalade/marmalade_example.mkb b/examples/example_marmalade/marmalade_example.mkb index bf5d1b86..4e765f16 100644 --- a/examples/example_marmalade/marmalade_example.mkb +++ b/examples/example_marmalade/marmalade_example.mkb @@ -33,6 +33,7 @@ files ../../imgui.cpp ../../imgui_demo.cpp ../../imgui_draw.cpp + ../../imgui_tables.cpp ../../imgui_widgets.cpp ../../imconfig.h ../../imgui.h diff --git a/examples/example_null/Makefile b/examples/example_null/Makefile index 25cecd82..edf0145e 100644 --- a/examples/example_null/Makefile +++ b/examples/example_null/Makefile @@ -13,7 +13,7 @@ WITH_FREETYPE ?= 0 EXE = example_null IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj index 690c660d..99dd54af 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj @@ -159,6 +159,7 @@ + diff --git a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters index d1f0876e..8ebfd6d1 100644 --- a/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters +++ b/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters @@ -38,6 +38,9 @@ imgui + + imgui + imgui diff --git a/examples/example_sdl_metal/Makefile b/examples/example_sdl_metal/Makefile index 53c8aabb..042bb04c 100644 --- a/examples/example_sdl_metal/Makefile +++ b/examples/example_sdl_metal/Makefile @@ -9,7 +9,7 @@ EXE = example_sdl_metal IMGUI_DIR = ../.. SOURCES = main.mm -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_metal.mm OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) diff --git a/examples/example_sdl_opengl2/Makefile b/examples/example_sdl_opengl2/Makefile index 2da745d7..5fdad0ba 100644 --- a/examples/example_sdl_opengl2/Makefile +++ b/examples/example_sdl_opengl2/Makefile @@ -17,7 +17,7 @@ EXE = example_sdl_opengl2 IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj index b8eb9219..6b9e642d 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj @@ -158,6 +158,7 @@ + diff --git a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters index 65acfe43..643b0ed7 100644 --- a/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters +++ b/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters @@ -22,6 +22,9 @@ sources + + imgui + imgui diff --git a/examples/example_sdl_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile index b408ce35..6e30a135 100644 --- a/examples/example_sdl_opengl3/Makefile +++ b/examples/example_sdl_opengl3/Makefile @@ -17,7 +17,7 @@ EXE = example_sdl_opengl3 IMGUI_DIR = ../.. SOURCES = main.cpp -SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj index c8d67f98..7ef1a792 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj @@ -158,6 +158,7 @@ + @@ -180,4 +181,4 @@ - \ No newline at end of file + diff --git a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters index ade2c96c..f6e323de 100644 --- a/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters +++ b/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters @@ -34,6 +34,9 @@ sources + + imgui + imgui diff --git a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj index 84cc94b4..8567b790 100644 --- a/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj +++ b/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj @@ -158,6 +158,7 @@ + @@ -177,4 +178,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 4a24dc1b..16e24a37 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -155,6 +155,7 @@ + @@ -167,4 +168,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters b/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters index 16107c9c..f76be9d0 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters @@ -44,6 +44,9 @@ sources + + imgui + imgui @@ -54,4 +57,4 @@ sources
- \ No newline at end of file + diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index e9945db9..4982050f 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -154,6 +154,7 @@ + diff --git a/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters b/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters index 6956b586..56defdde 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters @@ -47,6 +47,9 @@ sources + + imgui + diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj b/examples/example_win32_directx12/example_win32_directx12.vcxproj index 452328ce..ab8ee013 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj @@ -157,6 +157,7 @@ + @@ -168,4 +169,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters b/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters index 754c2954..91fc7343 100644 --- a/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters +++ b/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters @@ -44,6 +44,9 @@ sources + + imgui + imgui @@ -51,4 +54,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj b/examples/example_win32_directx9/example_win32_directx9.vcxproj index a33833b3..747dcebe 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -148,6 +148,7 @@ + @@ -167,4 +168,4 @@ - \ No newline at end of file + diff --git a/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters b/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters index 2a684553..5197644e 100644 --- a/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters +++ b/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters @@ -28,6 +28,9 @@ sources + + imgui + imgui @@ -55,4 +58,4 @@ sources - \ No newline at end of file + diff --git a/imgui.cpp b/imgui.cpp index 6fdb3b95..ad219eb9 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -371,6 +371,7 @@ CODE When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added! - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API. - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. diff --git a/imgui_tables.cpp b/imgui_tables.cpp new file mode 100644 index 00000000..2dbe9984 --- /dev/null +++ b/imgui_tables.cpp @@ -0,0 +1,73 @@ +// dear imgui, v1.80 WIP +// (tables and columns code) + +/* + * + * Index of this file: + * + * // [SECTION] Widgets: BeginTable, EndTable, etc. + * // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. + * + */ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#ifndef IMGUI_DISABLE + +#ifndef IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_MATH_OPERATORS +#endif +#include "imgui_internal.h" + +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later +#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types +#endif +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#if __has_warning("-Wunknown-warning-option") +#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! +#endif +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 +#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. +#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead +#endif + + +//----------------------------------------------------------------------------- +// [SECTION] Widgets: BeginTable, EndTable, etc. +//----------------------------------------------------------------------------- + + +//------------------------------------------------------------------------- +// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. +// (This is a legacy API, prefer using BeginTable/EndTable!) +//------------------------------------------------------------------------- + + +//------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/misc/single_file/imgui_single_file.h b/misc/single_file/imgui_single_file.h index 6c849441..6c1fb369 100644 --- a/misc/single_file/imgui_single_file.h +++ b/misc/single_file/imgui_single_file.h @@ -13,5 +13,6 @@ #include "../../imgui.cpp" #include "../../imgui_demo.cpp" #include "../../imgui_draw.cpp" +#include "../../imgui_tables.cpp" #include "../../imgui_widgets.cpp" #endif From 818e1a4eb4cfa08b0151b92217c8fcc6d70595ff Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 30 Nov 2020 17:59:39 +0100 Subject: [PATCH 383/959] Tables: Moving legacy Columns code --- imgui_tables.cpp | 434 +++++++++++++++++++++++++++++++++++++++++++++ imgui_widgets.cpp | 441 ---------------------------------------------- 2 files changed, 434 insertions(+), 441 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2dbe9984..67b625da 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -66,6 +66,440 @@ // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. // (This is a legacy API, prefer using BeginTable/EndTable!) //------------------------------------------------------------------------- +// - SetWindowClipRectBeforeSetChannel() [Internal] +// - GetColumnIndex() +// - GetColumnsCount() +// - GetColumnOffset() +// - GetColumnWidth() +// - SetColumnOffset() +// - SetColumnWidth() +// - PushColumnClipRect() [Internal] +// - PushColumnsBackground() [Internal] +// - PopColumnsBackground() [Internal] +// - FindOrCreateColumns() [Internal] +// - GetColumnsID() [Internal] +// - BeginColumns() +// - NextColumn() +// - EndColumns() +// - Columns() +//------------------------------------------------------------------------- + +// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +// they would meddle many times with the underlying ImDrawCmd. +// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +// the subsequent single call to SetCurrentChannel() does it things once. +void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect) +{ + ImVec4 clip_rect_vec4 = clip_rect.ToVec4(); + window->ClipRect = clip_rect; + window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4; + window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4; +} + +int ImGui::GetColumnIndex() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; +} + +int ImGui::GetColumnsCount() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; +} + +float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm) +{ + return offset_norm * (columns->OffMaxX - columns->OffMinX); +} + +float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset) +{ + return offset / (columns->OffMaxX - columns->OffMinX); +} + +static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; + +static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. + IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; + x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); + if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths)) + x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); + + return x; +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns == NULL) + return 0.0f; + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const float t = columns->Columns[column_index].OffsetNorm; + const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); + return x_offset; +} + +static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false) +{ + if (column_index < 0) + column_index = columns->Current; + + float offset_norm; + if (before_resize) + offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; + else + offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; + return ImGui::GetColumnOffsetFromNorm(columns, offset_norm); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns == NULL) + return GetContentRegionAvail().x; + + if (column_index < 0) + column_index = columns->Current; + return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + IM_ASSERT(column_index < columns->Columns.Size); + + const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1); + const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; + + if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow)) + offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); + columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX); + + if (preserve_width) + SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); +} + +void ImGui::SetColumnWidth(int column_index, float width) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + if (column_index < 0) + column_index = columns->Current; + SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); +} + +void ImGui::PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (column_index < 0) + column_index = columns->Current; + + ImGuiOldColumnData* column = &columns->Columns[column_index]; + PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); +} + +// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) +void ImGui::PushColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; + + // Optimization: avoid SetCurrentChannel() + PushClipRect() + columns->HostBackupClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, 0); +} + +void ImGui::PopColumnsBackground() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns->Count == 1) + return; + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); +} + +ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) +{ + // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. + for (int n = 0; n < window->ColumnsStorage.Size; n++) + if (window->ColumnsStorage[n].ID == id) + return &window->ColumnsStorage[n]; + + window->ColumnsStorage.push_back(ImGuiOldColumns()); + ImGuiOldColumns* columns = &window->ColumnsStorage.back(); + columns->ID = id; + return columns; +} + +ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) +{ + ImGuiWindow* window = GetCurrentWindow(); + + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (str_id ? 0 : columns_count)); + ImGuiID id = window->GetID(str_id ? str_id : "columns"); + PopID(); + + return id; +} + +void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(columns_count >= 1); + IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported + + // Acquire storage for the columns set + ImGuiID id = GetColumnsID(str_id, columns_count); + ImGuiOldColumns* columns = FindOrCreateColumns(window, id); + IM_ASSERT(columns->ID == id); + columns->Current = 0; + columns->Count = columns_count; + columns->Flags = flags; + window->DC.CurrentColumns = columns; + + columns->HostCursorPosY = window->DC.CursorPos.y; + columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; + columns->HostInitialClipRect = window->ClipRect; + columns->HostBackupParentWorkRect = window->ParentWorkRect; + window->ParentWorkRect = window->WorkRect; + + // Set state for first column + // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect + const float column_padding = g.Style.ItemSpacing.x; + const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); + const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f); + const float max_2 = window->WorkRect.Max.x + half_clip_extend_x; + columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f); + columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f); + columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; + + // Clear data if columns count changed + if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) + columns->Columns.resize(0); + + // Initialize default widths + columns->IsFirstFrame = (columns->Columns.Size == 0); + if (columns->Columns.Size == 0) + { + columns->Columns.reserve(columns_count + 1); + for (int n = 0; n < columns_count + 1; n++) + { + ImGuiOldColumnData column; + column.OffsetNorm = n / (float)columns_count; + columns->Columns.push_back(column); + } + } + + for (int n = 0; n < columns_count; n++) + { + // Compute clipping rectangle + ImGuiOldColumnData* column = &columns->Columns[n]; + float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n)); + float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f); + column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); + column->ClipRect.ClipWithFull(window->ClipRect); + } + + if (columns->Count > 1) + { + columns->Splitter.Split(window->DrawList, 1 + columns->Count); + columns->Splitter.SetCurrentChannel(window->DrawList, 1); + PushColumnClipRect(0); + } + + // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; +} + +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.CurrentColumns == NULL) + return; + + ImGuiContext& g = *GImGui; + ImGuiOldColumns* columns = window->DC.CurrentColumns; + + if (columns->Count == 1) + { + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + IM_ASSERT(columns->Current == 0); + return; + } + + // Next column + if (++columns->Current == columns->Count) + columns->Current = 0; + + PopItemWidth(); + + // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), + ImGuiOldColumnData* column = &columns->Columns[columns->Current]; + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); + columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); + + const float column_padding = g.Style.ItemSpacing.x; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + if (columns->Current > 0) + { + // Columns 1+ ignore IndentX (by canceling it out) + // FIXME-COLUMNS: Unnecessary, could be locked? + window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding; + } + else + { + // New row/line: column 0 honor IndentX. + window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); + columns->LineMinY = columns->LineMaxY; + } + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); + window->DC.CursorPos.y = columns->LineMinY; + window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); + window->DC.CurrLineTextBaseOffset = 0.0f; + + // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. + float offset_0 = GetColumnOffset(columns->Current); + float offset_1 = GetColumnOffset(columns->Current + 1); + float width = offset_1 - offset_0; + PushItemWidth(width * 0.65f); + window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; +} + +void ImGui::EndColumns() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + ImGuiOldColumns* columns = window->DC.CurrentColumns; + IM_ASSERT(columns != NULL); + + PopItemWidth(); + if (columns->Count > 1) + { + PopClipRect(); + columns->Splitter.Merge(window->DrawList); + } + + const ImGuiOldColumnFlags flags = columns->Flags; + columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = columns->LineMaxY; + if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize)) + window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent + + // Draw columns borders and handle resize + // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy + bool is_being_resized = false; + if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems) + { + // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. + const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); + const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); + int dragging_column = -1; + for (int n = 1; n < columns->Count; n++) + { + ImGuiOldColumnData* column = &columns->Columns[n]; + float x = window->Pos.x + GetColumnOffset(n); + const ImGuiID column_id = columns->ID + ImGuiID(n); + const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; + const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); + KeepAliveID(column_id); + if (IsClippedEx(column_hit_rect, column_id, false)) + continue; + + bool hovered = false, held = false; + if (!(flags & ImGuiOldColumnFlags_NoResize)) + { + ButtonBehavior(column_hit_rect, column_id, &hovered, &held); + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeEW; + if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize)) + dragging_column = n; + } + + // Draw column + const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); + const float xi = IM_FLOOR(x); + window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); + } + + // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. + if (dragging_column != -1) + { + if (!columns->IsBeingResized) + for (int n = 0; n < columns->Count + 1; n++) + columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; + columns->IsBeingResized = is_being_resized = true; + float x = GetDraggedColumnOffset(columns, dragging_column); + SetColumnOffset(dragging_column, x); + } + } + columns->IsBeingResized = is_being_resized; + + window->WorkRect = window->ParentWorkRect; + window->ParentWorkRect = columns->HostBackupParentWorkRect; + window->DC.CurrentColumns = NULL; + window->DC.ColumnsOffset.x = 0.0f; + window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); +} + +void ImGui::Columns(int columns_count, const char* id, bool border) +{ + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); + + ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder); + //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior + ImGuiOldColumns* columns = window->DC.CurrentColumns; + if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) + return; + + if (columns != NULL) + EndColumns(); + + if (columns_count != 1) + BeginColumns(id, columns_count, flags); +} //------------------------------------------------------------------------- diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 2ecb5656..3a30847d 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -7866,445 +7866,4 @@ void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, } -//------------------------------------------------------------------------- -// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. -// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. -//------------------------------------------------------------------------- -// - SetWindowClipRectBeforeSetChannel() [Internal] -// - GetColumnIndex() -// - GetColumnCount() -// - GetColumnOffset() -// - GetColumnWidth() -// - SetColumnOffset() -// - SetColumnWidth() -// - PushColumnClipRect() [Internal] -// - PushColumnsBackground() [Internal] -// - PopColumnsBackground() [Internal] -// - FindOrCreateColumns() [Internal] -// - GetColumnsID() [Internal] -// - BeginColumns() -// - NextColumn() -// - EndColumns() -// - Columns() -//------------------------------------------------------------------------- - -// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, -// they would meddle many times with the underlying ImDrawCmd. -// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let -// the subsequent single call to SetCurrentChannel() does it things once. -void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect) -{ - ImVec4 clip_rect_vec4 = clip_rect.ToVec4(); - window->ClipRect = clip_rect; - window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4; - window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4; -} - -int ImGui::GetColumnIndex() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; -} - -int ImGui::GetColumnsCount() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; -} - -float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm) -{ - return offset_norm * (columns->OffMaxX - columns->OffMinX); -} - -float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset) -{ - return offset / (columns->OffMaxX - columns->OffMinX); -} - -static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; - -static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index) -{ - // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing - // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. - IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); - - float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; - x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); - if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths)) - x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); - - return x; -} - -float ImGui::GetColumnOffset(int column_index) -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiOldColumns* columns = window->DC.CurrentColumns; - if (columns == NULL) - return 0.0f; - - if (column_index < 0) - column_index = columns->Current; - IM_ASSERT(column_index < columns->Columns.Size); - - const float t = columns->Columns[column_index].OffsetNorm; - const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); - return x_offset; -} - -static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false) -{ - if (column_index < 0) - column_index = columns->Current; - - float offset_norm; - if (before_resize) - offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; - else - offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; - return ImGui::GetColumnOffsetFromNorm(columns, offset_norm); -} - -float ImGui::GetColumnWidth(int column_index) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - ImGuiOldColumns* columns = window->DC.CurrentColumns; - if (columns == NULL) - return GetContentRegionAvail().x; - - if (column_index < 0) - column_index = columns->Current; - return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); -} - -void ImGui::SetColumnOffset(int column_index, float offset) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - ImGuiOldColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - if (column_index < 0) - column_index = columns->Current; - IM_ASSERT(column_index < columns->Columns.Size); - - const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1); - const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; - - if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow)) - offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); - columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX); - - if (preserve_width) - SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); -} - -void ImGui::SetColumnWidth(int column_index, float width) -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiOldColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - if (column_index < 0) - column_index = columns->Current; - SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); -} - -void ImGui::PushColumnClipRect(int column_index) -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiOldColumns* columns = window->DC.CurrentColumns; - if (column_index < 0) - column_index = columns->Current; - - ImGuiOldColumnData* column = &columns->Columns[column_index]; - PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); -} - -// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) -void ImGui::PushColumnsBackground() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiOldColumns* columns = window->DC.CurrentColumns; - if (columns->Count == 1) - return; - - // Optimization: avoid SetCurrentChannel() + PushClipRect() - columns->HostBackupClipRect = window->ClipRect; - SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect); - columns->Splitter.SetCurrentChannel(window->DrawList, 0); -} - -void ImGui::PopColumnsBackground() -{ - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiOldColumns* columns = window->DC.CurrentColumns; - if (columns->Count == 1) - return; - - // Optimization: avoid PopClipRect() + SetCurrentChannel() - SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect); - columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); -} - -ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) -{ - // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. - for (int n = 0; n < window->ColumnsStorage.Size; n++) - if (window->ColumnsStorage[n].ID == id) - return &window->ColumnsStorage[n]; - - window->ColumnsStorage.push_back(ImGuiOldColumns()); - ImGuiOldColumns* columns = &window->ColumnsStorage.back(); - columns->ID = id; - return columns; -} - -ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) -{ - ImGuiWindow* window = GetCurrentWindow(); - - // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. - // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. - PushID(0x11223347 + (str_id ? 0 : columns_count)); - ImGuiID id = window->GetID(str_id ? str_id : "columns"); - PopID(); - - return id; -} - -void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - - IM_ASSERT(columns_count >= 1); - IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported - - // Acquire storage for the columns set - ImGuiID id = GetColumnsID(str_id, columns_count); - ImGuiOldColumns* columns = FindOrCreateColumns(window, id); - IM_ASSERT(columns->ID == id); - columns->Current = 0; - columns->Count = columns_count; - columns->Flags = flags; - window->DC.CurrentColumns = columns; - - columns->HostCursorPosY = window->DC.CursorPos.y; - columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; - columns->HostInitialClipRect = window->ClipRect; - columns->HostBackupParentWorkRect = window->ParentWorkRect; - window->ParentWorkRect = window->WorkRect; - - // Set state for first column - // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect - const float column_padding = g.Style.ItemSpacing.x; - const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize)); - const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f); - const float max_2 = window->WorkRect.Max.x + half_clip_extend_x; - columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f); - columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f); - columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; - - // Clear data if columns count changed - if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) - columns->Columns.resize(0); - - // Initialize default widths - columns->IsFirstFrame = (columns->Columns.Size == 0); - if (columns->Columns.Size == 0) - { - columns->Columns.reserve(columns_count + 1); - for (int n = 0; n < columns_count + 1; n++) - { - ImGuiOldColumnData column; - column.OffsetNorm = n / (float)columns_count; - columns->Columns.push_back(column); - } - } - - for (int n = 0; n < columns_count; n++) - { - // Compute clipping rectangle - ImGuiOldColumnData* column = &columns->Columns[n]; - float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n)); - float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f); - column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); - column->ClipRect.ClipWithFull(window->ClipRect); - } - - if (columns->Count > 1) - { - columns->Splitter.Split(window->DrawList, 1 + columns->Count); - columns->Splitter.SetCurrentChannel(window->DrawList, 1); - PushColumnClipRect(0); - } - - // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user. - float offset_0 = GetColumnOffset(columns->Current); - float offset_1 = GetColumnOffset(columns->Current + 1); - float width = offset_1 - offset_0; - PushItemWidth(width * 0.65f); - window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); - window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); - window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; -} - -void ImGui::NextColumn() -{ - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems || window->DC.CurrentColumns == NULL) - return; - - ImGuiContext& g = *GImGui; - ImGuiOldColumns* columns = window->DC.CurrentColumns; - - if (columns->Count == 1) - { - window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); - IM_ASSERT(columns->Current == 0); - return; - } - - // Next column - if (++columns->Current == columns->Count) - columns->Current = 0; - - PopItemWidth(); - - // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() - // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), - ImGuiOldColumnData* column = &columns->Columns[columns->Current]; - SetWindowClipRectBeforeSetChannel(window, column->ClipRect); - columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1); - - const float column_padding = g.Style.ItemSpacing.x; - columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - if (columns->Current > 0) - { - // Columns 1+ ignore IndentX (by canceling it out) - // FIXME-COLUMNS: Unnecessary, could be locked? - window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding; - } - else - { - // New row/line: column 0 honor IndentX. - window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); - columns->LineMinY = columns->LineMaxY; - } - window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); - window->DC.CursorPos.y = columns->LineMinY; - window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); - window->DC.CurrLineTextBaseOffset = 0.0f; - - // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. - float offset_0 = GetColumnOffset(columns->Current); - float offset_1 = GetColumnOffset(columns->Current + 1); - float width = offset_1 - offset_0; - PushItemWidth(width * 0.65f); - window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; -} - -void ImGui::EndColumns() -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - ImGuiOldColumns* columns = window->DC.CurrentColumns; - IM_ASSERT(columns != NULL); - - PopItemWidth(); - if (columns->Count > 1) - { - PopClipRect(); - columns->Splitter.Merge(window->DrawList); - } - - const ImGuiOldColumnFlags flags = columns->Flags; - columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); - window->DC.CursorPos.y = columns->LineMaxY; - if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize)) - window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent - - // Draw columns borders and handle resize - // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy - bool is_being_resized = false; - if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems) - { - // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. - const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); - const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); - int dragging_column = -1; - for (int n = 1; n < columns->Count; n++) - { - ImGuiOldColumnData* column = &columns->Columns[n]; - float x = window->Pos.x + GetColumnOffset(n); - const ImGuiID column_id = columns->ID + ImGuiID(n); - const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; - const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); - KeepAliveID(column_id); - if (IsClippedEx(column_hit_rect, column_id, false)) - continue; - - bool hovered = false, held = false; - if (!(flags & ImGuiOldColumnFlags_NoResize)) - { - ButtonBehavior(column_hit_rect, column_id, &hovered, &held); - if (hovered || held) - g.MouseCursor = ImGuiMouseCursor_ResizeEW; - if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize)) - dragging_column = n; - } - - // Draw column - const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); - const float xi = IM_FLOOR(x); - window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); - } - - // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. - if (dragging_column != -1) - { - if (!columns->IsBeingResized) - for (int n = 0; n < columns->Count + 1; n++) - columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; - columns->IsBeingResized = is_being_resized = true; - float x = GetDraggedColumnOffset(columns, dragging_column); - SetColumnOffset(dragging_column, x); - } - } - columns->IsBeingResized = is_being_resized; - - window->WorkRect = window->ParentWorkRect; - window->ParentWorkRect = columns->HostBackupParentWorkRect; - window->DC.CurrentColumns = NULL; - window->DC.ColumnsOffset.x = 0.0f; - window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); -} - -void ImGui::Columns(int columns_count, const char* id, bool border) -{ - ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(columns_count >= 1); - - ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder); - //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior - ImGuiOldColumns* columns = window->DC.CurrentColumns; - if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) - return; - - if (columns != NULL) - EndColumns(); - - if (columns_count != 1) - BeginColumns(id, columns_count, flags); -} - -//------------------------------------------------------------------------- - #endif // #ifndef IMGUI_DISABLE From 8da7d3c3e5cd428b4dd7cf277af05c0d889439b7 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 19 Dec 2019 14:50:21 +0100 Subject: [PATCH 384/959] Tables: Initial commit. [Squashed 123+5 commits from tables_wip/] --- imgui.cpp | 141 ++- imgui.h | 153 ++++ imgui_draw.cpp | 9 + imgui_internal.h | 224 ++++- imgui_tables.cpp | 2235 +++++++++++++++++++++++++++++++++++++++++++++ imgui_widgets.cpp | 4 + 6 files changed, 2755 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index ad219eb9..c7be3624 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -947,6 +947,7 @@ ImGuiStyle::ImGuiStyle() FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + CellPadding = ImVec2(4,2); // Padding within a table cell TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). @@ -987,6 +988,7 @@ void ImGuiStyle::ScaleAllSizes(float scale_factor) FrameRounding = ImFloor(FrameRounding * scale_factor); ItemSpacing = ImFloor(ItemSpacing * scale_factor); ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor); + CellPadding = ImFloor(CellPadding * scale_factor); TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor); IndentSpacing = ImFloor(IndentSpacing * scale_factor); ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor); @@ -2135,6 +2137,14 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO) //----------------------------------------------------------------------------- +// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell. +// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous. +static bool GetSkipItemForListClipping() +{ + ImGuiContext& g = *GImGui; + return (g.CurrentTable ? g.CurrentTable->BackupSkipItems : g.CurrentWindow->SkipItems); +} + // Helper to calculate coarse clipping of large list of evenly sized items. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX @@ -2149,7 +2159,7 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items *out_items_display_end = items_count; return; } - if (window->SkipItems) + if (GetSkipItemForListClipping()) { *out_items_display_start = *out_items_display_end = 0; return; @@ -2185,12 +2195,20 @@ static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height) // The clipper should probably have a 4th step to display the last item in a regular manner. ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + float off_y = pos_y - window->DC.CursorPos.y; window->DC.CursorPos.y = pos_y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y); window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. if (ImGuiOldColumns* columns = window->DC.CurrentColumns) - columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly + columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly // FIXME-TABLE + if (ImGuiTable* table = g.CurrentTable) + { + if (table->IsInsideRow) + ImGui::TableEndRow(table); + table->RowPosY2 = window->DC.CursorPos.y; + table->RowBgColorCounter += (int)((off_y / line_height) + 0.5f); + } } ImGuiListClipper::ImGuiListClipper() @@ -2212,6 +2230,10 @@ void ImGuiListClipper::Begin(int items_count, float items_height) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + if (ImGuiTable* table = g.CurrentTable) + if (table->IsInsideRow) + ImGui::TableEndRow(table); + StartPosY = window->DC.CursorPos.y; ItemsHeight = items_height; ItemsCount = items_count; @@ -2237,8 +2259,12 @@ bool ImGuiListClipper::Step() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + ImGuiTable* table = g.CurrentTable; + if (table && table->IsInsideRow) + ImGui::TableEndRow(table); + // Reached end of list - if (DisplayEnd >= ItemsCount || window->SkipItems) + if (DisplayEnd >= ItemsCount || GetSkipItemForListClipping()) { End(); return false; @@ -2266,7 +2292,17 @@ bool ImGuiListClipper::Step() if (StepNo == 1) { IM_ASSERT(ItemsHeight <= 0.0f); - ItemsHeight = window->DC.CursorPos.y - StartPosY; + if (table) + { + const float pos_y1 = table->RowPosY1; // Using this instead of StartPosY to handle clipper straddling the frozen row + const float pos_y2 = table->RowPosY2; // Using this instead of CursorPos.y to take account of tallest cell. + ItemsHeight = pos_y2 - pos_y1; + window->DC.CursorPos.y = pos_y2; + } + else + { + ItemsHeight = window->DC.CursorPos.y - StartPosY; + } IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); StepNo = 2; } @@ -2405,6 +2441,7 @@ static const ImGuiStyleVarInfo GStyleVarInfo[] = { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing + { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize @@ -2512,6 +2549,9 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; + case ImGuiCol_TableHeaderBg: return "TableHeaderBg"; + case ImGuiCol_TableRowBg: return "TableRowBg"; + case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; case ImGuiCol_NavHighlight: return "NavHighlight"; @@ -3998,6 +4038,10 @@ void ImGui::Shutdown(ImGuiContext* context) g.CurrentTabBarStack.clear(); g.ShrinkWidthBuffer.clear(); + g.Tables.Clear(); + g.CurrentTableStack.clear(); + g.DrawChannelsTempMergeBuffer.clear(); + g.ClipboardHandlerData.clear(); g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); @@ -7374,7 +7418,7 @@ ImVec2 ImGui::GetContentRegionMax() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImVec2 mx = window->ContentRegionRect.Max - window->Pos; - if (window->DC.CurrentColumns) + if (window->DC.CurrentColumns || g.CurrentTable) mx.x = window->WorkRect.Max.x - window->Pos.x; return mx; } @@ -7385,7 +7429,7 @@ ImVec2 ImGui::GetContentRegionMaxAbs() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImVec2 mx = window->ContentRegionRect.Max; - if (window->DC.CurrentColumns) + if (window->DC.CurrentColumns || g.CurrentTable) mx.x = window->WorkRect.Max.x; return mx; } @@ -10459,6 +10503,23 @@ void ImGui::ShowMetricsWindow(bool* p_open) struct Funcs { + static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n) + { + if (rect_type == TRT_OuterRect) { return table->OuterRect; } + else if (rect_type == TRT_WorkRect) { return table->WorkRect; } + else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; } + else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; } + else if (rect_type == TRT_BackgroundClipRect) { return table->BackgroundClipRect; } + else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); } + else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; } + else if (rect_type == TRT_ColumnsContentHeadersUsed) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate + else if (rect_type == TRT_ColumnsContentHeadersIdeal) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersDesired, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // " + else if (rect_type == TRT_ColumnsContentRowsFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthRowsFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // " + else if (rect_type == TRT_ColumnsContentRowsUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->MinX + c->ContentWidthRowsUnfrozen, table->InnerClipRect.Max.y); } // " + IM_ASSERT(0); + return ImRect(); + } + static ImRect GetWindowRect(ImGuiWindow* window, int rect_type) { if (rect_type == WRT_OuterRect) { return window->Rect(); } @@ -10500,6 +10561,49 @@ void ImGui::ShowMetricsWindow(bool* p_open) } Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh); Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes); + + Checkbox("Show tables rectangles", &cfg->ShowTablesRects); + SameLine(); + SetNextItemWidth(GetFontSize() * 12); + cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count); + if (cfg->ShowTablesRects && g.NavWindow != NULL) + { + for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++) + { + ImGuiTable* table = g.Tables.GetByIndex(table_n); + if (table->LastFrameActive < g.FrameCount - 1 || table->OuterWindow != g.NavWindow) + continue; + + BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name); + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, ~0, 2.0f); + Indent(); + for (int rect_n = 0; rect_n < TRT_Count; rect_n++) + { + if (rect_n >= TRT_ColumnsRect) + { + if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect) + continue; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImRect r = Funcs::GetTableRect(table, rect_n, column_n); + Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]); + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, ~0, 2.0f); + } + } + else + { + ImRect r = Funcs::GetTableRect(table, rect_n, -1); + Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]); + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, ~0, 2.0f); + } + } + Unindent(); + } + } + TreePop(); } @@ -10533,7 +10637,6 @@ void ImGui::ShowMetricsWindow(bool* p_open) } // Details for Tables - IM_UNUSED(trt_rects_names); #ifdef IMGUI_HAS_TABLE if (TreeNode("Tables", "Tables (%d)", g.Tables.GetSize())) { @@ -10584,8 +10687,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_TABLE if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) { - for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) - DebugNodeTableSettings(settings); + //for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + // DebugNodeTableSettings(settings); TreePop(); } #endif // #ifdef IMGUI_HAS_TABLE @@ -10664,11 +10767,29 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_TABLE // Overlay: Display Tables Rectangles - if (show_tables_rects) + if (cfg->ShowTablesRects) { for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++) { ImGuiTable* table = g.Tables.GetByIndex(table_n); + if (table->LastFrameActive < g.FrameCount - 1) + continue; + ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow); + if (cfg->ShowTablesRectsType >= TRT_ColumnsRect) + { + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n); + ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255); + float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f; + draw_list->AddRect(r.Min, r.Max, col, 0.0f, ~0, thickness); + } + } + else + { + ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1); + draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); + } } } #endif // #ifdef IMGUI_HAS_TABLE diff --git a/imgui.h b/imgui.h index d1d42b3c..69ef0d42 100644 --- a/imgui.h +++ b/imgui.h @@ -33,6 +33,8 @@ Index of this file: // Draw List API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) +// FIXME-TABLE: Add ImGuiTableSortSpecsColumn and ImGuiTableSortSpecs in "Misc data structures" section above (we don't do it right now to facilitate merging various branches) + */ #pragma once @@ -136,6 +138,8 @@ struct ImGuiPayload; // User data payload for drag and drop opera struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) struct ImGuiStorage; // Helper for key->value storage struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +struct ImGuiTableSortSpecsColumn; // Sorting specification for one column of a table struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") @@ -151,6 +155,7 @@ typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle) typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier +typedef int ImGuiSortDirection; // -> enum ImGuiSortDirection_ // Enum: A sorting direction (ascending or descending) typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect(), AddRectFilled() etc. typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList @@ -170,6 +175,9 @@ typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: f typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() +typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() +typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() +typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() @@ -657,6 +665,35 @@ namespace ImGui IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column IMGUI_API int GetColumnsCount(); + // Tables + // [ALPHA API] API will evolve! (FIXME-TABLE) + // - Full-featured replacement for old Columns API + // - In most situations you can use TableNextRow() + TableSetColumnIndex() to populate a table. + // - If you are using tables as a sort of grid, populating every columns with the same type of contents, + // you may prefer using TableNextCell() instead of TableNextRow() + TableSetColumnIndex(). + #define IMGUI_HAS_TABLE 1 + IMGUI_API bool BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); + IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! + IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. + IMGUI_API bool TableNextCell(); // append into the next column (next column, or next row if currently in last column). Return true if column is visible. + IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true if column is visible. + IMGUI_API int TableGetColumnIndex(); // return current column index. + IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Use pass -1 to use current column. + IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Use pass -1 to use current column. + IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Use pass -1 to use current column. + // Tables: Headers & Columns declaration + // - Use TableSetupColumn() to specify resizing policy, default width, name, id, specific flags etc. + // - The name passed to TableSetupColumn() is used by TableAutoHeaders() and by the context-menu + // - Use TableAutoHeaders() to submit the whole header row, otherwise you may treat the header row as a regular row, manually call TableHeader() and other widgets. + // - Headers are required to perform some interactions: reordering, sorting, context menu // FIXME-TABLES: remove context from this list! + IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = -1.0f, ImU32 user_id = 0); + IMGUI_API void TableAutoHeaders(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu + IMGUI_API void TableHeader(const char* label); // submit one header cell manually. + // Tables: Sorting + // - Call TableGetSortSpecs() to retrieve latest sort specs for the table. Return value will be NULL if no sorting. + // - Read ->SpecsChanged to tell if the specs have changed since last call. + IMGUI_API const ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). + // Tab Bars, Tabs IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! @@ -967,6 +1004,85 @@ enum ImGuiTabItemFlags_ ImGuiTabItemFlags_Trailing = 1 << 7 // Enforce the tab position to the right of the tab bar (before the scrolling buttons) }; +// Flags for ImGui::BeginTable() +enum ImGuiTableFlags_ +{ + // Features + ImGuiTableFlags_None = 0, + ImGuiTableFlags_Resizable = 1 << 0, // Allow resizing columns. + ImGuiTableFlags_Reorderable = 1 << 1, // Allow reordering columns (need calling TableSetupColumn() + TableAutoHeaders() or TableHeaders() to display headers) + ImGuiTableFlags_Hideable = 1 << 2, // Allow hiding columns (with right-click on header) (FIXME-TABLE: allow without headers). + ImGuiTableFlags_Sortable = 1 << 3, // Allow sorting on one column (sort_specs_count will always be == 1). Call TableGetSortSpecs() to obtain sort specs. + ImGuiTableFlags_MultiSortable = 1 << 4, // Allow sorting on multiple columns by holding Shift (sort_specs_count may be > 1). Call TableGetSortSpecs() to obtain sort specs. + ImGuiTableFlags_NoSavedSettings = 1 << 5, // Disable persisting columns order, width and sort settings in the .ini file. + // Decoration + ImGuiTableFlags_RowBg = 1 << 6, // Use ImGuiCol_TableRowBg and ImGuiCol_TableRowBgAlt colors behind each rows. + ImGuiTableFlags_BordersOuter = 1 << 7, // Draw outer borders. + ImGuiTableFlags_BordersV = 1 << 8, // Draw vertical borders between columns. + ImGuiTableFlags_BordersH = 1 << 9, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersFullHeight = 1 << 10, // Borders covers all lines even when Headers are being used, allow resizing all rows. + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersH, + // Padding, Sizing + ImGuiTableFlags_NoClipX = 1 << 12, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items with be able to overflow) + ImGuiTableFlags_SizingPolicyStretchX = 1 << 13, // (Default if ScrollX is off) Columns will default to use ImGuiTableColumnFlags_WidthStretch. Fit all columns within available width. Fixed and Weighted columns allowed. + ImGuiTableFlags_SizingPolicyFixedX = 1 << 14, // (Default if ScrollX is on) Columns will default to use ImGuiTableColumnFlags_WidthFixed or WidthAuto. Enlarge as needed: enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rect. Only Fixed columns allowed. Weighted columns will calculate their width assuming no scrolling. + ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribute to automatic width calculation for every columns. + ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) + // Scrolling + ImGuiTableFlags_ScrollX = 1 << 17, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 18, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, + ImGuiTableFlags_ScrollFreezeRowsShift_ = 19, // We can lock 1 to 3 rows (starting from the top). Encode each of those values as dedicated flags. + ImGuiTableFlags_ScrollFreezeTopRow = 1 << ImGuiTableFlags_ScrollFreezeRowsShift_, + ImGuiTableFlags_ScrollFreeze2Rows = 2 << ImGuiTableFlags_ScrollFreezeRowsShift_, + ImGuiTableFlags_ScrollFreeze3Rows = 3 << ImGuiTableFlags_ScrollFreezeRowsShift_, + ImGuiTableFlags_ScrollFreezeColumnsShift_ = 21, // We can lock 1 to 3 columns (starting from the left). Encode each of those values as dedicated flags. + ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << ImGuiTableFlags_ScrollFreezeColumnsShift_, + ImGuiTableFlags_ScrollFreeze2Columns = 2 << ImGuiTableFlags_ScrollFreezeColumnsShift_, + ImGuiTableFlags_ScrollFreeze3Columns = 3 << ImGuiTableFlags_ScrollFreezeColumnsShift_, + + // Combinations and masks + ImGuiTableFlags_SizingPolicyMaskX_ = ImGuiTableFlags_SizingPolicyStretchX | ImGuiTableFlags_SizingPolicyFixedX, + ImGuiTableFlags_ScrollFreezeRowsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeRowsShift_, + ImGuiTableFlags_ScrollFreezeColumnsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeColumnsShift_ +}; + +// Flags for ImGui::TableSetupColumn() +// FIXME-TABLE: Rename to ImGuiColumns_*, stick old columns api flags in there under an obsolete api block +enum ImGuiTableColumnFlags_ +{ + ImGuiTableColumnFlags_None = 0, + ImGuiTableColumnFlags_DefaultHide = 1 << 0, // Default as a hidden column. + ImGuiTableColumnFlags_DefaultSort = 1 << 1, // Default as a sorting column. + ImGuiTableColumnFlags_WidthFixed = 1 << 2, // Column will keep a fixed size, preferable with horizontal scrolling enabled (default if table sizing policy is SizingPolicyFixedX). + ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch, preferable with horizontal scrolling disabled (default if table sizing policy is SizingPolicyStretchX). + ImGuiTableColumnFlags_WidthAlwaysAutoResize = 1 << 4, // Column will keep resizing based on submitted contents (with a one frame delay) == Fixed with auto resize + ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. + ImGuiTableColumnFlags_NoClipX = 1 << 6, // Disable clipping for this column (all NoClipX columns will render in a same draw command). + ImGuiTableColumnFlags_NoSort = 1 << 7, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). + ImGuiTableColumnFlags_NoSortAscending = 1 << 8, // Disable ability to sort in the ascending direction. + ImGuiTableColumnFlags_NoSortDescending = 1 << 9, // Disable ability to sort in the descending direction. + ImGuiTableColumnFlags_NoHide = 1 << 10, // Disable hiding this column. + ImGuiTableColumnFlags_NoHeaderWidth = 1 << 11, // Header width don't contribute to automatic column width. + ImGuiTableColumnFlags_PreferSortAscending = 1 << 12, // Make the initial sort direction Ascending when first sorting on this column (default). + ImGuiTableColumnFlags_PreferSortDescending = 1 << 13, // Make the initial sort direction Descending when first sorting on this column. + //ImGuiTableColumnFlags_AlignLeft = 1 << 14, + //ImGuiTableColumnFlags_AlignCenter = 1 << 15, + //ImGuiTableColumnFlags_AlignRight = 1 << 16, + + // Combinations and masks + ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthAlwaysAutoResize, + ImGuiTableColumnFlags_NoDirectResize_ = 1 << 20 // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) + //ImGuiTableColumnFlags_AlignMask_ = ImGuiTableColumnFlags_AlignLeft | ImGuiTableColumnFlags_AlignCenter | ImGuiTableColumnFlags_AlignRight +}; + +// Flags for ImGui::TableNextRow() +enum ImGuiTableRowFlags_ +{ + ImGuiTableRowFlags_None = 0, + ImGuiTableRowFlags_Headers = 1 << 0 // Identify header row (set default background color + width of its contents accounted different for auto column width) +}; + // Flags for ImGui::IsWindowFocused() enum ImGuiFocusedFlags_ { @@ -1044,6 +1160,14 @@ enum ImGuiDir_ ImGuiDir_COUNT }; +// A sorting direction +enum ImGuiSortDirection_ +{ + ImGuiSortDirection_None = 0, + ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc. + ImGuiSortDirection_Descending = 2 // Descending = 9->0, Z->A etc. +}; + // User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array enum ImGuiKey_ { @@ -1188,6 +1312,9 @@ enum ImGuiCol_ ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, + ImGuiCol_TableHeaderBg, // Table header background + ImGuiCol_TableRowBg, // Table row background (even rows) + ImGuiCol_TableRowBgAlt, // Table row background (odd rows) ImGuiCol_TextSelectedBg, ImGuiCol_DragDropTarget, ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item @@ -1228,6 +1355,7 @@ enum ImGuiStyleVar_ ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing ImGuiStyleVar_IndentSpacing, // float IndentSpacing + ImGuiStyleVar_CellPadding, // ImVec2 CellPadding ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding ImGuiStyleVar_GrabMinSize, // float GrabMinSize @@ -1464,6 +1592,7 @@ struct ImGuiStyle float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). + ImVec2 CellPadding; // Padding within a table cell ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). @@ -1700,6 +1829,30 @@ struct ImGuiPayload bool IsDelivery() const { return Delivery; } }; +// Sorting specification for one column of a table (sizeof == 8 bytes) +struct ImGuiTableSortSpecsColumn +{ + ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) + ImU8 ColumnIndex; // Index of the column + ImU8 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) + ImS8 SortSign; // +1 or -1 (you can use this or SortDirection, whichever is more convenient for your sort function) + ImS8 SortDirection; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function) + + ImGuiTableSortSpecsColumn() { ColumnUserID = 0; ColumnIndex = 0; SortOrder = 0; SortSign = +1; SortDirection = ImGuiSortDirection_Ascending; } +}; + +// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +// Obtained by calling TableGetSortSpecs() +struct ImGuiTableSortSpecs +{ + const ImGuiTableSortSpecsColumn* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1 unless e.g. ImGuiTableFlags_MultiSortable is enabled. + bool SpecsChanged; // Set to true by TableGetSortSpecs() call if the specs have changed since the previous call. + ImU64 ColumnsMask; // Set to the mask of column indexes included in the Specs array. e.g. (1 << N) when column N is sorted. + + ImGuiTableSortSpecs() { Specs = NULL; SpecsCount = 0; SpecsChanged = false; ColumnsMask = 0x00; } +}; + //----------------------------------------------------------------------------- // Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) // Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 93eb23f2..e915dd76 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -222,6 +222,9 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); @@ -277,6 +280,9 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.27f, 0.27f, 0.38f, 1.00f); + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; @@ -333,6 +339,9 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.78f, 0.87f, 0.98f, 1.00f); + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.07f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f); colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered]; diff --git a/imgui_internal.h b/imgui_internal.h index 33cc991e..5ec83845 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -111,6 +111,10 @@ struct ImGuiStackSizes; // Storage of stack sizes for debugging/asse struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it struct ImGuiTabBar; // Storage for a tab bar struct ImGuiTabItem; // Storage for a tab item (within a tab bar) +struct ImGuiTable; // Storage for a table +struct ImGuiTableColumn; // Storage for one column of a table +struct ImGuiTableSettings; // Storage for a table .ini settings +struct ImGuiTableColumnsSettings; // Storage for a column .ini settings struct ImGuiWindow; // Storage for one window struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame) struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session) @@ -264,6 +268,7 @@ IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); // Helpers: Bit manipulation static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } +static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } // Helpers: String, Formatting @@ -1329,6 +1334,12 @@ struct ImGuiContext ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size unsigned char DragDropPayloadBufLocal[16]; // Local buffer for small payloads + // Table + ImGuiTable* CurrentTable; + ImPool Tables; + ImVector CurrentTableStack; + ImVector DrawChannelsTempMergeBuffer; + // Tab bars ImGuiTabBar* CurrentTabBar; ImPool TabBars; @@ -1366,6 +1377,7 @@ struct ImGuiContext ImGuiTextBuffer SettingsIniData; // In memory .ini settings ImVector SettingsHandlers; // List of .ini settings handlers ImChunkStream SettingsWindows; // ImGuiWindow .ini settings entries + ImChunkStream SettingsTables; // ImGuiTable .ini settings entries ImVector Hooks; // Hooks for extensions (e.g. test engine) // Capture/Logging @@ -1496,6 +1508,7 @@ struct ImGuiContext DragDropHoldJustPressedId = 0; memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal)); + CurrentTable = NULL; CurrentTabBar = NULL; LastValidMousePos = ImVec2(0.0f, 0.0f); @@ -1581,6 +1594,7 @@ struct IMGUI_API ImGuiWindowTempData ImVector ChildWindows; ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) ImGuiOldColumns* CurrentColumns; // Current columns set + ImGuiTable* CurrentTable; // Current table set ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() int FocusCounterRegular; // (Legacy Focus/Tabbing system) Sequential counter, start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign) @@ -1805,7 +1819,185 @@ struct ImGuiTabBar //----------------------------------------------------------------------------- #ifdef IMGUI_HAS_TABLE -// + +#define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code +#define IMGUI_TABLE_MAX_COLUMNS 64 // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64. + +// [Internal] sizeof() ~ 96 +struct ImGuiTableColumn +{ + ImGuiID UserID; // Optional, value passed to TableSetupColumn() + ImGuiTableColumnFlags FlagsIn; // Flags as input by user. See ImGuiTableColumnFlags_ + ImGuiTableColumnFlags Flags; // Effective flags. See ImGuiTableColumnFlags_ + float ResizeWeight; // ~1.0f. Master width data when (Flags & _WidthStretch) + float MinX; // Absolute positions + float MaxX; + float WidthRequested; // Master width data when !(Flags & _WidthStretch) + float WidthGiven; // == (MaxX - MinX). FIXME-TABLE: Store all persistent width in multiple of FontSize? + float StartXRows; // Start position for the frame, currently ~(MinX + CellPaddingX) + float StartXHeaders; + ImS16 ContentWidthRowsFrozen; // Contents width. Because freezing is non correlated from headers we need all 4 variants (ImDrawCmd merging uses different data than alignment code). + ImS16 ContentWidthRowsUnfrozen; // (encoded as ImS16 because we actually rarely use those width) + ImS16 ContentWidthHeadersUsed; // TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls + ImS16 ContentWidthHeadersDesired; + float ContentMaxPosRowsFrozen; // Submitted contents absolute maximum position, from which we can infer width. + float ContentMaxPosRowsUnfrozen; // (kept as float because we need to manipulate those between each cell change) + float ContentMaxPosHeadersUsed; + float ContentMaxPosHeadersDesired; + ImRect ClipRect; + ImS16 NameOffset; // Offset into parent ColumnsName[] + bool IsActive; // Is the column not marked Hidden by the user (regardless of clipping). We're not calling this "Visible" here because visibility also depends on clipping. + bool NextIsActive; + ImS8 IndexDisplayOrder; // Index within DisplayOrder[] (column may be reordered by users) + ImS8 IndexWithinActiveSet; // Index within active set (<= IndexOrder) + ImS8 DrawChannelCurrent; // Index within DrawSplitter.Channels[] + ImS8 DrawChannelRowsBeforeFreeze; + ImS8 DrawChannelRowsAfterFreeze; + ImS8 PrevActiveColumn; // Index of prev active column within Columns[], -1 if first active column + ImS8 NextActiveColumn; // Index of next active column within Columns[], -1 if last active column + ImS8 AutoFitFrames; + ImS8 SortOrder; // -1: Not sorting on this column + ImS8 SortDirection; // enum ImGuiSortDirection_ + + ImGuiTableColumn() + { + memset(this, 0, sizeof(*this)); + ResizeWeight = 1.0f; + WidthRequested = WidthGiven = -1.0f; + NameOffset = -1; + IsActive = NextIsActive = true; + IndexDisplayOrder = IndexWithinActiveSet = -1; + DrawChannelCurrent = DrawChannelRowsBeforeFreeze = DrawChannelRowsAfterFreeze = -1; + PrevActiveColumn = NextActiveColumn = -1; + AutoFitFrames = 3; + SortOrder = -1; + SortDirection = ImGuiSortDirection_Ascending; + } +}; + +// FIXME-OPT: Since CountColumns is invariant, we could use a single alloc for ImGuiTable + the three vectors it is carrying. +struct ImGuiTable +{ + ImGuiID ID; + ImGuiTableFlags Flags; + ImVector Columns; + ImVector DisplayOrder; // Store display order of columns (when not reordered, the values are 0...Count-1) + ImU64 ActiveMaskByIndex; // Column Index -> IsActive map (Active == not hidden by user/api) in a format adequate for iterating column without touching cold data + ImU64 ActiveMaskByDisplayOrder; // Column DisplayOrder -> IsActive map + ImGuiTableFlags SettingsSaveFlags; // Pre-compute which data we are going to save into the .ini file (e.g. when order is not altered we won't save order) + int SettingsOffset; // Offset in g.SettingsTables + int LastFrameActive; + int ColumnsCount; // Number of columns declared in BeginTable() + int ColumnsActiveCount; // Number of non-hidden columns (<= ColumnsCount) + int CurrentColumn; + int CurrentRow; + float RowPosY1; + float RowPosY2; + float RowTextBaseline; + ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ + ImGuiTableRowFlags LastRowFlags : 16; + int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper) + ImU32 RowBgColor; // Request for current row background color + ImU32 BorderOuterColor; + ImU32 BorderInnerColor; + float BorderX1; + float BorderX2; + float CellPaddingX1; // Padding from each borders + float CellPaddingX2; + float CellPaddingY; + float CellSpacingX; // Spacing between non-bordered cells + float LastOuterHeight; // Outer height from last frame + float LastFirstRowHeight; // Height of first row from last frame + float ColumnsTotalWidth; + float InnerWidth; + ImRect OuterRect; // Note: OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). + ImRect WorkRect; + ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. + ImRect InnerClipRect; + ImRect BackgroundClipRect; // We use this to cpu-clip cell background color fill + ImGuiWindow* OuterWindow; // Parent window for the table + ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) + ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names + ImDrawListSplitter DrawSplitter; // We carry our own ImDrawList splitter to allow recursion (could be stored outside?) + ImVector SortSpecsData; // FIXME-OPT: Fixed-size array / small-vector pattern, optimize for single sort spec + ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() + ImS8 SortSpecsCount; + ImS8 DeclColumnsCount; // Count calls to TableSetupColumn() + ImS8 HoveredColumnBody; // [DEBUG] Unlike HoveredColumnBorder this doesn't fulfill all Hovering rules properly. Used for debugging/tools for now. + ImS8 HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). + ImS8 ResizedColumn; // Index of column being resized. + ImS8 LastResizedColumn; + ImS8 ReorderColumn; // Index of column being reordered. (not cleared) + ImS8 ReorderColumnDir; // -1 or +1 + ImS8 RightMostActiveColumn; // Index of right-most non-hidden column. + ImS8 LeftMostStretchedColumnDisplayOrder; // Display order of left-most stretched column. + ImS8 ContextPopupColumn; // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot + ImS8 DummyDrawChannel; // Redirect non-visible columns here. + ImS8 FreezeRowsRequest; // Requested frozen rows count + ImS8 FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset) + ImS8 FreezeColumnsRequest; // Requested frozen columns count + ImS8 FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) + bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. + bool IsInsideRow; // Set if inside TableBeginRow()/TableEndRow(). + bool IsFirstFrame; + bool IsSortSpecsDirty; + bool IsUsingHeaders; // Set if the first row had the ImGuiTableRowFlags_Headers flag. + bool IsContextPopupOpen; + bool IsSettingsRequestLoad; + bool IsSettingsLoaded; + 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) + bool IsResetDisplayOrderRequest; + bool IsFreezeRowsPassed; // Set when we got past the frozen row (the first one). + bool BackupSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis + ImRect BackupWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() + ImVec2 BackupCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() + + ImGuiTable() + { + memset(this, 0, sizeof(*this)); + SettingsOffset = -1; + LastFrameActive = -1; + LastResizedColumn = -1; + ContextPopupColumn = -1; + ReorderColumn = -1; + } +}; + +// sizeof() ~ 12 +struct ImGuiTableColumnSettings +{ + float WidthOrWeight; + ImGuiID UserID; + ImS8 Index; + ImS8 DisplayOrder; + ImS8 SortOrder; + ImS8 SortDirection : 7; + ImU8 Visible : 1; // This is called Active in ImGuiTableColumn, in .ini file we call it Visible. + + ImGuiTableColumnSettings() + { + WidthOrWeight = 0.0f; + UserID = 0; + Index = -1; + DisplayOrder = SortOrder = -1; + SortDirection = ImGuiSortDirection_None; + Visible = 1; + } +}; + +// This is designed to be stored in a single ImChunkStream (1 header followed by N ImGuiTableColumnSettings, etc.) +struct ImGuiTableSettings +{ + ImGuiID ID; // Set to 0 to invalidate/delete the setting + ImGuiTableFlags SaveFlags; + ImS8 ColumnsCount; + ImS8 ColumnsCountMax; + + ImGuiTableSettings() { memset(this, 0, sizeof(*this)); } + ImGuiTableColumnSettings* GetColumnSettings() { return (ImGuiTableColumnSettings*)(this + 1); } +}; + #endif // #ifdef IMGUI_HAS_TABLE //----------------------------------------------------------------------------- @@ -1977,6 +2169,35 @@ namespace ImGui IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm); IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); + // Tables + //IMGUI_API int GetTableColumnNo(); + //IMGUI_API bool SetTableColumnNo(int column_n); + //IMGUI_API int GetTableLineNo(); + IMGUI_API void TableBeginInitVisibility(ImGuiTable* table); + IMGUI_API void TableBeginInitDrawChannels(ImGuiTable* table); + IMGUI_API void TableUpdateLayout(ImGuiTable* table); + IMGUI_API void TableUpdateBorders(ImGuiTable* table); + IMGUI_API void TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column, float width); + IMGUI_API void TableDrawBorders(ImGuiTable* table); + IMGUI_API void TableDrawMergeChannels(ImGuiTable* table); + IMGUI_API void TableDrawContextMenu(ImGuiTable* table, int column_n); + IMGUI_API void TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* column, bool add_to_existing_sort_orders); + IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); + IMGUI_API void TableBeginRow(ImGuiTable* table); + IMGUI_API void TableEndRow(ImGuiTable* table); + IMGUI_API void TableBeginCell(ImGuiTable* table, int column_no); + IMGUI_API void TableEndCell(ImGuiTable* table); + IMGUI_API ImRect TableGetCellRect(); + IMGUI_API const char* TableGetColumnName(ImGuiTable* table, int column_no); + IMGUI_API void PushTableBackground(); + IMGUI_API void PopTableBackground(); + IMGUI_API void TableLoadSettings(ImGuiTable* table); + IMGUI_API void TableSaveSettings(ImGuiTable* table); + IMGUI_API ImGuiTableSettings* TableFindSettings(ImGuiTable* table); + IMGUI_API void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); + IMGUI_API void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); + IMGUI_API void TableSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); + // Tab Bars IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); @@ -2094,6 +2315,7 @@ namespace ImGui IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); 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); IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label); IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings); IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 67b625da..657ccad4 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -61,6 +61,2241 @@ // [SECTION] Widgets: BeginTable, EndTable, etc. //----------------------------------------------------------------------------- +// Typical call flow: (root level is public API): +// - BeginTable() user begin into a table +// - BeginChild() - (if ScrollX/ScrollY is set) +// - TableBeginInitVisibility() - lock columns visibility +// - TableBeginInitDrawChannels() - setup ImDrawList channels +// - TableSetupColumn() user submit columns details (optional) +// - TableAutoHeaders() or TableHeader() user submit a headers row (optional) +// - TableSortSpecsClickColumn() +// - TableGetSortSpecs() user queries updated sort specs (optional) +// - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders() +// - TableUpdateLayout() - called by the FIRST call to TableNextRow() +// - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +// - TableDrawContextMenu() - draw right-click context menu +// - [...] user emit contents +// - EndTable() user ends the table +// - TableDrawBorders() - draw outer borders, inner vertical borders +// - TableDrawMergeChannels() - merge draw channels if clipping isn't required +// - TableSetColumnWidth() - apply resizing width +// - TableUpdateColumnsWeightFromWidth() +// - EndChild() - (if ScrollX/ScrollY is set) + +// Configuration +static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders. +static const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f; // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped. + +// Helper +inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) +{ + // Adjust flags: set default sizing policy + if ((flags & ImGuiTableFlags_SizingPolicyMaskX_) == 0) + flags |= (flags & ImGuiTableFlags_ScrollX) ? ImGuiTableFlags_SizingPolicyFixedX : ImGuiTableFlags_SizingPolicyStretchX; + + // Adjust flags: MultiSortable automatically enable Sortable + if (flags & ImGuiTableFlags_MultiSortable) + flags |= ImGuiTableFlags_Sortable; + + // Adjust flags: disable saved settings if there's nothing to save + if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0) + flags |= ImGuiTableFlags_NoSavedSettings; + + // Adjust flags: enforce borders when resizable + if (flags & ImGuiTableFlags_Resizable) + flags |= ImGuiTableFlags_BordersV; + + // Adjust flags: disable top rows freezing if there's no scrolling + if ((flags & ImGuiTableFlags_ScrollX) == 0) + flags &= ~ImGuiTableFlags_ScrollFreezeColumnsMask_; + if ((flags & ImGuiTableFlags_ScrollY) == 0) + flags &= ~ImGuiTableFlags_ScrollFreezeRowsMask_; + + // Adjust flags: disable NoHostExtendY if we have any scrolling going on + if ((flags & ImGuiTableFlags_NoHostExtendY) && (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0) + flags &= ~ImGuiTableFlags_NoHostExtendY; + + // Adjust flags: we don't support NoClipX with (FreezeColumns > 0), we could with some work but it doesn't appear to be worth the effort + if (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) + flags &= ~ImGuiTableFlags_NoClipX; + + return flags; +} + +// About 'outer_size': +// The meaning of outer_size needs to differ slightly depending of if we are using ScrollX/ScrollY flags. +// With ScrollX/ScrollY: using a child window for scrolling: +// - outer_size.y < 0.0f -> bottom align +// - outer_size.y = 0.0f -> bottom align: consistent with BeginChild(), best to preserve (0,0) default arg +// - outer_size.y > 0.0f -> fixed child height +// Without scrolling, we output table directly in parent window: +// - outer_size.y < 0.0f -> bottom align (will auto extend, unless NoHostExtendV is set) +// - outer_size.y = 0.0f -> zero minimum height (will auto extend, unless NoHostExtendV is set) +// - outer_size.y > 0.0f -> minimum height (will auto extend, unless NoHostExtendV is set) +// About: 'inner_width': +// With ScrollX: +// - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird +// - inner_width = 0.0f -> auto enlarge: *only* fixed size columns, which will take space they need (proportional columns becomes fixed columns) <-- desired default :( +// - inner_width > 0.0f -> fit in known width: fixed column take space they need if possible (otherwise shrink down), proportional columns share remaining space. +// Without ScrollX: +// - inner_width < 0.0f -> fit in known width (right align from outer_size.x) <-- desired default +// - inner_width = 0.0f -> auto enlarge: will emit contents size in parent window +// - inner_width > 0.0f -> fit in known width (bypass outer_size.x, permitted but not useful, should instead alter outer_width) +// FIXME-TABLE: This is currently not very useful. +// FIXME-TABLE: Replace enlarge vs fixed width by a flag. +// Even if not really useful, we allow 'inner_scroll_width < outer_size.x' for consistency and to facilitate understanding of what the value does. +bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* outer_window = GetCurrentWindow(); + IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS && "Only 0..63 columns allowed!"); + if (flags & ImGuiTableFlags_ScrollX) + IM_ASSERT(inner_width >= 0.0f); + ImGuiID id = GetID(str_id); + + const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0; + const ImVec2 avail_size = GetContentRegionAvail(); + ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f); + ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size); + + // If an outer size is specified ahead we will be able to early out when not visible, + // The exact rules here can evolve. + if (use_child_window && IsClippedEx(outer_rect, id, false)) + { + ItemSize(outer_rect); + return false; + } + + flags = TableFixFlags(flags); + if (outer_window->Flags & ImGuiWindowFlags_NoSavedSettings) + flags |= ImGuiTableFlags_NoSavedSettings; + + // Acquire storage for the table + ImGuiTable* table = g.Tables.GetOrAddByKey(id); + const ImGuiTableFlags table_last_flags = table->Flags; + table->ID = id; + table->Flags = flags; + table->IsFirstFrame = (table->LastFrameActive == -1); + table->LastFrameActive = g.FrameCount; + table->OuterWindow = table->InnerWindow = outer_window; + table->ColumnsCount = columns_count; + table->ColumnsNames.Buf.resize(0); + table->IsLayoutLocked = false; + table->InnerWidth = inner_width; + table->OuterRect = outer_rect; + table->WorkRect = outer_rect; + + if (use_child_window) + { + // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) + ImVec2 override_content_size(FLT_MAX, FLT_MAX); + if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY)) + override_content_size.y = FLT_MIN; + + // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and never lead to any scrolling) + // We don't handle inner_width < 0.0f, we could potentially use it to right-align based on the right side of the child window work rect, + // which would require knowing ahead if we are going to have decoration taking horizontal spaces (typically a vertical scrollbar). + if (inner_width != 0.0f) + override_content_size.x = inner_width; + + if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX) + SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f)); + + // Create scrolling region (without border = zero window padding) + ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; + BeginChildEx(str_id, id, table->OuterRect.GetSize(), false, child_flags); + table->InnerWindow = g.CurrentWindow; + table->WorkRect = table->InnerWindow->WorkRect; + table->OuterRect = table->InnerWindow->Rect(); + } + else + { + // WorkRect.Max will grow as we append contents. + PushID(id); + } + + const bool has_cell_padding_x = (flags & (ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV)) != 0; + ImGuiWindow* inner_window = table->InnerWindow; + table->CurrentColumn = -1; + table->CurrentRow = -1; + table->RowBgColorCounter = 0; + table->LastRowFlags = ImGuiTableRowFlags_None; + + table->CellPaddingX1 = has_cell_padding_x ? g.Style.CellPadding.x + 1.0f : 0.0f; + table->CellPaddingX2 = has_cell_padding_x ? g.Style.CellPadding.x : 0.0f; + table->CellPaddingY = g.Style.CellPadding.y; + table->CellSpacingX = has_cell_padding_x ? 0.0f : g.Style.CellPadding.x; + + table->HostClipRect = inner_window->ClipRect; + table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; + table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width + table->InnerClipRect.ClipWith(table->HostClipRect); + table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? table->WorkRect.Max.y : inner_window->ClipRect.Max.y; + table->BackgroundClipRect = table->InnerClipRect; + table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow + table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() + table->FreezeRowsRequest = (ImS8)((flags & ImGuiTableFlags_ScrollFreezeRowsMask_) >> ImGuiTableFlags_ScrollFreezeRowsShift_); + table->FreezeRowsCount = (inner_window->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0; + table->FreezeColumnsRequest = (ImS8)((flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) >> ImGuiTableFlags_ScrollFreezeColumnsShift_); + table->FreezeColumnsCount = (inner_window->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; + table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); + table->DeclColumnsCount = 0; + table->LastResizedColumn = table->ResizedColumn; + table->HoveredColumnBody = -1; + table->HoveredColumnBorder = -1; + table->RightMostActiveColumn = -1; + table->LeftMostStretchedColumnDisplayOrder = -1; + table->IsFirstFrame = false; + + // FIXME-TABLE FIXME-STYLE: Using opaque colors facilitate overlapping elements of the grid + //table->BorderOuterColor = GetColorU32(ImGuiCol_Separator, 1.00f); + //table->BorderInnerColor = GetColorU32(ImGuiCol_Separator, 0.60f); + table->BorderOuterColor = GetColorU32(ImVec4(0.31f, 0.31f, 0.35f, 1.00f)); + table->BorderInnerColor = GetColorU32(ImVec4(0.23f, 0.23f, 0.25f, 1.00f)); + //table->BorderOuterColor = IM_COL32(255, 0, 0, 255); + //table->BorderInnerColor = IM_COL32(255, 255, 0, 255); + table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f); + table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f); + + // Make table current + g.CurrentTableStack.push_back(ImGuiPtrOrIndex(g.Tables.GetIndex(table))); + g.CurrentTable = table; + outer_window->DC.CurrentTable = table; + if ((table_last_flags & ImGuiTableFlags_Reorderable) && !(flags & ImGuiTableFlags_Reorderable)) + table->IsResetDisplayOrderRequest = true; + + // Clear data if columns count changed + if (table->Columns.Size != 0 && table->Columns.Size != columns_count) + { + table->Columns.resize(0); + table->DisplayOrder.resize(0); + } + + // Setup default columns state + if (table->Columns.Size == 0) + { + table->IsFirstFrame = true; + table->IsSortSpecsDirty = true; + table->Columns.reserve(columns_count); + table->DisplayOrder.reserve(columns_count); + for (int n = 0; n < columns_count; n++) + { + ImGuiTableColumn column; + column.IndexDisplayOrder = (ImS8)n; + table->Columns.push_back(column); + table->DisplayOrder.push_back(column.IndexDisplayOrder); + } + } + + // Load settings + if (table->IsFirstFrame || table->IsSettingsRequestLoad) + TableLoadSettings(table); + + // Handle reordering request + // Note: we don't clear ReorderColumn after handling the request. + if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0) + { + IM_ASSERT(table->ReorderColumnDir == -1 || table->ReorderColumnDir == +1); + IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); + ImGuiTableColumn* dragged_column = &table->Columns[table->ReorderColumn]; + ImGuiTableColumn* target_column = &table->Columns[(table->ReorderColumnDir == -1) ? dragged_column->PrevActiveColumn : dragged_column->NextActiveColumn]; + ImSwap(table->DisplayOrder[dragged_column->IndexDisplayOrder], table->DisplayOrder[target_column->IndexDisplayOrder]); + ImSwap(dragged_column->IndexDisplayOrder, target_column->IndexDisplayOrder); + table->ReorderColumnDir = 0; + table->IsSettingsDirty = true; + } + + // Handle display order reset request + if (table->IsResetDisplayOrderRequest) + { + for (int n = 0; n < columns_count; n++) + table->DisplayOrder[n] = table->Columns[n].IndexDisplayOrder = (ImU8)n; + table->IsResetDisplayOrderRequest = false; + table->IsSettingsDirty = true; + } + + TableBeginInitVisibility(table); + TableBeginInitDrawChannels(table); + + // Grab a copy of window fields we will modify + table->BackupSkipItems = inner_window->SkipItems; + table->BackupWorkRect = inner_window->WorkRect; + table->BackupCursorMaxPos = inner_window->DC.CursorMaxPos; + + if (flags & ImGuiTableFlags_NoClipX) + table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 1); + else + inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false); + + return true; +} + +void ImGui::TableBeginInitVisibility(ImGuiTable* table) +{ + // Setup and lock Active state and order + table->ColumnsActiveCount = 0; + table->IsDefaultDisplayOrder = true; + ImGuiTableColumn* last_active_column = NULL; + bool want_column_auto_fit = false; + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + const int column_n = table->DisplayOrder[order_n]; + if (column_n != order_n) + table->IsDefaultDisplayOrder = false; + ImGuiTableColumn* column = &table->Columns[column_n]; + column->NameOffset = -1; + if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide)) + column->NextIsActive = true; + if (column->IsActive != column->NextIsActive) + { + column->IsActive = column->NextIsActive; + table->IsSettingsDirty = true; + if (!column->IsActive && column->SortOrder != -1) + table->IsSortSpecsDirty = true; + } + if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_MultiSortable)) + table->IsSortSpecsDirty = true; + if (column->AutoFitFrames > 0) + want_column_auto_fit = true; + + ImU64 index_mask = (ImU64)1 << column_n; + ImU64 display_order_mask = (ImU64)1 << column->IndexDisplayOrder; + if (column->IsActive) + { + column->PrevActiveColumn = column->NextActiveColumn = -1; + if (last_active_column) + { + last_active_column->NextActiveColumn = (ImS8)column_n; + column->PrevActiveColumn = (ImS8)table->Columns.index_from_ptr(last_active_column); + } + column->IndexWithinActiveSet = (ImS8)table->ColumnsActiveCount; + table->ColumnsActiveCount++; + table->ActiveMaskByIndex |= index_mask; + table->ActiveMaskByDisplayOrder |= display_order_mask; + last_active_column = column; + } + else + { + column->IndexWithinActiveSet = -1; + table->ActiveMaskByIndex &= ~index_mask; + table->ActiveMaskByDisplayOrder &= ~display_order_mask; + } + IM_ASSERT(column->IndexWithinActiveSet <= column->IndexDisplayOrder); + } + table->RightMostActiveColumn = (ImS8)(last_active_column ? table->Columns.index_from_ptr(last_active_column) : -1); + + // Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid + // the column fitting to wait until the first visible frame of the child container (may or not be a good thing). + if (want_column_auto_fit && table->OuterWindow != table->InnerWindow) + table->InnerWindow->SkipItems = false; +} + +void ImGui::TableBeginInitDrawChannels(ImGuiTable* table) +{ + // Allocate draw channels. + // - We allocate them following the storage order instead of the display order so reordering won't needlessly increase overall dormant memory cost + // - We isolate headers draw commands in their own channels instead of just altering clip rects. This is in order to facilitate merging of draw commands. + // - After crossing FreezeRowsCount, all columns see their current draw channel increased. + // - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. + // Draw channel allocation (before merging): + // - NoClip --> 1+1 channels: background + foreground (same clip rect == 1 draw call) + // - Clip --> 1+N channels + // - FreezeRows || FreezeColumns --> 1+N*2 (unless scrolling value is zero) + // - FreezeRows && FreezeColunns --> 2+N*2 (unless scrolling value is zero) + const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1; + const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClipX) ? 1 : table->ColumnsActiveCount; + const int channels_for_background = 1; + const int channels_for_dummy = (table->ColumnsActiveCount < table->ColumnsCount) ? +1 : 0; + const int channels_total = channels_for_background + (channels_for_row * freeze_row_multiplier) + channels_for_dummy; + table->DrawSplitter.Split(table->InnerWindow->DrawList, channels_total); + table->DummyDrawChannel = channels_for_dummy ? (ImS8)(channels_total - 1) : -1; + + int draw_channel_current = 1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->IsActive) + { + column->DrawChannelRowsBeforeFreeze = (ImS8)(draw_channel_current); + column->DrawChannelRowsAfterFreeze = (ImS8)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row : 0)); + if (!(table->Flags & ImGuiTableFlags_NoClipX)) + draw_channel_current++; + } + else + { + column->DrawChannelRowsBeforeFreeze = column->DrawChannelRowsAfterFreeze = table->DummyDrawChannel; + } + column->DrawChannelCurrent = column->DrawChannelRowsBeforeFreeze; + } +} + +// Adjust flags: default width mode + weighted columns are not allowed when auto extending +static ImGuiTableColumnFlags TableFixColumnFlags(ImGuiTable* table, ImGuiTableColumnFlags flags) +{ + // Sizing Policy + if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0) + { + if (table->Flags & ImGuiTableFlags_SizingPolicyFixedX) + flags |= ((table->Flags & ImGuiTableFlags_Resizable) && !(flags & ImGuiTableColumnFlags_NoResize)) ? ImGuiTableColumnFlags_WidthFixed : ImGuiTableColumnFlags_WidthAlwaysAutoResize; + else + flags |= ImGuiTableColumnFlags_WidthStretch; + } + IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used. + if ((flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize))// || ((flags & ImGuiTableColumnFlags_WidthStretch) && (table->Flags & ImGuiTableFlags_SizingPolicyStretchX))) + flags |= ImGuiTableColumnFlags_NoResize; + //if ((flags & ImGuiTableColumnFlags_WidthStretch) && (table->Flags & ImGuiTableFlags_SizingPolicyFixedX)) + // flags = (flags & ~ImGuiTableColumnFlags_WidthMask_) | ImGuiTableColumnFlags_WidthFixed; + + // Sorting + if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending)) + flags |= ImGuiTableColumnFlags_NoSort; + + // Alignment + //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0) + // flags |= ImGuiTableColumnFlags_AlignCenter; + //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used. + + return flags; +} + +static void TableFixColumnSortDirection(ImGuiTableColumn* column) +{ + // Handle NoSortAscending/NoSortDescending + if (column->SortDirection == ImGuiSortDirection_Ascending && (column->Flags & ImGuiTableColumnFlags_NoSortAscending)) + column->SortDirection = ImGuiSortDirection_Descending; + else if (column->SortDirection == ImGuiSortDirection_Descending && (column->Flags & ImGuiTableColumnFlags_NoSortDescending)) + column->SortDirection = ImGuiSortDirection_Ascending; +} + +static float TableGetMinColumnWidth() +{ + ImGuiContext& g = *GImGui; + // return g.Style.ColumnsMinSpacing; + return g.Style.FramePadding.x * 3.0f; +} + +// Layout columns for the frame +// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first. +// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for WidthAuto columns, +// increase feedback side-effect with widgets relying on WorkRect.Max.x. Maybe provide a default distribution for WidthAuto columns? +void ImGui::TableUpdateLayout(ImGuiTable* table) +{ + IM_ASSERT(table->IsLayoutLocked == false); + + // Compute offset, clip rect for the frame + const ImRect work_rect = table->WorkRect; + const float padding_auto_x = table->CellPaddingX1; // Can't make auto padding larger than what WorkRect knows about so right-alignment matches. + const float min_column_width = TableGetMinColumnWidth(); + + int count_fixed = 0; + float width_fixed = 0.0f; + float total_weights = 0.0f; + table->LeftMostStretchedColumnDisplayOrder = -1; + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + const int column_n = table->DisplayOrder[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Adjust flags: default width mode + weighted columns are not allowed when auto extending + column->Flags = TableFixColumnFlags(table, column->FlagsIn); + + // We have a unusual edge case where if the user doesn't call TableGetSortSpecs() but has sorting enabled + // or varying sorting flags, we still want the sorting arrows to honor those flags. + if (table->Flags & ImGuiTableFlags_Sortable) + TableFixColumnSortDirection(column); + + if (column->Flags & (ImGuiTableColumnFlags_WidthAlwaysAutoResize | ImGuiTableColumnFlags_WidthFixed)) + { + // Latch initial size for fixed columns + count_fixed += 1; + const bool init_size = (column->AutoFitFrames > 0) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize); + if (init_size) + { + // Combine width from regular rows + width from headers unless requested not to + float width_request = (float)ImMax(column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen); + if (!(table->Flags & ImGuiTableFlags_NoHeadersWidth) && !(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth)) + width_request = ImMax(width_request, (float)column->ContentWidthHeadersDesired); + column->WidthRequested = ImMax(width_request + padding_auto_x, min_column_width); + + // FIXME-TABLE: Increase minimum size during init frame so avoid biasing auto-fitting widgets (e.g. TextWrapped) too much. + // Otherwise what tends to happen is that TextWrapped would output a very large height (= first frame scrollbar display very off + clipper would skip lots of items) + // This is merely making the side-effect less extreme, but doesn't properly fixes it. + if (column->AutoFitFrames > 1 && table->IsFirstFrame) + column->WidthRequested = ImMax(column->WidthRequested, min_column_width * 4.0f); + } + width_fixed += column->WidthRequested; + } + else + { + IM_ASSERT(column->Flags & ImGuiTableColumnFlags_WidthStretch); + IM_ASSERT(column->ResizeWeight > 0.0f); + total_weights += column->ResizeWeight; + if (table->LeftMostStretchedColumnDisplayOrder == -1) + table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->IndexDisplayOrder; + } + + // Don't increment auto-fit until container window got a chance to submit its items + if (column->AutoFitFrames > 0 && table->BackupSkipItems == false) + column->AutoFitFrames--; + } + + // Layout + const float width_spacings = table->CellSpacingX * (table->ColumnsActiveCount - 1); + float width_avail; + if ((table->Flags & ImGuiTableFlags_ScrollX) && (table->InnerWidth == 0.0f)) + width_avail = table->InnerClipRect.GetWidth() - width_spacings - 1.0f; + else + width_avail = work_rect.GetWidth() - width_spacings - 1.0f; // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible + const float width_avail_for_stretched_columns = width_avail - width_fixed; + float width_remaining_for_stretched_columns = width_avail_for_stretched_columns; + + // Apply final width based on requested widths + // Mark some columns as not resizable + int count_resizable = 0; + table->ColumnsTotalWidth = width_spacings; + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + ImGuiTableColumn* column = &table->Columns[table->DisplayOrder[order_n]]; + + // Allocate width for stretched/weighted columns + if (column->Flags & ImGuiTableColumnFlags_WidthStretch) + { + float weight_ratio = column->ResizeWeight / total_weights; + column->WidthRequested = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, min_column_width) + 0.01f); + width_remaining_for_stretched_columns -= column->WidthRequested; + + // [Resize Rule 2] Resizing from right-side of a weighted column before a fixed column froward sizing to left-side of fixed column + // We also need to copy the NoResize flag.. + if (column->NextActiveColumn != -1) + if (ImGuiTableColumn* next_column = &table->Columns[column->NextActiveColumn]) + if (next_column->Flags & ImGuiTableColumnFlags_WidthFixed) + column->Flags |= (next_column->Flags & ImGuiTableColumnFlags_NoDirectResize_); + } + + // [Resize Rule 1] The right-most active column is not resizable if there is at least one Stretch column (see comments in TableResizeColumn().) + if (column->NextActiveColumn == -1 && table->LeftMostStretchedColumnDisplayOrder != -1) + column->Flags |= ImGuiTableColumnFlags_NoDirectResize_; + + if (!(column->Flags & ImGuiTableColumnFlags_NoResize)) + count_resizable++; + + // Assign final width, record width in case we will need to shrink + column->WidthGiven = ImFloor(ImMax(column->WidthRequested, min_column_width)); + table->ColumnsTotalWidth += column->WidthGiven; + } + +#if 0 + const float width_excess = table->ColumnsTotalWidth - work_rect.GetWidth(); + if ((table->Flags & ImGuiTableFlags_SizingPolicyStretchX) && width_excess > 0.0f) + { + // Shrink widths when the total does not fit + // FIXME-TABLE: This is working but confuses/conflicts with manual resizing. + // FIXME-TABLE: Policy to shrink down below below ideal/requested width if there's no room? + g.ShrinkWidthBuffer.resize(table->ColumnsActiveCount); + for (int order_n = 0, active_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + const int column_n = table->DisplayOrder[order_n]; + g.ShrinkWidthBuffer[active_n].Index = column_n; + g.ShrinkWidthBuffer[active_n].Width = table->Columns[column_n].WidthGiven; + active_n++; + } + ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess); + for (int n = 0; n < g.ShrinkWidthBuffer.Size; n++) + table->Columns[g.ShrinkWidthBuffer.Data[n].Index].WidthGiven = ImMax(g.ShrinkWidthBuffer.Data[n].Width, min_column_size); + // FIXME: Need to alter table->ColumnsTotalWidth + } + else +#endif + + // Redistribute remainder width due to rounding (remainder width is < 1.0f * number of Stretch column) + // Using right-to-left distribution (more likely to match resizing cursor), could be adjusted depending where the mouse cursor is and/or relative weights. + // FIXME-TABLE: May be simpler to store floating width and floor final positions only + // FIXME-TABLE: Make it optional? User might prefer to preserve pixel perfect same size? + if (width_remaining_for_stretched_columns >= 1.0f) + for (int order_n = table->ColumnsCount - 1; total_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--) + { + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + ImGuiTableColumn* column = &table->Columns[table->DisplayOrder[order_n]]; + if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + column->WidthRequested += 1.0f; + column->WidthGiven += 1.0f; + width_remaining_for_stretched_columns -= 1.0f; + } + + // Setup final position, offset and clipping rectangles + int active_n = 0; + float offset_x = (table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x; + ImRect host_clip_rect = table->InnerClipRect; + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + const int column_n = table->DisplayOrder[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + + if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == active_n) + offset_x += work_rect.Min.x - table->OuterRect.Min.x; + + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + { + // Hidden column: clear a few fields and we are done with it for the remainder of the function. + // We set a zero-width clip rect however we pay attention to set Min.y/Max.y properly to not interfere with the clipper. + column->MinX = column->MaxX = offset_x; + column->StartXRows = column->StartXHeaders = offset_x; + column->WidthGiven = 0.0f; + column->ClipRect.Min.x = offset_x; + column->ClipRect.Min.y = work_rect.Min.y; + column->ClipRect.Max.x = offset_x; + column->ClipRect.Max.y = FLT_MAX; + column->ClipRect.ClipWithFull(host_clip_rect); + continue; + } + + // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. + // Because of this we also know that all of the columns will always fit in table->WorkRect and therefore in table->InnerRect (because ScrollX is off) + if (!(table->Flags & ImGuiTableFlags_ScrollX)) + { + float max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width; + if (offset_x + column->WidthGiven > max_x) + column->WidthGiven = ImMax(max_x - offset_x, min_column_width); + } + + column->MinX = offset_x; + column->MaxX = column->MinX + column->WidthGiven; + + const float initial_max_pos_x = column->MinX + table->CellPaddingX1; + column->ContentMaxPosRowsFrozen = column->ContentMaxPosRowsUnfrozen = initial_max_pos_x; + column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersDesired = initial_max_pos_x; + + // Starting cursor position + column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1; + + // Alignment + // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in many cases. + // (To be able to honor this we might be able to store a log of cells width, per row, for visible rows, but nav/programmatic scroll would have visible artifacts.) + //if (column->Flags & ImGuiTableColumnFlags_AlignRight) + // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]); + //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) + // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]), 0.5f); + + //// A one pixel padding on the right side makes clipping more noticeable and contents look less cramped. + column->ClipRect.Min.x = column->MinX; + column->ClipRect.Min.y = work_rect.Min.y; + column->ClipRect.Max.x = column->MaxX;// -1.0f; + column->ClipRect.Max.y = FLT_MAX; + column->ClipRect.ClipWithFull(host_clip_rect); + + if (active_n < table->FreezeColumnsCount) + host_clip_rect.Min.x = ImMax(host_clip_rect.Min.x, column->MaxX + 2.0f); + + offset_x += column->WidthGiven + table->CellSpacingX; + active_n++; + } + + // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either because of using _WidthAlwaysAutoResize/_WidthStretch) + // This will hide the resizing option from the context menu. + if (count_resizable == 0 && (table->Flags & ImGuiTableFlags_Resizable)) + table->Flags &= ~ImGuiTableFlags_Resizable; + + // Borders + if (table->Flags & ImGuiTableFlags_Resizable) + TableUpdateBorders(table); + + // Reset fields after we used them in TableSetupResize() + table->LastFirstRowHeight = 0.0f; + table->IsLayoutLocked = true; + table->IsUsingHeaders = false; + + // Context menu + if (table->IsContextPopupOpen) + { + if (BeginPopup("##TableContextMenu")) + { + TableDrawContextMenu(table, table->ContextPopupColumn); + EndPopup(); + } + else + { + table->IsContextPopupOpen = false; + } + } +} + +// Process interaction on resizing borders. Actual size change will be applied in EndTable() +// - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise +// - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets overlapping the same area. +void ImGui::TableUpdateBorders(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable); + + // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and use + // the final height from last frame. Because this is only affecting _interaction_ with columns, it is not really problematic. + // (whereas the actual visual will be displayed in EndTable() and using the current frame height) + // Actual columns highlight/render will be performed in EndTable() and not be affected. + const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersFullHeight); + const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS; + const float hit_y1 = table->OuterRect.Min.y; + const float hit_y2_full = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight); + const float hit_y2 = borders_full_height ? hit_y2_full : (hit_y1 + table->LastFirstRowHeight); + const float mouse_x_hover_body = (g.IO.MousePos.y >= hit_y1 && g.IO.MousePos.y < hit_y2_full) ? g.IO.MousePos.x : FLT_MAX; + + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + + const int column_n = table->DisplayOrder[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Detect hovered column: + // - we perform an unusually low-level check here.. not using IsMouseHoveringRect() to avoid touch padding. + // - we don't care about the full set of IsItemHovered() feature either. + if (mouse_x_hover_body >= column->MinX && mouse_x_hover_body < column->MaxX) + table->HoveredColumnBody = (ImS8)column_n; + + if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) + continue; + + ImGuiID column_id = table->ID + (ImGuiID)column_n; + ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, hit_y2); + //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)); + KeepAliveID(column_id); + + bool hovered = false, held = false; + ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap); + if (held) + table->ResizedColumn = (ImS8)column_n; + if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held) + { + table->HoveredColumnBorder = (ImS8)column_n; + SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } + } +} + +void ImGui::EndTable() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL); + + const ImGuiTableFlags flags = table->Flags; + ImGuiWindow* inner_window = table->InnerWindow; + ImGuiWindow* outer_window = table->OuterWindow; + IM_ASSERT(inner_window == g.CurrentWindow); + IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow); + + if (table->IsInsideRow) + TableEndRow(table); + + // Finalize table height + inner_window->SkipItems = table->BackupSkipItems; + inner_window->DC.CursorMaxPos = table->BackupCursorMaxPos; + if (inner_window != outer_window) + { + table->OuterRect.Max.y = ImMax(table->OuterRect.Max.y, inner_window->Pos.y + inner_window->Size.y); + inner_window->DC.CursorMaxPos.y = table->RowPosY2; + } + else if (!(flags & ImGuiTableFlags_NoHostExtendY)) + { + table->OuterRect.Max.y = ImMax(table->OuterRect.Max.y, inner_window->DC.CursorPos.y); + inner_window->DC.CursorMaxPos.y = table->RowPosY2; + } + table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y); + table->LastOuterHeight = table->OuterRect.GetHeight(); + + // Store content width reference for each column + float max_pos_x = inner_window->DC.CursorMaxPos.x; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Store content width (for both Headers and Rows) + //float ref_x = column->MinX; + float ref_x_rows = column->StartXRows - table->CellPaddingX1; + float ref_x_headers = column->StartXHeaders - table->CellPaddingX1; + column->ContentWidthRowsFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsFrozen - ref_x_rows); + column->ContentWidthRowsUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsUnfrozen - ref_x_rows); + column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers); + column->ContentWidthHeadersDesired = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersDesired - ref_x_headers); + + if (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) + max_pos_x = ImMax(max_pos_x, column->MaxX); + } + + // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. + inner_window->DC.CursorMaxPos.x = max_pos_x + 1; + + if (!(flags & ImGuiTableFlags_NoClipX)) + inner_window->DrawList->PopClipRect(); + inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back(); + + // Draw borders + if ((flags & ImGuiTableFlags_Borders) != 0) + TableDrawBorders(table); + + // Flatten channels and merge draw calls + table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0); + TableDrawMergeChannels(table); + + // When releasing a column being resized, scroll to keep the resulting column in sight + const float min_column_width = TableGetMinColumnWidth(); + if (!(table->Flags & ImGuiTableFlags_ScrollX) && inner_window != outer_window) + { + inner_window->Scroll.x = 0.0f; + } + else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX) + { + ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn]; + if (column->MaxX < table->InnerClipRect.Min.x) + SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - min_column_width, 1.0f); + else if (column->MaxX > table->InnerClipRect.Max.x) + SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + min_column_width, 1.0f); + } + + // Apply resizing/dragging at the end of the frame + // FIXME-TABLE: Preserve contents width _while resizing down_ until releasing. + // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling. + if (table->ResizedColumn != -1) + { + ImGuiTableColumn* column = &table->Columns[table->ResizedColumn]; + const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS); + const float new_width = ImFloor(new_x2 - column->MinX); + TableSetColumnWidth(table, column, new_width); + } + + // Layout in outer window + inner_window->WorkRect = table->BackupWorkRect; + inner_window->SkipItems = table->BackupSkipItems; + outer_window->DC.CursorPos = table->OuterRect.Min; + outer_window->DC.ColumnsOffset.x = 0.0f; + if (inner_window != outer_window) + { + // Override EndChild's ItemSize with our own to enable auto-resize on the X axis when possible + float backup_outer_cursor_pos_x = outer_window->DC.CursorPos.x; + EndChild(); + outer_window->DC.CursorMaxPos.x = backup_outer_cursor_pos_x + table->ColumnsTotalWidth + 1.0f + inner_window->ScrollbarSizes.x; + } + else + { + PopID(); + ImVec2 item_size = table->OuterRect.GetSize(); + item_size.x = table->ColumnsTotalWidth; + ItemSize(item_size); + } + + // Save settings + if (table->IsSettingsDirty) + TableSaveSettings(table); + + // Clear or restore current table, if any + IM_ASSERT(g.CurrentWindow == outer_window); + IM_ASSERT(g.CurrentTable == table); + outer_window->DC.CurrentTable = NULL; + g.CurrentTableStack.pop_back(); + g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL; +} + +void ImGui::TableDrawBorders(ImGuiTable* table) +{ + ImGuiWindow* inner_window = table->InnerWindow; + ImGuiWindow* outer_window = table->OuterWindow; + table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0); + if (inner_window->Hidden || !table->HostClipRect.Overlaps(table->InnerClipRect)) + return; + + // Draw inner border and resizing feedback + const float draw_y1 = table->OuterRect.Min.y; + float draw_y2_base = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight; + float draw_y2_full = table->OuterRect.Max.y; + ImU32 border_base_col; + if (!table->IsUsingHeaders || (table->Flags & ImGuiTableFlags_BordersFullHeight)) + { + draw_y2_base = draw_y2_full; + border_base_col = table->BorderInnerColor; + } + else + { + border_base_col = table->BorderOuterColor; + } + + if (table->Flags & ImGuiTableFlags_BordersV) + { + const bool draw_left_most_border = (table->Flags & ImGuiTableFlags_BordersOuter) == 0; + if (draw_left_most_border) + inner_window->DrawList->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, 1.0f); + + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + + const int column_n = table->DisplayOrder[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + const bool is_hovered = (table->HoveredColumnBorder == column_n); + const bool is_resized = (table->ResizedColumn == column_n); + const bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered); + if (draw_right_border && column->MaxX > column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + { + // Draw in outer window so right-most column won't be clipped + // Always draw full height border when: + // - not using headers + // - user specify ImGuiTableFlags_BordersFullHeight + // - being interacted with + // - on the delimitation of frozen column scrolling + const ImU32 col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : border_base_col; + float draw_y2 = draw_y2_base; + if (is_hovered || is_resized || (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1)) + draw_y2 = draw_y2_full; + inner_window->DrawList->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, 1.0f); + } + } + } + + // Draw outer border + if (table->Flags & ImGuiTableFlags_BordersOuter) + { + // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their parent. + // In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part of it in inner window, + // and the part that's over scrollbars in the outer window..) + // Either solution currently won't allow us to use a larger border size: the border would clipped. + ImRect outer_border = table->OuterRect; + if (inner_window != outer_window) + outer_border.Expand(1.0f); + outer_window->DrawList->AddRect(outer_border.Min, outer_border.Max, table->BorderOuterColor); // IM_COL32(255, 0, 0, 255)); + } + else if (table->Flags & ImGuiTableFlags_BordersH) + { + // Draw bottom-most border + const float border_y = table->RowPosY2; + if (border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y) + inner_window->DrawList->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderOuterColor); + } +} + +static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table) +{ + IM_ASSERT(table->LeftMostStretchedColumnDisplayOrder != -1); + + // Measure existing quantity + float visible_weight = 0.0f; + float visible_width = 0.0f; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsActive || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + visible_weight += column->ResizeWeight; + visible_width += column->WidthRequested; + } + IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f); + + // Apply new weights + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!column->IsActive || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + continue; + column->ResizeWeight = (column->WidthRequested + 0.0f) / visible_width; + } +} + +void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, float column_0_width) +{ + // Constraints + float min_width = TableGetMinColumnWidth(); + float max_width_0 = FLT_MAX; + if (!(table->Flags & ImGuiTableFlags_ScrollX)) + max_width_0 = (table->WorkRect.Max.x - column_0->MinX) - (table->ColumnsActiveCount - (column_0->IndexWithinActiveSet + 1)) * min_width; + column_0_width = ImClamp(column_0_width, min_width, max_width_0); + + // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) + if (column_0->WidthGiven == column_0_width || column_0->WidthRequested == column_0_width) + return; + + ImGuiTableColumn* column_1 = (column_0->NextActiveColumn != -1) ? &table->Columns[column_0->NextActiveColumn] : NULL; + + // In this surprisingly not simple because of how we support mixing Fixed and Stretch columns. + // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. + // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user. + // Scenarios: + // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset. + // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered. + // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Weighted column will always be minimal size. + // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 W2 W3 resize from W1| or W2| --> FIXME + // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1) + // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1) + // - W1 W2 F3 resize from W1| or W2| --> ok + // - W1 F2 W3 resize from W1| or F2| --> FIXME + // - F1 W2 F3 resize from W2| --> ok + // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. (forwarded by Resize Rule 2) + // - W1 F2 F3 resize from F2| --> FIXME should resize F2, F3 and not have effect on W1 (Stretch columns are _before_ the Fixed column). + + // Rules: + // - [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableSetupLayout(). + // - [Resize Rule 2] Resizing from right-side of a Stretch column before a fixed column froward sizing to left-side of fixed column. + // - [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to ensure that our left border won't move. + + if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed) + { + // [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to + // ensure that our left border won't move, which we can do by making sure column_a/column_b resizes cancels each others. + if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed)) + if (table->LeftMostStretchedColumnDisplayOrder != -1 && table->LeftMostStretchedColumnDisplayOrder < column_0->IndexDisplayOrder) + { + // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) + float column_1_width = ImMax(column_1->WidthRequested - (column_0_width - column_0->WidthRequested), min_width); + column_0_width = column_0->WidthRequested + column_1->WidthRequested - column_1_width; + column_1->WidthRequested = column_1_width; + } + + // Apply + //IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthRequested, column_0_width); + column_0->WidthRequested = column_0_width; + } + else if (column_0->Flags & ImGuiTableColumnFlags_WidthStretch) + { + // [Resize Rule 2] + if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed)) + { + float off = (column_0->WidthGiven - column_0_width); + float column_1_width = column_1->WidthGiven + off; + column_1->WidthRequested = ImMax(min_width, column_1_width); + return; + } + + // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) + float column_1_width = ImMax(column_1->WidthRequested - (column_0_width - column_0->WidthRequested), min_width); + column_0_width = column_0->WidthRequested + column_1->WidthRequested - column_1_width; + column_1->WidthRequested = column_1_width; + column_0->WidthRequested = column_0_width; + TableUpdateColumnsWeightFromWidth(table); + } + table->IsSettingsDirty = true; +} + +// Columns where the contents didn't stray off their local clip rectangle can be merged into a same draw command. +// To achieve this we merge their clip rect and make them contiguous in the channel list so they can be merged. +// So here we'll reorder the draw cmd which can be merged, by arranging them into a maximum of 4 distinct groups: +// +// 1 group: 2 groups: 2 groups: 4 groups: +// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze +// [ .. ] or no scroll [ 1. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll +// +// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). +// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group +// based on its position (within frozen rows/columns set or not). +// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect, and they will be merged by the DrawSplitter.Merge() call. +// +// Column channels will not be merged into one of the 1-4 groups in the following cases: +// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). +// Direct ImDrawList calls won't be noticed so if you use them make sure the ImGui:: bounds matches, by e.g. calling SetCursorScreenPos(). +// - The channel uses more than one draw command itself (we drop all our merging stuff here.. we could do better but it's going to be rare) +// +// This function is particularly tricky to understand.. take a breath. +void ImGui::TableDrawMergeChannels(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + ImDrawListSplitter* splitter = &table->DrawSplitter; + const bool is_frozen_v = (table->FreezeRowsCount > 0); + const bool is_frozen_h = (table->FreezeColumnsCount > 0); + + int merge_set_mask = 0; + int merge_set_channels_count[4] = { 0 }; + ImU64 merge_set_channels_mask[4] = { 0 }; + ImRect merge_set_clip_rect[4]; + for (int n = 0; n < IM_ARRAYSIZE(merge_set_clip_rect); n++) + merge_set_clip_rect[n] = ImVec4(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + bool merge_set_all_fit_within_inner_rect = (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0; + + // 1. Scan channels and take note of those who can be merged + for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + { + if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + continue; + const int column_n = table->DisplayOrder[order_n]; + ImGuiTableColumn* column = &table->Columns[column_n]; + + const int merge_set_sub_count = is_frozen_v ? 2 : 1; + for (int merge_set_sub_n = 0; merge_set_sub_n < merge_set_sub_count; merge_set_sub_n++) + { + const int channel_no = (merge_set_sub_n == 0) ? column->DrawChannelRowsBeforeFreeze : column->DrawChannelRowsAfterFreeze; + + // Don't attempt to merge if there are multiple calls within the column + ImDrawChannel* src_channel = &splitter->_Channels[channel_no]; + if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0) + src_channel->_CmdBuffer.pop_back(); + if (src_channel->_CmdBuffer.Size != 1) + continue; + + // Find out the width of this merge set and check if it will fit in our column. + float width_contents; + if (merge_set_sub_count == 1) // No row freeze (same as testing !is_frozen_v) + width_contents = ImMax(column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed); + else if (merge_set_sub_n == 0) // Row freeze: use width before freeze + width_contents = ImMax(column->ContentWidthRowsFrozen, column->ContentWidthHeadersUsed); + else // Row freeze: use width after freeze + width_contents = column->ContentWidthRowsUnfrozen; + if (width_contents > column->WidthGiven && !(column->Flags & ImGuiTableColumnFlags_NoClipX)) + continue; + + const int dst_merge_set_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_set_sub_n : 1); + IM_ASSERT(merge_set_channels_count[dst_merge_set_n] < (int)sizeof(merge_set_channels_mask[dst_merge_set_n]) * 8); + merge_set_mask |= (1 << dst_merge_set_n); + merge_set_channels_mask[dst_merge_set_n] |= (ImU64)1 << channel_no; + merge_set_channels_count[dst_merge_set_n]++; + merge_set_clip_rect[dst_merge_set_n].Add(src_channel->_CmdBuffer[0].ClipRect); + + // If we end with a single set and hosted by the outer window, we'll attempt to merge our draw command with + // the existing outer window command. But we can only do so if our columns all fit within the expected clip rect, + // otherwise clipping will be incorrect when ScrollX is disabled. + // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column don't fit within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect + + // 2019/10/22: (1) This is breaking table_2_draw_calls but I cannot seem to repro what it is attempting to fix... + // cf git fce2e8dc "Fixed issue with clipping when outerwindow==innerwindow / support ScrollH without ScrollV." + // 2019/10/22: (2) Clamping code in TableSetupLayout() seemingly made this not necessary... +#if 0 + if (column->MinX < table->InnerClipRect.Min.x || column->MaxX > table->InnerClipRect.Max.x) + merge_set_all_fit_within_inner_rect = false; +#endif + } + + // Invalidate current draw channel (we don't clear DrawChannelBeforeRowFreeze/DrawChannelAfterRowFreeze solely to facilitate debugging) + column->DrawChannelCurrent = -1; + } + + // 2. Rewrite channel list in our preferred order + if (merge_set_mask != 0) + { + // Use shared temporary storage so the allocation gets amortized + g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - 1); + ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data; + ImU64 remaining_mask = ((splitter->_Count < 64) ? ((ImU64)1 << splitter->_Count) - 1 : ~(ImU64)0) & ~1; + const bool may_extend_clip_rect_to_host_rect = ImIsPowerOfTwo(merge_set_mask); + for (int merge_set_n = 0; merge_set_n < 4; merge_set_n++) + if (merge_set_channels_count[merge_set_n]) + { + ImU64 merge_channels_mask = merge_set_channels_mask[merge_set_n]; + ImRect merge_clip_rect = merge_set_clip_rect[merge_set_n]; + if (may_extend_clip_rect_to_host_rect) + { + //GetOverlayDrawList()->AddRect(table->HostClipRect.Min, table->HostClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 3.0f); + //GetOverlayDrawList()->AddRect(table->InnerClipRect.Min, table->InnerClipRect.Max, IM_COL32(0, 255, 0, 200), 0.0f, ~0, 1.0f); + //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 2.0f); + merge_clip_rect.Add(merge_set_all_fit_within_inner_rect ? table->HostClipRect : table->InnerClipRect); + //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(0, 255, 0, 200)); + } + remaining_mask &= ~merge_channels_mask; + for (int n = 0; n < splitter->_Count && merge_channels_mask != 0; n++) + { + // Copy + overwrite new clip rect + const ImU64 n_mask = (ImU64)1 << n; + if ((merge_channels_mask & n_mask) == 0) + continue; + ImDrawChannel* channel = &splitter->_Channels[n]; + IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect))); + channel->_CmdBuffer[0].ClipRect = *(ImVec4*)&merge_clip_rect; + memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); + merge_channels_mask &= ~n_mask; + } + } + + // Append channels that we didn't reorder at the end of the list + for (int n = 0; n < splitter->_Count && remaining_mask != 0; n++) + { + const ImU64 n_mask = (ImU64)1 << n; + if ((remaining_mask & n_mask) == 0) + continue; + ImDrawChannel* channel = &splitter->_Channels[n]; + memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); + remaining_mask &= ~n_mask; + } + IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size); + memcpy(splitter->_Channels.Data + 1, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - 1) * sizeof(ImDrawChannel)); + } + + // 3. Actually merge (channels using the same clip rect will be contiguous and naturally merged) + splitter->Merge(table->InnerWindow->DrawList); +} + +// We use a default parameter of 'init_width_or_weight == -1' +// ImGuiTableColumnFlags_WidthFixed, width <= 0 --> init width == auto +// ImGuiTableColumnFlags_WidthFixed, width > 0 --> init width == manual +// ImGuiTableColumnFlags_WidthStretch, weight < 0 --> init weight == 1.0f +// ImGuiTableColumnFlags_WidthStretch, weight >= 0 --> init weight == custom +// Use a different API? +void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Can only call TableSetupColumn() after BeginTable()!"); + IM_ASSERT(!table->IsLayoutLocked && "Can only call TableSetupColumn() before first row!"); + IM_ASSERT(table->DeclColumnsCount >= 0 && table->DeclColumnsCount < table->ColumnsCount && "Called TableSetupColumn() too many times!"); + + ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; + table->DeclColumnsCount++; + + column->UserID = user_id; + column->FlagsIn = flags; + column->Flags = TableFixColumnFlags(table, column->FlagsIn); + flags = column->Flags; + + // Initialize defaults + if (table->IsFirstFrame && !table->IsSettingsLoaded) + { + // Init width or weight + // Disable auto-fit if a default fixed width has been specified + if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) + { + column->WidthRequested = init_width_or_weight; + column->AutoFitFrames = 0; + } + if (flags & ImGuiTableColumnFlags_WidthStretch) + { + IM_ASSERT(init_width_or_weight < 0.0f || init_width_or_weight > 0.0f); + column->ResizeWeight = (init_width_or_weight < 0.0f ? 1.0f : init_width_or_weight); + } + else + { + column->ResizeWeight = 1.0f; + } + + // Init default visibility/sort state + if (flags & ImGuiTableColumnFlags_DefaultHide) + column->IsActive = column->NextIsActive = false; + if (flags & ImGuiTableColumnFlags_DefaultSort) + column->SortOrder = 0; // Multiple columns using _DefaultSort will be reordered when building the sort specs. + } + + // Store name (append with zero-terminator in contiguous buffer) + IM_ASSERT(column->NameOffset == -1); + if (label != NULL) + { + column->NameOffset = (ImS16)table->ColumnsNames.size(); + table->ColumnsNames.append(label, label + strlen(label) + 1); + } +} + +// Starts into the first cell of a new row +void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float min_row_height) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + if (table->CurrentRow == -1) + TableUpdateLayout(table); + else if (table->IsInsideRow) + TableEndRow(table); + + table->LastRowFlags = table->RowFlags; + table->RowFlags = row_flags; + TableBeginRow(table); + + // We honor min_height requested by user, but cannot guarantee per-row maximum height as that would essentially require a unique clipping rectangle per-cell. + table->RowPosY2 += min_row_height; + + TableBeginCell(table, 0); +} + +// [Internal] +void ImGui::TableBeginRow(ImGuiTable* table) +{ + ImGuiWindow* window = table->InnerWindow; + IM_ASSERT(!table->IsInsideRow); + + // New row + table->CurrentRow++; + table->CurrentColumn = -1; + table->RowBgColor = IM_COL32_DISABLE; + table->IsInsideRow = true; + + // Begin frozen rows + float next_y1 = table->RowPosY2; + if (table->CurrentRow == 0 && table->FreezeRowsCount > 0) + next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y; + + table->RowPosY1 = table->RowPosY2 = next_y1; + table->RowTextBaseline = 0.0f; + window->DC.CursorMaxPos.y = next_y1; + + // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging. + if (table->RowFlags & ImGuiTableRowFlags_Headers) + { + table->RowBgColor = GetColorU32(ImGuiCol_TableHeaderBg); + if (table->CurrentRow == 0) + table->IsUsingHeaders = true; + } +} + +// [Internal] +void ImGui::TableEndRow(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(window == table->InnerWindow); + IM_ASSERT(table->IsInsideRow); + + TableEndCell(table); + + table->RowPosY2 += table->CellPaddingY; + + // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. + // However it is likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. + window->DC.CursorPos.y = table->RowPosY2; + + // Row background fill + const float bg_y1 = table->RowPosY1; + const float bg_y2 = table->RowPosY2; + + if (table->CurrentRow == 0) + table->LastFirstRowHeight = bg_y2 - bg_y1; + + if (table->CurrentRow >= 0 && bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y) + { + // Decide of background color for the row + ImU32 bg_col = 0; + if (table->RowBgColor != IM_COL32_DISABLE) + bg_col = table->RowBgColor; + else if (table->Flags & ImGuiTableFlags_RowBg) + bg_col = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg); + + // Decide of separating border color + ImU32 border_col = 0; + if (table->CurrentRow != 0 || table->InnerWindow == table->OuterWindow) + { + if (table->Flags & ImGuiTableFlags_BordersH) + { + if (table->CurrentRow == 0 && table->InnerWindow == table->OuterWindow) + border_col = table->BorderOuterColor; + else if (!(table->LastRowFlags & ImGuiTableRowFlags_Headers)) + border_col = table->BorderInnerColor; + } + else + { + if (table->RowFlags & ImGuiTableRowFlags_Headers) + border_col = table->BorderOuterColor; + } + } + + if (bg_col != 0 || border_col != 0) + table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); + + // Draw background + // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle + if (bg_col) + { + ImRect bg_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2); + bg_rect.ClipWith(table->BackgroundClipRect); + if (bg_rect.Min.y < bg_rect.Max.y) + window->DrawList->AddRectFilledMultiColor(bg_rect.Min, bg_rect.Max, bg_col, bg_col, bg_col, bg_col); + } + + // Draw top border + const float border_y = bg_y1; + if (border_col && border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), border_col); + } + + const bool unfreeze_rows = (table->CurrentRow + 1 == table->FreezeRowsCount && table->FreezeRowsCount > 0); + + // Draw bottom border (always strong) + const bool draw_separating_border = unfreeze_rows || (table->RowFlags & ImGuiTableRowFlags_Headers); + if (draw_separating_border) + if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderOuterColor); + + // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) + // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and get the new cursor position. + if (unfreeze_rows) + { + IM_ASSERT(table->IsFreezeRowsPassed == false); + table->IsFreezeRowsPassed = true; + table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); + + ImRect r; + r.Min.x = table->InnerClipRect.Min.x; + r.Min.y = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y); + r.Max.x = table->InnerClipRect.Max.x; + r.Max.y = window->InnerClipRect.Max.y; + table->BackgroundClipRect = r; + + float row_height = table->RowPosY2 - table->RowPosY1; + table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y; + table->RowPosY1 = table->RowPosY2 - row_height; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + column->DrawChannelCurrent = column->DrawChannelRowsAfterFreeze; + column->ClipRect.Min.y = r.Min.y; + } + } + + if (!(table->RowFlags & ImGuiTableRowFlags_Headers)) + table->RowBgColorCounter++; + table->IsInsideRow = false; +} + +// [Internal] This is called a lot, so we need to be mindful of unnecessary overhead! +void ImGui::TableBeginCell(ImGuiTable* table, int column_no) +{ + table->CurrentColumn = column_no; + ImGuiTableColumn* column = &table->Columns[column_no]; + ImGuiWindow* window = table->InnerWindow; + + const float start_x = (table->RowFlags & ImGuiTableRowFlags_Headers) ? column->StartXHeaders : column->StartXRows; + + window->DC.LastItemId = 0; + window->DC.CursorPos = ImVec2(start_x, table->RowPosY1 + table->CellPaddingY); + window->DC.CursorMaxPos.x = window->DC.CursorPos.x; + window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT // FIXME-TABLE: Recurse + window->DC.CurrLineTextBaseOffset = table->RowTextBaseline; + + window->WorkRect.Min.y = window->DC.CursorPos.y; + window->WorkRect.Min.x = column->MinX + table->CellPaddingX1; + window->WorkRect.Max.x = column->MaxX - table->CellPaddingX2; + + // To allow ImGuiListClipper to function we propagate our row height + if (!column->IsActive) + window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2); + + // FIXME-COLUMNS: Setup baseline, preserve across columns (how can we obtain first line baseline tho..) + // window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); + + window->SkipItems = column->IsActive ? table->BackupSkipItems : true; + if (table->Flags & ImGuiTableFlags_NoClipX) + { + table->DrawSplitter.SetCurrentChannel(window->DrawList, 1); + } + else + { + table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); + //window->ClipRect = column->ClipRect; + //IM_ASSERT(column->ClipRect.Max.x > column->ClipRect.Min.x && column->ClipRect.Max.y > column->ClipRect.Min.y); + //window->DrawList->_ClipRectStack.back() = ImVec4(column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y); + //window->DrawList->UpdateClipRect(); + window->DrawList->PopClipRect(); + window->DrawList->PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); + //IMGUI_DEBUG_LOG("%d (%.0f,%.0f)(%.0f,%.0f)\n", column_no, column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y); + window->ClipRect = window->DrawList->_ClipRectStack.back(); + } +} + +// [Internal] +void ImGui::TableEndCell(ImGuiTable* table) +{ + ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + ImGuiWindow* window = table->InnerWindow; + + // Report maximum position so we can infer content size per column. + float* p_max_pos_x; + if (table->RowFlags & ImGuiTableRowFlags_Headers) + p_max_pos_x = &column->ContentMaxPosHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call + else + p_max_pos_x = table->IsFreezeRowsPassed ? &column->ContentMaxPosRowsUnfrozen : &column->ContentMaxPosRowsFrozen; + *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x); + table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y); + + // Propagate text baseline for the entire row + // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one. + table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset); +} + +// Append into the next cell +// FIXME-TABLE: Wrapping to next row should be optional? +bool ImGui::TableNextCell() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + + if (table->CurrentColumn != -1 && table->CurrentColumn + 1 < table->ColumnsCount) + { + TableEndCell(table); + TableBeginCell(table, table->CurrentColumn + 1); + } + else + { + TableNextRow(); + } + + ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + return column->IsActive; +} + +const char* ImGui::TableGetColumnName(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return NULL; + if (column_n < 0) + column_n = table->CurrentColumn; + return TableGetColumnName(table, column_n); +} + +bool ImGui::TableGetColumnIsVisible(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + if (column_n < 0) + column_n = table->CurrentColumn; + return (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) != 0; +} + +int ImGui::TableGetColumnIndex() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return 0; + return table->CurrentColumn; +} + +bool ImGui::TableSetColumnIndex(int column_idx) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + + if (table->CurrentColumn != column_idx) + { + if (table->CurrentColumn != -1) + TableEndCell(table); + IM_ASSERT(column_idx >= 0 && table->ColumnsCount); + TableBeginCell(table, column_idx); + } + + return (table->ActiveMaskByIndex & ((ImU64)1 << column_idx)) != 0; +} + +ImRect ImGui::TableGetCellRect() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + return ImRect(column->MinX, table->RowPosY1, column->MaxX, table->RowPosY2); +} + +const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_no) +{ + ImGuiTableColumn* column = &table->Columns[column_no]; + if (column->NameOffset == -1) + return NULL; + return &table->ColumnsNames.Buf[column->NameOffset]; +} + +void ImGui::PushTableBackground() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiTable* table = g.CurrentTable; + table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); + PushClipRect(table->HostClipRect.Min, table->HostClipRect.Max, false); +} + +void ImGui::PopTableBackground() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiTable* table = g.CurrentTable; + ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); + PopClipRect(); +} + +// FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? +void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + bool want_separator = false; + selected_column_n = ImClamp(selected_column_n, -1, table->ColumnsCount - 1); + + // Sizing + if (table->Flags & ImGuiTableFlags_Resizable) + { + if (ImGuiTableColumn* selected_column = (selected_column_n != -1) ? &table->Columns[selected_column_n] : NULL) + { + const bool can_resize = !(selected_column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && selected_column->IsActive; + if (MenuItem("Size column to fit", NULL, false, can_resize)) + selected_column->AutoFitFrames = 1; + } + + if (MenuItem("Size all columns to fit", NULL)) + { + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->IsActive) + column->AutoFitFrames = 1; + } + } + want_separator = true; + } + + // Ordering + if (table->Flags & ImGuiTableFlags_Reorderable) + { + if (MenuItem("Reset order", NULL, false, !table->IsDefaultDisplayOrder)) + table->IsResetDisplayOrderRequest = true; + want_separator = true; + } + + // Hiding / Visibility + if (table->Flags & ImGuiTableFlags_Hideable) + { + if (want_separator) + Separator(); + want_separator = false; + + PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true); + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + const char* name = TableGetColumnName(table, column_n); + if (name == NULL) + name = ""; + + // Make sure we can't hide the last active column + bool menu_item_active = (column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true; + if (column->IsActive && table->ColumnsActiveCount <= 1) + menu_item_active = false; + if (MenuItem(name, NULL, column->IsActive, menu_item_active)) + column->NextIsActive = !column->IsActive; + } + PopItemFlag(); + } +} + +// This is a helper to output headers based on the column names declared in TableSetupColumn() +// The intent is that advanced users would not need to use this helper and may create their own. +void ImGui::TableAutoHeaders() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table && table->CurrentRow == -1); + + int open_context_popup = INT_MAX; + + // This for loop is constructed to not make use of internal functions, + // as this is intended to be a base template to copy and build from. + TableNextRow(ImGuiTableRowFlags_Headers, GetTextLineHeight()); + const int columns_count = table->ColumnsCount; + for (int column_n = 0; column_n < columns_count; column_n++) + { + if (!TableSetColumnIndex(column_n)) + continue; + + const char* name = TableGetColumnName(column_n); + + // FIXME-TABLE: Test custom user elements +#if 0 + if (column_n < 2) + { + static bool b[10] = {}; + PushID(column_n); + PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + Checkbox("##", &b[column_n]); + PopStyleVar(); + PopID(); + SameLine(0.0f, g.Style.ItemInnerSpacing.x); + } +#endif + + // [DEBUG] + //if (g.IO.KeyCtrl) { static char buf[32]; name = buf; ImGuiTableColumn* c = &table->Columns[column_n]; if (c->Flags & ImGuiTableColumnFlags_WidthStretch) ImFormatString(buf, 32, "%.3f>%.1f", c->ResizeWeight, c->WidthGiven); else ImFormatString(buf, 32, "%.1f", c->WidthGiven); } + + PushID(column_n); // Allow unnamed labels (generally accidental, but let's behave nicely with them) + TableHeader(name); + PopID(); + + // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden + if (IsMouseReleased(1) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + open_context_popup = column_n; + } + + // FIXME-TABLE: This is not user-land code any more... + window->SkipItems = table->BackupSkipItems; + + // Allow opening popup from the right-most section after the last column + // FIXME-TABLE: This is not user-land code any more... perhaps instead we should expose hovered column. + // and allow some sort of row-centric IsItemHovered() for full flexibility? + const float unused_x1 = (table->RightMostActiveColumn != -1) ? table->Columns[table->RightMostActiveColumn].MaxX : table->WorkRect.Min.x; + if (unused_x1 < table->WorkRect.Max.x) + { + // FIXME: We inherit ClipRect/SkipItem from last submitted column (active or not), let's override + window->ClipRect = table->InnerClipRect; + + ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; + window->DC.CursorPos = ImVec2(unused_x1, table->RowPosY1); + ImVec2 size = ImVec2(table->WorkRect.Max.x - window->DC.CursorPos.x, table->RowPosY2 - table->RowPosY1); + if (size.x > 0.0f && size.y > 0.0f) + { + InvisibleButton("##RemainingSpace", size); + window->DC.CursorPos.y -= g.Style.ItemSpacing.y; + window->DC.CursorMaxPos = backup_cursor_max_pos; // Don't feed back into the width of the Header row + + // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden + if (IsMouseReleased(1) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + open_context_popup = -1; + } + + window->ClipRect = window->DrawList->_ClipRectStack.back(); + } + + // Context Menu + if (open_context_popup != INT_MAX) + { + table->IsContextPopupOpen = true; + table->ContextPopupColumn = (ImS8)open_context_popup; + OpenPopup("##TableContextMenu"); + } +} + +// Emit a column header (text + optional sort order) +// We cpu-clip text here so that all columns headers can be merged into a same draw call. +// FIXME-TABLE: Should hold a selection state. +void ImGui::TableHeader(const char* label) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + if (window->SkipItems) + return; + + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table->CurrentColumn != -1); + const int column_n = table->CurrentColumn; + ImGuiTableColumn* column = &table->Columns[column_n]; + + float row_height = GetTextLineHeight(); + ImRect cell_r = TableGetCellRect(); + ImRect work_r = cell_r; + work_r.Min.x = window->DC.CursorPos.x; + work_r.Max.y = work_r.Min.y + row_height; + + // Label + if (label == NULL) + label = ""; + const char* label_end = FindRenderedTextEnd(label); + ImVec2 label_size = CalcTextSize(label, label_end, true); + ImVec2 label_pos = window->DC.CursorPos; + float ellipsis_max = work_r.Max.x; + + // Selectable + PushID(label); + + // FIXME-TABLE: Fix when padding are disabled. + //window->DC.CursorPos.x = column->MinX + table->CellPadding.x; + + // Keep header highlighted when context menu is open. (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) + const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n); + const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld, ImVec2(0.0f, row_height)); + const bool held = IsItemActive(); + window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f; + + // Drag and drop: re-order columns. Frozen columns are not reorderable. + // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone. + if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive) + { + // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x + table->ReorderColumn = (ImS8)column_n; + if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x) + if (column->PrevActiveColumn != -1 && (column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (table->Columns[column->PrevActiveColumn].IndexWithinActiveSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = -1; + if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x) + if (column->NextActiveColumn != -1 && (column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (table->Columns[column->NextActiveColumn].IndexWithinActiveSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = +1; + } + + // Sort order arrow + float w_arrow = 0.0f; + float w_sort_text = 0.0f; + if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort)) + { + const float ARROW_SCALE = 0.75f; + w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);// table->CellPadding.x); + if (column->SortOrder != -1) + { + w_sort_text = 0.0f; + + char sort_order_suf[8]; + if (column->SortOrder > 0) + { + ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), "%d", column->SortOrder + 1); + w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x; + } + + float x = ImMax(cell_r.Min.x, work_r.Max.x - w_arrow - w_sort_text); + ellipsis_max -= w_arrow + w_sort_text; + + float y = label_pos.y; + ImU32 col = GetColorU32(ImGuiCol_Text); + if (column->SortOrder > 0) + { + PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f)); + RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf); + PopStyleColor(); + x += w_sort_text; + } + RenderArrow(window->DrawList, ImVec2(x, y), col, column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Down : ImGuiDir_Up, ARROW_SCALE); + } + + // Handle clicking on column header to adjust Sort Order + if (pressed && table->ReorderColumn != column_n) + TableSortSpecsClickColumn(table, column, g.IO.KeyShift); + } + if (!held && table->ReorderColumn == column_n) + table->ReorderColumn = -1; + + // 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 + row_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size); + + // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging. + // FIXME-TABLE: Clarify policies of how label width and potential decorations (arrows) fit into auto-resize of the column + float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow; + column->ContentMaxPosHeadersUsed = ImMax(column->ContentMaxPosHeadersUsed, work_r.Max.x);// ImMin(max_pos_x, work_r.Max.x)); + column->ContentMaxPosHeadersDesired = ImMax(column->ContentMaxPosHeadersDesired, max_pos_x); + + PopID(); +} + +void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* clicked_column, bool add_to_existing_sort_orders) +{ + if (!(table->Flags & ImGuiTableFlags_MultiSortable)) + add_to_existing_sort_orders = false; + + ImS8 sort_order_max = 0; + if (add_to_existing_sort_orders) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + sort_order_max = ImMax(sort_order_max, table->Columns[column_n].SortOrder); + + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column == clicked_column) + { + // Set new sort direction and sort order + // - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. + // - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. + // - Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert + // the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code. + if (column->SortOrder == -1) + column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); + else + column->SortDirection = (ImU8)((column->SortDirection == ImGuiSortDirection_Ascending) ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending); + if (column->SortOrder == -1 || !add_to_existing_sort_orders) + column->SortOrder = add_to_existing_sort_orders ? sort_order_max + 1 : 0; + } + else + { + if (!add_to_existing_sort_orders) + column->SortOrder = -1; + } + TableFixColumnSortDirection(column); + } + table->IsSettingsDirty = true; + table->IsSortSpecsDirty = true; +} + +// Return NULL if no sort specs. +// Return ->WantSort == true when the specs have changed since the last query. +const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL); + + if (!(table->Flags & ImGuiTableFlags_Sortable)) + return NULL; + + // Flatten sort specs into user facing data + const bool was_dirty = table->IsSortSpecsDirty; + if (was_dirty) + { + TableSortSpecsSanitize(table); + + // Write output + table->SortSpecsData.resize(table->SortSpecsCount); + table->SortSpecs.ColumnsMask = 0x00; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->SortOrder == -1) + continue; + ImGuiTableSortSpecsColumn* sort_spec = &table->SortSpecsData[column->SortOrder]; + sort_spec->ColumnUserID = column->UserID; + sort_spec->ColumnIndex = (ImU8)column_n; + sort_spec->SortOrder = (ImU8)column->SortOrder; + sort_spec->SortSign = (column->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1; + sort_spec->SortDirection = column->SortDirection; + table->SortSpecs.ColumnsMask |= (ImU64)1 << column_n; + } + } + + // User facing data + table->SortSpecs.Specs = table->SortSpecsData.Data; + table->SortSpecs.SpecsCount = table->SortSpecsData.Size; + table->SortSpecs.SpecsChanged = was_dirty; + table->IsSortSpecsDirty = false; + return table->SortSpecs.SpecsCount ? &table->SortSpecs : NULL; +} + +bool ImGui::TableGetColumnIsSorted(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + if (column_n < 0) + column_n = table->CurrentColumn; + ImGuiTableColumn* column = &table->Columns[column_n]; + return (column->SortOrder != -1); +} + +void ImGui::TableSortSpecsSanitize(ImGuiTable* table) +{ + // Clear SortOrder from hidden column and verify that there's no gap or duplicate. + int sort_order_count = 0; + ImU64 sort_order_mask = 0x00; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->SortOrder != -1 && !column->IsActive) + column->SortOrder = -1; + if (column->SortOrder == -1) + continue; + sort_order_count++; + sort_order_mask |= ((ImU64)1 << column->SortOrder); + IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8); + } + + const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1); + const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_MultiSortable); + if (need_fix_linearize || need_fix_single_sort_order) + { + ImU64 fixed_mask = 0x00; + for (int sort_n = 0; sort_n < sort_order_count; sort_n++) + { + // Fix: Rewrite sort order fields if needed so they have no gap or duplicate. + // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1) + int column_with_smallest_sort_order = -1; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1) + if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder) + column_with_smallest_sort_order = column_n; + IM_ASSERT(column_with_smallest_sort_order != -1); + fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order); + table->Columns[column_with_smallest_sort_order].SortOrder = (ImS8)sort_n; + + // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set. + if (need_fix_single_sort_order) + { + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + if (column_n != column_with_smallest_sort_order) + table->Columns[column_n].SortOrder = -1; + break; + } + } + } + + // Fallback default sort order (if no column has the ImGuiTableColumnFlags_DefaultSort flag) + if (sort_order_count == 0 && table->IsFirstFrame) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (!(column->Flags & ImGuiTableColumnFlags_NoSort) && column->IsActive) + { + sort_order_count = 1; + column->SortOrder = 0; + break; + } + } + + table->SortSpecsCount = (ImS8)sort_order_count; +} + +//------------------------------------------------------------------------- +// TABLE - .ini settings +//------------------------------------------------------------------------- +// [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings. +// [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table. +// [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty. +// [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file. +//------------------------------------------------------------------------- + +static ImGuiTableSettings* CreateTableSettings(ImGuiID id, int columns_count) +{ + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings)); + IM_PLACEMENT_NEW(settings) ImGuiTableSettings(); + ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings(); + for (int n = 0; n < columns_count; n++, settings_column++) + IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings(); + settings->ID = id; + settings->ColumnsCount = settings->ColumnsCountMax = (ImS8)columns_count; + return settings; +} + +static ImGuiTableSettings* FindTableSettingsByID(ImGuiID id) +{ + // FIXME-OPT: Might want to store a lookup map for this? + ImGuiContext& g = *GImGui; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + if (settings->ID == id) + return settings; + return NULL; +} + +ImGuiTableSettings* ImGui::TableFindSettings(ImGuiTable* table) +{ + if (table->SettingsOffset == -1) + return NULL; + + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); + IM_ASSERT(settings->ID == table->ID); + if (settings->ColumnsCountMax < table->ColumnsCount) + { + settings->ID = 0; // Ditch storage if we won't fit because of a count change + return NULL; + } + return settings; +} + +void ImGui::TableSaveSettings(ImGuiTable* table) +{ + table->IsSettingsDirty = false; + if (table->Flags & ImGuiTableFlags_NoSavedSettings) + return; + + // Bind or create settings data + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = TableFindSettings(table); + if (settings == NULL) + { + settings = CreateTableSettings(table->ID, table->ColumnsCount); + table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); + } + settings->ColumnsCount = (ImS8)table->ColumnsCount; + + // Serialize ImGuiTableSettings/ImGuiTableColumnSettings --> ImGuiTable/ImGuiTableColumn + IM_ASSERT(settings->ID == table->ID); + IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount); + ImGuiTableColumn* column = table->Columns.Data; + ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); + + // FIXME-TABLE: Logic to avoid saving default widths? + settings->SaveFlags = ImGuiTableFlags_Resizable; + for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++) + { + //column_settings->WidthOrWeight = column->WidthRequested; // FIXME-WIP + column_settings->Index = (ImS8)n; + column_settings->DisplayOrder = column->IndexDisplayOrder; + column_settings->SortOrder = column->SortOrder; + column_settings->SortDirection = column->SortDirection; + column_settings->Visible = column->IsActive; + + // We skip saving some data in the .ini file when they are unnecessary to restore our state + // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet. + if (column->IndexDisplayOrder != n) + settings->SaveFlags |= ImGuiTableFlags_Reorderable;; + if (column_settings->SortOrder != -1) + settings->SaveFlags |= ImGuiTableFlags_Sortable; + if (column_settings->Visible != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) + settings->SaveFlags |= ImGuiTableFlags_Hideable; + } + settings->SaveFlags &= table->Flags; + + MarkIniSettingsDirty(); +} + +void ImGui::TableLoadSettings(ImGuiTable* table) +{ + ImGuiContext& g = *GImGui; + table->IsSettingsRequestLoad = false; + if (table->Flags & ImGuiTableFlags_NoSavedSettings) + return; + + // Bind settings + ImGuiTableSettings* settings; + if (table->SettingsOffset == -1) + { + settings = FindTableSettingsByID(table->ID); + if (settings == NULL) + return; + table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); + } + else + { + settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); + } + table->IsSettingsLoaded = true; + settings->SaveFlags = table->Flags; + + // Serialize ImGuiTable/ImGuiTableColumn --> ImGuiTableSettings/ImGuiTableColumnSettings + ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); + for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++) + { + int column_n = column_settings->Index; + if (column_n < 0 || column_n >= table->ColumnsCount) + continue; + ImGuiTableColumn* column = &table->Columns[column_n]; + //column->WidthRequested = column_settings->WidthOrWeight; // FIXME-WIP + if (column_settings->DisplayOrder != -1) + column->IndexDisplayOrder = column_settings->DisplayOrder; + if (column_settings->SortOrder != -1) + { + column->SortOrder = column_settings->SortOrder; + column->SortDirection = column_settings->SortDirection; + } + column->IsActive = column->NextIsActive = column_settings->Visible; + } + + // FIXME-TABLE: Need to validate .ini data + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->DisplayOrder[table->Columns[column_n].IndexDisplayOrder] = (ImU8)column_n; +} + +void* ImGui::TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +{ + ImGuiID id = 0; + int columns_count = 0; + if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2) + return NULL; + return CreateTableSettings(id, columns_count); +} + +void ImGui::TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +{ + // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" + ImGuiTableSettings* settings = (ImGuiTableSettings*)entry; + int column_n = 0, r = 0, n = 0; + if (sscanf(line, "Column %d%n", &column_n, &r) == 1) { line = ImStrSkipBlank(line + r); } else { return; } + if (column_n < 0 || column_n >= settings->ColumnsCount) + return; + + char c = 0; + ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n; + column->Index = (ImS8)column_n; + if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r) == 1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; } + if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); /* .. */ settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->Visible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } + if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImS8)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; } + if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImS8)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } +} + +void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +{ + ImGuiContext& g = *ctx; + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + { + if (settings->ID == 0) // Skip ditched settings + continue; + + // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped (e.g. Order was unchanged) + const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0; + const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0; + const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0; + const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0; + if (!save_size && !save_visible && !save_order && !save_sort) + continue; + + buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve + buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount); + ImGuiTableColumnSettings* column = settings->GetColumnSettings(); + for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++) + { + // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" + if (column->UserID != 0) + buf->appendf("Column %-2d UserID=%08X", column_n, column->UserID); + else + buf->appendf("Column %-2d", column_n); + if (save_size) buf->appendf(" Width=%d", 0);// (int)settings_column->WidthOrWeight); // FIXME-TABLE + if (save_visible) buf->appendf(" Visible=%d", column->Visible); + if (save_order) buf->appendf(" Order=%d", column->DisplayOrder); + if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^'); + buf->append("\n"); + } + buf->append("\n"); + } +} + +//------------------------------------------------------------------------- +// TABLE - Debugging +//------------------------------------------------------------------------- +// - DebugNodeTable() [Internal] +//------------------------------------------------------------------------- + +void ImGui::DebugNodeTable(ImGuiTable* table) +{ + char buf[256]; + char* p = buf; + const char* buf_end = buf + IM_ARRAYSIZE(buf); + ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name); + bool open = TreeNode(table, "%s", buf); + if (IsItemHovered()) + GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); + if (open) + { + for (int n = 0; n < table->ColumnsCount; n++) + { + ImGuiTableColumn* column = &table->Columns[n]; + const char* name = TableGetColumnName(table, n); + BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" + "Active: %d, DrawChannels: %d,%d\n" + "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" + "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", + n, column->IndexDisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, + column->IsActive, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, + column->WidthGiven, column->WidthRequested, column->ResizeWeight, + column->UserID, column->Flags, + (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", + (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "", + (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) ? "WidthAlwaysAutoResize " : "", + (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : ""); + } + ImGuiTableSettings* settings = TableFindSettings(table); + if (settings && TreeNode("Settings")) + { + BulletText("SaveFlags: 0x%08X", settings->SaveFlags); + BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax); + for (int n = 0; n < settings->ColumnsCount; n++) + { + ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n]; + BulletText("Column %d Order %d SortOrder %d Visible %d UserID 0x%08X WidthOrWeight %.3f", + n, column_settings->DisplayOrder, column_settings->SortOrder, column_settings->Visible, column_settings->UserID, column_settings->WidthOrWeight); + } + TreePop(); + } + TreePop(); + } +} + +//------------------------------------------------------------------------- + + + //------------------------------------------------------------------------- // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc. diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 3a30847d..6954960b 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5999,6 +5999,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // which would be advantageous since most selectable are not selected. if (span_all_columns && window->DC.CurrentColumns) PushColumnsBackground(); + else if ((flags & ImGuiSelectableFlags_SpanAllColumns) && g.CurrentTable) + PushTableBackground(); // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries ImGuiButtonFlags button_flags = 0; @@ -6047,6 +6049,8 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if (span_all_columns && window->DC.CurrentColumns) PopColumnsBackground(); + else if (span_all_columns && g.CurrentTable) + PopTableBackground(); if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb); From a09954bdaf037fdf28ad90f93c38bf0c4a636306 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 19 Dec 2019 14:52:18 +0100 Subject: [PATCH 385/959] Tables: Initial demo code. --- imgui_demo.cpp | 971 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 971 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 71fe735f..89320593 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -132,6 +132,15 @@ Index of this file: #define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) #define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V)) +// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall +#ifndef IMGUI_CDECL +#ifdef _MSC_VER +#define IMGUI_CDECL __cdecl +#else +#define IMGUI_CDECL +#endif +#endif + //----------------------------------------------------------------------------- // [SECTION] Forward Declarations, Helpers //----------------------------------------------------------------------------- @@ -206,6 +215,7 @@ void ImGui::ShowUserGuide() // - ShowDemoWindowWidgets() // - ShowDemoWindowLayout() // - ShowDemoWindowPopups() +// - ShowDemoWindowTables() // - ShowDemoWindowColumns() // - ShowDemoWindowMisc() //----------------------------------------------------------------------------- @@ -215,6 +225,7 @@ void ImGui::ShowUserGuide() static void ShowDemoWindowWidgets(); static void ShowDemoWindowLayout(); static void ShowDemoWindowPopups(); +static void ShowDemoWindowTables(); static void ShowDemoWindowColumns(); static void ShowDemoWindowMisc(); @@ -472,6 +483,7 @@ void ImGui::ShowDemoWindow(bool* p_open) ShowDemoWindowWidgets(); ShowDemoWindowLayout(); ShowDemoWindowPopups(); + ShowDemoWindowTables(); ShowDemoWindowColumns(); ShowDemoWindowMisc(); @@ -3211,6 +3223,962 @@ static void ShowDemoWindowPopups() } } +// Dummy data structure that we use for the Table demo. +// (pre-C++11 doesn't allow us to instantiate ImVector template if this structure if defined inside the demo function) +namespace +{ +// We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code. +// This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. +// But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) +// If you don't use sorting, you will generally never care about giving column an ID! +enum MyItemColumnID +{ + MyItemColumnID_ID, + MyItemColumnID_Name, + MyItemColumnID_Action, + MyItemColumnID_Quantity, + MyItemColumnID_Description +}; + +struct MyItem +{ + int ID; + const char* Name; + int Quantity; + + // We have a problem which is affecting _only this demo_ and should not affect your code: + // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(), + // however qsort doesn't allow passing user data to comparing function. + // As a workaround, we are storing the sort specs in a static/global for the comparing function to access. + // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global. + static const ImGuiTableSortSpecs* s_current_sort_specs; + + // Compare function to be used by qsort() + static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs) + { + const MyItem* a = (const MyItem*)lhs; + const MyItem* b = (const MyItem*)rhs; + for (int n = 0; n < s_current_sort_specs->SpecsCount; n++) + { + // Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn() + // We could also choose to identify columns based on their index (sort_spec->ColumnIndex), which is simpler! + const ImGuiTableSortSpecsColumn* sort_spec = &s_current_sort_specs->Specs[n]; + int delta = 0; + switch (sort_spec->ColumnUserID) + { + case MyItemColumnID_ID: delta = (a->ID - b->ID); break; + case MyItemColumnID_Name: delta = (strcmp(a->Name, b->Name)); break; + case MyItemColumnID_Quantity: delta = (a->Quantity - b->Quantity); break; + case MyItemColumnID_Description: delta = (strcmp(a->Name, b->Name)); break; + default: IM_ASSERT(0); break; + } + if (delta < 0) + return -1 * sort_spec->SortSign; + if (delta > 0) + return +1 * sort_spec->SortSign; + } + + // qsort() is instable so always return a way to differenciate 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); + } +}; +const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL; +} + +static void ShowDemoWindowTables() +{ + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (!ImGui::CollapsingHeader("Tables")) + return; + + ImGui::PushID("Tables"); + + int open_action = -1; + if (ImGui::Button("Open all")) + open_action = 1; + ImGui::SameLine(); + if (ImGui::Button("Close all")) + open_action = 0; + ImGui::SameLine(); + + // Options + static bool disable_indent = false; + ImGui::Checkbox("Disable tree indentation", &disable_indent); + ImGui::SameLine(); + HelpMarker("Disable the indenting of tree nodes so demo tables can use the full window width."); + ImGui::Separator(); + if (disable_indent) + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f); + + // About Styling of tables + // Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs. + // There are however a few settings that a shared and part of the ImGuiStyle structure: + // style.CellPadding // Padding within each cell + // style.Colors[ImGuiCol_TableHeaderBg] // Table header background + // style.Colors[ImGuiCol_TableRowBg] // Table row background when ImGuiTableFlags_RowBg is enabled (even rows) + // style.Colors[ImGuiCol_TableRowBgAlt] // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) + + // Demos + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Basic")) + { + // Here we will showcase 4 different ways to output a table. They are very simple variations of a same thing! + + // Basic use of tables using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. + // In many situations, this is the most flexible and easy to use pattern. + HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop."); + if (ImGui::BeginTable("##table1", 3)) + { + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Row %d Column %d", row, column); + } + } + ImGui::EndTable(); + } + + // This essentially the same as above, except instead of using a for loop we call TableSetColumnIndex() manually. + // Sometimes this makes more sense. + HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, manually."); + if (ImGui::BeginTable("##table2", 3)) + { + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::Text("Row %d", row); + ImGui::TableSetColumnIndex(1); + ImGui::Text("Some contents"); + ImGui::TableSetColumnIndex(2); + ImGui::Text("123.456"); + } + ImGui::EndTable(); + } + + // Another subtle variant, we call TableNextCell() _before_ each cell. At the end of a row, TableNextCell() will create a new row. + // Note that we don't call TableNextRow() here! + // If we want to call TableNextRow(), then we don't need to call TableNextCell() for the first cell. + HelpMarker("Only using TableNextCell(), which tends to be convenient for tables where every cells contains the same type of contents.\nThis is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition."); + if (ImGui::BeginTable("##table4", 3)) + { + for (int item = 0; item < 14; item++) + { + ImGui::TableNextCell(); + ImGui::Text("Item %d", item); + } + ImGui::EndTable(); + } + + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("With borders, background")) + { + // Expose a few Borders related flags interactively + static ImGuiTableFlags flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; + static bool display_width = false; + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&flags, ImGuiTableFlags_Borders); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersOuter\n | ImGuiTableFlags_BordersV\n | ImGuiTableFlags_BordersH"); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); + ImGui::Checkbox("Debug Display width", &display_width); + + if (ImGui::BeginTable("##table1", 3, flags)) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + if (display_width) + { + ImVec2 p = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + float x1 = p.x; + float x2 = ImGui::GetWindowPos().x + ImGui::GetContentRegionMax().x; + float x3 = draw_list->GetClipRectMax().x; + float y2 = p.y + ImGui::GetTextLineHeight(); + draw_list->AddLine(ImVec2(x1, y2), ImVec2(x3, y2), IM_COL32(255, 255, 0, 255)); // Hard clipping limit + draw_list->AddLine(ImVec2(x1, y2), ImVec2(x2, y2), IM_COL32(255, 0, 0, 255)); // Normal limit + ImGui::Text("w=%.2f", x2 - x1); + } + else + { + ImGui::Text("Hello %d,%d", row, column); + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Resizable, stretch")) + { + // By default, if we don't enable ScrollX the sizing policy for each columns is "Stretch" + // Each columns maintain a sizing weight, and they will occupy all available width. + static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV; + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::SameLine(); HelpMarker("Using the _Resizable flag automatically enables the _BordersV flag as well."); + + if (ImGui::BeginTable("##table1", 3, flags)) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", row, column); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Resizable, fixed")) + { + // Here we use ImGuiTableFlags_SizingPolicyFixedX (even though _ScrollX is not set) + // So columns will adopt the "Fixed" policy and will maintain a fixed weight regardless of the whole available width. + // If there is not enough available width to fit all columns, they will however be resized down. + // FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings + HelpMarker("Using _Resizable + _SizingPolicyFixedX flags.\nFixed-width columns generally makes more sense if you want to use horizontal scrolling."); + static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV; + //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); // FIXME-TABLE: Explain or fix the effect of enable Scroll on outer_size + if (ImGui::BeginTable("##table1", 3, flags)) + { + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", row, column); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Resizable, mixed")) + { + HelpMarker("Using columns flag to alter resizing policy on a per-column basis."); + static ImGuiTableFlags flags = ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); // FIXME-TABLE: Explain or fix the effect of enable Scroll on outer_size + + if (ImGui::BeginTable("##table1", 3, flags, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 6))) + { + ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);// | ImGuiTableColumnFlags_NoResize); + ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableAutoHeaders(); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %d,%d", (column == 2) ? "Stretch" : "Fixed", row, column); + } + } + ImGui::EndTable(); + } + if (ImGui::BeginTable("##table2", 6, flags, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 6))) + { + ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide); + ImGui::TableSetupColumn("DDD", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("EEE", ImGuiTableColumnFlags_WidthStretch); + ImGui::TableSetupColumn("FFF", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide); + ImGui::TableAutoHeaders(); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 6; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%s %d,%d", (column >= 3) ? "Stretch" : "Fixed", row, column); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Reorderable, hideable, with headers")) + { + HelpMarker("Click and drag column headers to reorder columns.\n\nYou can also right-click on a header to open a context menu."); + static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV; + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", (unsigned int*)&flags, ImGuiTableFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", (unsigned int*)&flags, ImGuiTableFlags_Hideable); + + if (ImGui::BeginTable("##table1", 3, flags)) + { + // Submit columns name with TableSetupColumn() and call TableAutoHeaders() to create a row with a header in each column. + // (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.) + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableAutoHeaders(); + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", row, column); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Vertical scrolling, with clipping")) + { + HelpMarker("Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\nWe also demonstrate using ImGuiListClipper to virtualize the submission of many items."); + ImVec2 size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 7); + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); + + if (ImGui::BeginTable("##table1", 3, flags, size)) + { + ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None); + ImGui::TableAutoHeaders(); + ImGuiListClipper clipper; + clipper.Begin(1000); + while (clipper.Step()) + { + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", row, column); + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Horizontal scrolling")) + { + HelpMarker("When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingPolicyFixedX, as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\nAlso note that as of the current version, you will almost always want to enable ScrollY along with ScrollX, because the container window won't automatically extend vertically to fix contents (this may be improved in future versions)."); + ImVec2 size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 10); + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_ScrollFreezeLeftColumn | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); + + if (ImGui::BeginTable("##table1", 7, flags, size)) + { + ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of ImGuiTableFlags_ScrollFreezeLeftColumn + ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Four", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Five", ImGuiTableColumnFlags_None); + ImGui::TableSetupColumn("Six", ImGuiTableColumnFlags_None); + ImGui::TableAutoHeaders(); + for (int row = 0; row < 20; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 7; column++) + { + ImGui::TableSetColumnIndex(column); + if (column == 0) + ImGui::Text("Line %d", row); + else + ImGui::Text("Hello world %d,%d", row, column); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Columns flags")) + { + // Create a first table just to show all the options/flags we want to make visible in our example! + const int column_count = 3; + const char* column_names[column_count] = { "One", "Two", "Three" }; + static ImGuiTableColumnFlags column_flags[column_count] = { ImGuiTableColumnFlags_DefaultSort, ImGuiTableColumnFlags_None, ImGuiTableColumnFlags_DefaultHide }; + + if (ImGui::BeginTable("##flags", column_count, ImGuiTableFlags_None)) + { + for (int column = 0; column < column_count; column++) + { + ImGui::TableNextCell(); + // Make the UI compact because there are so many fields + ImGuiStyle& style = ImGui::GetStyle(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, 2)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, 2)); + ImGui::PushID(column); + ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation + ImGui::Text("Column '%s'", column_names[column]); + ImGui::CheckboxFlags("_NoResize", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoResize); + ImGui::CheckboxFlags("_NoClipX", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoClipX); + ImGui::CheckboxFlags("_NoHide", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoHide); + ImGui::CheckboxFlags("_DefaultSort", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_DefaultSort); + ImGui::CheckboxFlags("_DefaultHide", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_DefaultHide); + ImGui::CheckboxFlags("_NoSort", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoSort); + ImGui::CheckboxFlags("_NoSortAscending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoSortAscending); + ImGui::CheckboxFlags("_NoSortDescending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoSortDescending); + ImGui::CheckboxFlags("_PreferSortAscending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_PreferSortAscending); + ImGui::CheckboxFlags("_PreferSortDescending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_PreferSortDescending); + ImGui::PopID(); + ImGui::PopStyleVar(2); + } + ImGui::EndTable(); + } + + // Create the real table we care about for the example! + const ImGuiTableFlags flags = ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable; + if (ImGui::BeginTable("##table1", column_count, flags)) + { + for (int column = 0; column < column_count; column++) + ImGui::TableSetupColumn(column_names[column], column_flags[column]); + ImGui::TableAutoHeaders(); + for (int row = 0; row < 8; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < column_count; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %s", ImGui::TableGetColumnName(column)); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Recursive")) + { + HelpMarker("This demonstrate embedding a table into another table cell."); + + if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + { + ImGui::TableSetupColumn("A0"); + ImGui::TableSetupColumn("A1"); + ImGui::TableAutoHeaders(); + + ImGui::TableNextRow(); ImGui::Text("A0 Cell 0"); + { + float rows_height = ImGui::GetTextLineHeightWithSpacing() * 2; + if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + { + ImGui::TableSetupColumn("B0"); + ImGui::TableSetupColumn("B1"); + ImGui::TableAutoHeaders(); + + ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::Text("B0 Cell 0"); + ImGui::TableNextCell(); + ImGui::Text("B0 Cell 1"); + ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::Text("B1 Cell 0"); + ImGui::TableNextCell(); + ImGui::Text("B1 Cell 1"); + + ImGui::EndTable(); + } + } + ImGui::TableNextCell(); ImGui::Text("A0 Cell 1"); + ImGui::TableNextRow(); ImGui::Text("A1 Cell 0"); + ImGui::TableNextCell(); ImGui::Text("A1 Cell 1"); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Sizing policies, cell contents")) + { + HelpMarker("This section allows you to interact and see the effect of StretchX vs FixedX sizing policies depending on whether Scroll is enabled and the contents of your columns."); + enum ContentsType { CT_ShortText, CT_LongText, CT_Button, CT_StretchButton, CT_InputText }; + static int contents_type = CT_ShortText; + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); + ImGui::Combo("Contents", &contents_type, "Short Text\0Long Text\0Button\0Stretch Button\0InputText\0"); + + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); + if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) + flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyStretchX); // Can't specify both sizing polices so we clear the other + ImGui::SameLine(); HelpMarker("Default if _ScrollX if disabled."); + if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyFixedX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyFixedX)) + flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyFixedX); // Can't specify both sizing polices so we clear the other + ImGui::SameLine(); HelpMarker("Default if _ScrollX if enabled."); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClipX", (unsigned int*)&flags, ImGuiTableFlags_NoClipX); + + if (ImGui::BeginTable("##3ways", 3, flags, ImVec2(0, 100))) + { + for (int row = 0; row < 10; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + char label[32]; + static char text_buf[32] = ""; + sprintf(label, "Hello %d,%d", row, column); + switch (contents_type) + { + case CT_ShortText: ImGui::TextUnformatted(label); break; + case CT_LongText: ImGui::Text("Some longer text %d,%d\nOver two lines..", row, column); break; + case CT_Button: ImGui::Button(label); break; + case CT_StretchButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break; + case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText(label, text_buf, IM_ARRAYSIZE(text_buf)); break; + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Compact table")) + { + // FIXME-TABLE: Vertical border not overridden the same way as horizontal one + HelpMarker("Setting style.CellPadding to (0,0)."); + + static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); + + static bool no_widget_frame = false; + ImGui::Checkbox("no_widget_frame", &no_widget_frame); + + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0, 0)); + if (ImGui::BeginTable("##3ways", 3, flags)) + { + for (int row = 0; row < 10; row++) + { + static char text_buf[32] = ""; + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::PushID(row * 3 + column); + if (no_widget_frame) + ImGui::PushStyleColor(ImGuiCol_FrameBg, 0); + ImGui::InputText("##cell", text_buf, IM_ARRAYSIZE(text_buf)); + if (no_widget_frame) + ImGui::PopStyleColor(); + ImGui::PopID(); + } + } + ImGui::EndTable(); + } + ImGui::PopStyleVar(); + ImGui::TreePop(); + } + + static const char* template_items_names[] = + { + "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", + "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot" + }; + + // This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting. + // Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified) + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Sorting")) + { + HelpMarker("Use Shift+Click to sort on multiple columns"); + + // Create item list + static ImVector items; + if (items.Size == 0) + { + items.resize(50, MyItem()); + for (int n = 0; n < items.Size; n++) + { + const int template_n = n % IM_ARRAYSIZE(template_items_names); + MyItem& item = items[n]; + item.ID = n; + item.Name = template_items_names[template_n]; + item.Quantity = (n * n - n) % 20; // Assign default quantities + } + } + + static ImGuiTableFlags flags = + ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_MultiSortable + | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV + | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollFreezeTopRow; + if (ImGui::BeginTable("##table", 4, flags, ImVec2(0, 250), 0.0f)) + { + // Declare columns + // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + // Demonstrate using a mixture of flags among available sort-related flags: + // - ImGuiTableColumnFlags_DefaultSort + // - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending + // - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Name); + ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Action); + ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, -1.0f, MyItemColumnID_Quantity); + + // Sort our data if sort specs have been changed! + if (const ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs()) + if (sorts_specs->SpecsChanged && items.Size > 1) + { + MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. + qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); + } + + // Display data + ImGui::TableAutoHeaders(); + ImGuiListClipper clipper; + clipper.Begin(items.Size); + while (clipper.Step()) + for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) + { + MyItem* item = &items[row_n]; + ImGui::PushID(item->ID); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::Text("%04d", item->ID); + ImGui::TableSetColumnIndex(1); + ImGui::TextUnformatted(item->Name); + ImGui::TableSetColumnIndex(2); + ImGui::SmallButton("None"); + ImGui::TableSetColumnIndex(3); + ImGui::Text("%d", item->Quantity); + ImGui::PopID(); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Advanced")) + { + static ImGuiTableFlags flags = + ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_MultiSortable + | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders + | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY + | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_ScrollFreezeLeftColumn + | ImGuiTableFlags_SizingPolicyFixedX + ; + + enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_Selectable }; + static int contents_type = CT_Button; + const char* contents_type_names[] = { "Text", "Button", "SmallButton", "Selectable" }; + + static int items_count = IM_ARRAYSIZE(template_items_names); + static ImVec2 outer_size_value = ImVec2(0, 250); + static float row_min_height = 0.0f; // Auto + static float inner_width_without_scroll = 0.0f; // Fill + static float inner_width_with_scroll = 0.0f; // Auto-extend + static bool outer_size_enabled = true; + static bool lock_left_column_visibility = false; + static bool show_headers = true; + static bool show_wrapped_text = false; + static ImGuiTextFilter filter; + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which affects sizing + if (ImGui::TreeNodeEx("Options")) + { + // Make the UI compact because there are so many fields + ImGuiStyle& style = ImGui::GetStyle(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, 1)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, 2)); + ImGui::PushItemWidth(200); + + ImGui::BulletText("Features:"); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", (unsigned int*)&flags, ImGuiTableFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", (unsigned int*)&flags, ImGuiTableFlags_Hideable); + ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", (unsigned int*)&flags, ImGuiTableFlags_Sortable); + ImGui::CheckboxFlags("ImGuiTableFlags_MultiSortable", (unsigned int*)&flags, ImGuiTableFlags_MultiSortable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", (unsigned int*)&flags, ImGuiTableFlags_NoSavedSettings); + ImGui::Unindent(); + + ImGui::BulletText("Decoration:"); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersFullHeight", (unsigned int*)&flags, ImGuiTableFlags_BordersFullHeight); + ImGui::Unindent(); + + ImGui::BulletText("Padding, Sizing:"); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClipX", (unsigned int*)&flags, ImGuiTableFlags_NoClipX); + if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) + flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyStretchX); // Can't specify both sizing polices so we clear the other + ImGui::SameLine(); HelpMarker("[Default if ScrollX is off]\nFit all columns within available width (or specified inner_width). Fixed and Stretch columns allowed."); + if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyFixedX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyFixedX)) + flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyFixedX); // Can't specify both sizing polices so we clear the other + ImGui::SameLine(); HelpMarker("[Default if ScrollX is on]\nEnlarge as needed: enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rectangle. Only Fixed columns allowed. Stretched columns will calculate their width assuming no scrolling."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHeadersWidth", (unsigned int*)&flags, ImGuiTableFlags_NoHeadersWidth); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", (unsigned int*)&flags, ImGuiTableFlags_NoHostExtendY); + ImGui::Unindent(); + + ImGui::BulletText("Scrolling:"); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); + + // For the purpose of our "advanced" demo, we expose the 3 freezing variants on both axises instead of only exposing the most common flag. + //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); + //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); + int freeze_row_count = (flags & ImGuiTableFlags_ScrollFreezeRowsMask_) >> ImGuiTableFlags_ScrollFreezeRowsShift_; + int freeze_col_count = (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) >> ImGuiTableFlags_ScrollFreezeColumnsShift_; + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + if (ImGui::DragInt("ImGuiTableFlags_ScrollFreezeTopRow/2Rows/3Rows", &freeze_row_count, 0.2f, 0, 3)) + if (freeze_row_count >= 0 && freeze_row_count <= 3) + flags = (flags & ~ImGuiTableFlags_ScrollFreezeRowsMask_) | (freeze_row_count << ImGuiTableFlags_ScrollFreezeRowsShift_); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + if (ImGui::DragInt("ImGuiTableFlags_ScrollFreezeLeftColumn/2Columns/3Columns", &freeze_col_count, 0.2f, 0, 3)) + if (freeze_col_count >= 0 && freeze_col_count <= 3) + flags = (flags & ~ImGuiTableFlags_ScrollFreezeColumnsMask_) | (freeze_col_count << ImGuiTableFlags_ScrollFreezeColumnsShift_); + + ImGui::Unindent(); + + ImGui::BulletText("Other:"); + ImGui::Indent(); + ImGui::DragFloat2("##OuterSize", &outer_size_value.x); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Checkbox("outer_size", &outer_size_enabled); + ImGui::SameLine(); + HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set), the table is output directly in the parent window. OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendV is set)."); + + // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. + // To facilitate experimentation we expose two values and will select the right one depending on active flags. + if (flags & ImGuiTableFlags_ScrollX) + ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX); + else + ImGui::DragFloat("inner_width (when ScrollX inactive)", &inner_width_without_scroll, 1.0f, 0.0f, FLT_MAX); + ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX); + ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); + ImGui::DragInt("items_count", &items_count, 0.1f, 0, 5000); + ImGui::Combo("contents_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names)); + filter.Draw("filter"); + ImGui::Checkbox("show_headers", &show_headers); + ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); + ImGui::Checkbox("lock_left_column_visibility", &lock_left_column_visibility); + ImGui::Unindent(); + + ImGui::PopItemWidth(); + ImGui::PopStyleVar(2); + ImGui::Spacing(); + ImGui::TreePop(); + } + + // Recreate/reset item list if we changed the number of items + static ImVector items; + static ImVector selection; + static bool items_need_sort = false; + if (items.Size != items_count) + { + items.resize(items_count, MyItem()); + for (int n = 0; n < items_count; n++) + { + const int template_n = n % IM_ARRAYSIZE(template_items_names); + MyItem& item = items[n]; + item.ID = n; + item.Name = template_items_names[template_n]; + item.Quantity = (template_n == 3) ? 10 : (template_n == 4) ? 20 : 0; // Assign default quantities + } + } + + const ImDrawList* parent_draw_list = ImGui::GetWindowDrawList(); + const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size; + + const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : inner_width_without_scroll; + if (ImGui::BeginTable("##table", 5, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use)) + { + // Declare columns + // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | (lock_left_column_visibility ? ImGuiTableColumnFlags_NoHide : 0), -1.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Name); + ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Action); + ImGui::TableSetupColumn("Quantity Long Label", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 1.0f, MyItemColumnID_Quantity);// , ImGuiTableColumnFlags_None | ImGuiTableColumnFlags_WidthAlwaysAutoResize); + ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_WidthStretch, 1.0f, MyItemColumnID_Description);// , ImGuiTableColumnFlags_WidthAlwaysAutoResize); + + // Sort our data if sort specs have been changed! + const ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs(); + if (sorts_specs && sorts_specs->SpecsChanged) + items_need_sort = true; + if (sorts_specs && items_need_sort && items.Size > 1) + { + MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. + qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); + } + items_need_sort = false; + + // Take note of whether we are currently sorting based on the Quantity field, + // we will use this to trigger sorting when we know the data of this column has been modified. + const bool sorts_specs_using_quantity = ImGui::TableGetColumnIsSorted(3); + + // Show headers + if (show_headers) + ImGui::TableAutoHeaders(); + + // Show data + // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? + ImGui::PushButtonRepeat(true); +#if 1 + ImGuiListClipper clipper; + clipper.Begin(items.Size); + while (clipper.Step()) + { + for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) +#else + { + for (int row_n = 0; row_n < items_count; n++) +#endif + { + MyItem* item = &items[row_n]; + if (!filter.PassFilter(item->Name)) + continue; + + const bool item_is_selected = selection.contains(item->ID); + ImGui::PushID(item->ID); + ImGui::TableNextRow(ImGuiTableRowFlags_None, row_min_height); + + // For the demo purpose we can select among different type of items submitted in the first column + char label[32]; + sprintf(label, "%04d", item->ID); + if (contents_type == CT_Text) + ImGui::TextUnformatted(label); + else if (contents_type == CT_Button) + ImGui::Button(label); + else if (contents_type == CT_SmallButton) + ImGui::SmallButton(label); + else if (contents_type == CT_Selectable) + { + if (ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap, ImVec2(0, row_min_height))) + { + if (ImGui::GetIO().KeyCtrl) + { + if (item_is_selected) + selection.find_erase_unsorted(item->ID); + else + selection.push_back(item->ID); + } + else + { + selection.clear(); + selection.push_back(item->ID); + } + } + } + + ImGui::TableNextCell(); + ImGui::TextUnformatted(item->Name); + + // Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity, + // and we are currently sorting on the column showing the Quantity. + // To avoid triggering a sort while holding the button, we only trigger it when the button has been released. + // You will probably need a more advanced system in your code if you want to automatically sort when a specific entry changes. + if (ImGui::TableNextCell()) + { + if (ImGui::SmallButton("Chop")) { item->Quantity += 1; } + if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } + ImGui::SameLine(); + if (ImGui::SmallButton("Eat")) { item->Quantity -= 1; } + if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } + } + + ImGui::TableNextCell(); + ImGui::Text("%d", item->Quantity); + + ImGui::TableNextCell(); + if (show_wrapped_text) + ImGui::TextWrapped("Lorem ipsum dolor sit amet"); + else + ImGui::Text("Lorem ipsum dolor sit amet"); + + ImGui::PopID(); + } + } + ImGui::PopButtonRepeat(); + + const ImVec2 table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY()); + const ImVec2 table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY()); + const ImDrawList* table_draw_list = ImGui::GetWindowDrawList(); + ImGui::EndTable(); + + static bool show_debug_details = false; + ImGui::Checkbox("Debug details", &show_debug_details); + if (show_debug_details) + { + ImGui::SameLine(0.0f, 0.0f); + const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size; + if (table_draw_list == parent_draw_list) + ImGui::Text(": DrawCmd: +%d (in same window)", table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count); + else + ImGui::Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)", + table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y); + } + } + ImGui::TreePop(); + } + + if (disable_indent) + ImGui::PopStyleVar(); + ImGui::PopID(); +} + +// 2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful Tables API! static void ShowDemoWindowColumns() { if (!ImGui::CollapsingHeader("Columns")) @@ -3225,6 +4193,8 @@ static void ShowDemoWindowColumns() if (disable_indent) ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f); + ImGui::TextWrapped("Note: Columns are under-featured and not maintained. Prefer using the more flexible and powerful Tables API!"); + // Basic columns if (ImGui::TreeNode("Basic")) { @@ -3944,6 +4914,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) 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("CellPadding", (float*)&style.CellPadding, 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"); From e06a36ab120b69b91b6a66c12c7a925eb4b9f942 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 26 Dec 2019 11:15:56 +0100 Subject: [PATCH 386/959] Tables: Support for multiple Tables using same id where most settings are synced. (some minor one-frame lack of sync when e.g. toggling visibility in context menu) --- imgui_internal.h | 7 ++++- imgui_tables.cpp | 78 ++++++++++++++++++++++++++++++++---------------- 2 files changed, 58 insertions(+), 27 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 5ec83845..6cddf0c9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1891,6 +1891,8 @@ struct ImGuiTable int ColumnsActiveCount; // Number of non-hidden columns (<= ColumnsCount) int CurrentColumn; int CurrentRow; + ImS16 InstanceNo; // Count of BeginTable() calls with same ID in the same frame (generally 0) + ImS16 InstanceInteracted; float RowPosY1; float RowPosY2; float RowTextBaseline; @@ -1910,6 +1912,7 @@ struct ImGuiTable float LastFirstRowHeight; // Height of first row from last frame float ColumnsTotalWidth; float InnerWidth; + float ResizedColumnNextWidth; ImRect OuterRect; // Note: OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). ImRect WorkRect; ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. @@ -1925,7 +1928,8 @@ struct ImGuiTable ImS8 DeclColumnsCount; // Count calls to TableSetupColumn() ImS8 HoveredColumnBody; // [DEBUG] Unlike HoveredColumnBorder this doesn't fulfill all Hovering rules properly. Used for debugging/tools for now. ImS8 HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). - ImS8 ResizedColumn; // Index of column being resized. + ImS8 ResizedColumn; // Index of column being resized. Reset by InstanceNo==0. + ImS8 HeadHeaderColumn; // Index of column header being held. ImS8 LastResizedColumn; ImS8 ReorderColumn; // Index of column being reordered. (not cleared) ImS8 ReorderColumnDir; // -1 or +1 @@ -1957,6 +1961,7 @@ struct ImGuiTable { memset(this, 0, sizeof(*this)); SettingsOffset = -1; + InstanceInteracted = -1; LastFrameActive = -1; LastResizedColumn = -1; ContextPopupColumn = -1; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 657ccad4..57b049ba 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -158,9 +158,8 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f); ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size); - // If an outer size is specified ahead we will be able to early out when not visible, - // The exact rules here can evolve. - if (use_child_window && IsClippedEx(outer_rect, id, false)) + // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping rules may evolve. + if (use_child_window && IsClippedEx(outer_rect, 0, false)) { ItemSize(outer_rect); return false; @@ -173,9 +172,16 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags // Acquire storage for the table ImGuiTable* table = g.Tables.GetOrAddByKey(id); const ImGuiTableFlags table_last_flags = table->Flags; + const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceNo + 1; + const ImGuiID instance_id = id + instance_no; + if (instance_no > 0) + IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID"); + + // Initialize table->ID = id; table->Flags = flags; table->IsFirstFrame = (table->LastFrameActive == -1); + table->InstanceNo = (ImS16)instance_no; table->LastFrameActive = g.FrameCount; table->OuterWindow = table->InnerWindow = outer_window; table->ColumnsCount = columns_count; @@ -203,7 +209,7 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags // Create scrolling region (without border = zero window padding) ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; - BeginChildEx(str_id, id, table->OuterRect.GetSize(), false, child_flags); + BeginChildEx(str_id, instance_id, table->OuterRect.GetSize(), false, child_flags); table->InnerWindow = g.CurrentWindow; table->WorkRect = table->InnerWindow->WorkRect; table->OuterRect = table->InnerWindow->Rect(); @@ -211,7 +217,7 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags else { // WorkRect.Max will grow as we append contents. - PushID(id); + PushID(instance_id); } const bool has_cell_padding_x = (flags & (ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV)) != 0; @@ -244,7 +250,6 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags table->HoveredColumnBody = -1; table->HoveredColumnBorder = -1; table->RightMostActiveColumn = -1; - table->LeftMostStretchedColumnDisplayOrder = -1; table->IsFirstFrame = false; // FIXME-TABLE FIXME-STYLE: Using opaque colors facilitate overlapping elements of the grid @@ -291,18 +296,36 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags if (table->IsFirstFrame || table->IsSettingsRequestLoad) TableLoadSettings(table); + // Handle resizing request + // (We process this at the first beginning of the frame) + // FIXME-TABLE: Preserve contents width _while resizing down_ until releasing. + // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling. + if (table->InstanceNo == 0) + { + if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX) + TableSetColumnWidth(table, &table->Columns[table->ResizedColumn], table->ResizedColumnNextWidth); + table->ResizedColumnNextWidth = FLT_MAX; + table->ResizedColumn = -1; + } + // Handle reordering request // Note: we don't clear ReorderColumn after handling the request. - if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0) - { - IM_ASSERT(table->ReorderColumnDir == -1 || table->ReorderColumnDir == +1); - IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); - ImGuiTableColumn* dragged_column = &table->Columns[table->ReorderColumn]; - ImGuiTableColumn* target_column = &table->Columns[(table->ReorderColumnDir == -1) ? dragged_column->PrevActiveColumn : dragged_column->NextActiveColumn]; - ImSwap(table->DisplayOrder[dragged_column->IndexDisplayOrder], table->DisplayOrder[target_column->IndexDisplayOrder]); - ImSwap(dragged_column->IndexDisplayOrder, target_column->IndexDisplayOrder); - table->ReorderColumnDir = 0; - table->IsSettingsDirty = true; + if (table->InstanceNo == 0) + { + if (table->HeadHeaderColumn == -1 && table->ReorderColumn != -1) + table->ReorderColumn = -1; + table->HeadHeaderColumn = -1; + if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0) + { + IM_ASSERT(table->ReorderColumnDir == -1 || table->ReorderColumnDir == +1); + IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); + ImGuiTableColumn* dragged_column = &table->Columns[table->ReorderColumn]; + ImGuiTableColumn* target_column = &table->Columns[(table->ReorderColumnDir == -1) ? dragged_column->PrevActiveColumn : dragged_column->NextActiveColumn]; + ImSwap(table->DisplayOrder[dragged_column->IndexDisplayOrder], table->DisplayOrder[target_column->IndexDisplayOrder]); + ImSwap(dragged_column->IndexDisplayOrder, target_column->IndexDisplayOrder); + table->ReorderColumnDir = 0; + table->IsSettingsDirty = true; + } } // Handle display order reset request @@ -713,7 +736,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->IsUsingHeaders = false; // Context menu - if (table->IsContextPopupOpen) + if (table->IsContextPopupOpen && table->InstanceNo == table->InstanceInteracted) { if (BeginPopup("##TableContextMenu")) { @@ -763,7 +786,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) continue; - ImGuiID column_id = table->ID + (ImGuiID)column_n; + ImGuiID column_id = table->ID + (table->InstanceNo * table->ColumnsCount) + column_n; ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, hit_y2); //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)); KeepAliveID(column_id); @@ -771,7 +794,10 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) bool hovered = false, held = false; ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap); if (held) + { table->ResizedColumn = (ImS8)column_n; + table->InstanceInteracted = table->InstanceNo; + } if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held) { table->HoveredColumnBorder = (ImS8)column_n; @@ -861,14 +887,12 @@ void ImGui::EndTable() } // Apply resizing/dragging at the end of the frame - // FIXME-TABLE: Preserve contents width _while resizing down_ until releasing. - // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling. if (table->ResizedColumn != -1) { ImGuiTableColumn* column = &table->Columns[table->ResizedColumn]; const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS); const float new_width = ImFloor(new_x2 - column->MinX); - TableSetColumnWidth(table, column, new_width); + table->ResizedColumnNextWidth = new_width; } // Layout in outer window @@ -940,7 +964,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const int column_n = table->DisplayOrder[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; const bool is_hovered = (table->HoveredColumnBorder == column_n); - const bool is_resized = (table->ResizedColumn == column_n); + const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceNo); const bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered); if (draw_right_border && column->MaxX > column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. { @@ -1724,7 +1748,7 @@ void ImGui::TableAutoHeaders() // [DEBUG] //if (g.IO.KeyCtrl) { static char buf[32]; name = buf; ImGuiTableColumn* c = &table->Columns[column_n]; if (c->Flags & ImGuiTableColumnFlags_WidthStretch) ImFormatString(buf, 32, "%.3f>%.1f", c->ResizeWeight, c->WidthGiven); else ImFormatString(buf, 32, "%.1f", c->WidthGiven); } - PushID(column_n); // Allow unnamed labels (generally accidental, but let's behave nicely with them) + PushID(table->InstanceNo * table->ColumnsCount + column_n); // Allow unnamed labels (generally accidental, but let's behave nicely with them) TableHeader(name); PopID(); @@ -1767,6 +1791,7 @@ void ImGui::TableAutoHeaders() { table->IsContextPopupOpen = true; table->ContextPopupColumn = (ImS8)open_context_popup; + table->InstanceInteracted = table->InstanceNo; OpenPopup("##TableContextMenu"); } } @@ -1807,9 +1832,11 @@ void ImGui::TableHeader(const char* label) //window->DC.CursorPos.x = column->MinX + table->CellPadding.x; // Keep header highlighted when context menu is open. (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) - const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n); + const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceNo); const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld, ImVec2(0.0f, row_height)); const bool held = IsItemActive(); + if (held) + table->HeadHeaderColumn = (ImS8)column_n; window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f; // Drag and drop: re-order columns. Frozen columns are not reorderable. @@ -1818,6 +1845,7 @@ void ImGui::TableHeader(const char* label) { // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x table->ReorderColumn = (ImS8)column_n; + table->InstanceInteracted = table->InstanceNo; if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x) if (column->PrevActiveColumn != -1 && (column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (table->Columns[column->PrevActiveColumn].IndexWithinActiveSet < table->FreezeColumnsRequest)) table->ReorderColumnDir = -1; @@ -1863,8 +1891,6 @@ void ImGui::TableHeader(const char* label) if (pressed && table->ReorderColumn != column_n) TableSortSpecsClickColumn(table, column, g.IO.KeyShift); } - if (!held && table->ReorderColumn == column_n) - table->ReorderColumn = -1; // Render clipped label // Clipping here ensure that in the majority of situations, all our header cells will be merged into a single draw call. From eee82e0451047ce15ab8d7ed8532c50ba2208580 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 28 Dec 2019 17:45:15 +0100 Subject: [PATCH 387/959] Tables: Columns with no policy in a scrolling table will default to WidthFixed instead of WidthAlwaysAutoResize if an explicit value is passed to TableSetupColumn() --- imgui_tables.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 57b049ba..d545b45a 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -499,8 +499,8 @@ static float TableGetMinColumnWidth() // Layout columns for the frame // Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first. -// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for WidthAuto columns, -// increase feedback side-effect with widgets relying on WorkRect.Max.x. Maybe provide a default distribution for WidthAuto columns? +// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for WidthAlwaysAutoResize columns, +// increase feedback side-effect with widgets relying on WorkRect.Max.x. Maybe provide a default distribution for WidthAlwaysAutoResize columns? void ImGui::TableUpdateLayout(ImGuiTable* table) { IM_ASSERT(table->IsLayoutLocked == false); @@ -522,6 +522,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; // Adjust flags: default width mode + weighted columns are not allowed when auto extending + // FIXME-TABLE: Clarify why we need to do this again here and not just in TableSetupColumn() column->Flags = TableFixColumnFlags(table, column->FlagsIn); // We have a unusual edge case where if the user doesn't call TableGetSortSpecs() but has sorting enabled @@ -1269,6 +1270,12 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; table->DeclColumnsCount++; + // When passing a width automatically enforce WidthFixed policy (vs TableFixColumnFlags would default to WidthAlwaysAutoResize) + // (we write down to FlagsIn which is a little misleading, another solution would be to pass init_width_or_weight to TableFixColumnFlags) + if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0) + if ((table->Flags & ImGuiTableFlags_SizingPolicyFixedX) && (init_width_or_weight > 0.0f)) + flags |= ImGuiTableColumnFlags_WidthFixed; + column->UserID = user_id; column->FlagsIn = flags; column->Flags = TableFixColumnFlags(table, column->FlagsIn); From 883c236edaf88ce3e030309c9352d1d21478b1e5 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 28 Dec 2019 19:17:59 +0100 Subject: [PATCH 388/959] Tables: Handle columns clipped due to host rect Return false in user functions, set SkipItems in window, redirect to dummy draw channel. --- imgui.cpp | 1 + imgui_demo.cpp | 4 +- imgui_internal.h | 10 +++-- imgui_tables.cpp | 106 ++++++++++++++++++++++++++++++----------------- 4 files changed, 78 insertions(+), 43 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c7be3624..660e2b55 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -11068,6 +11068,7 @@ void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {} void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} +void ImGui::DebugNodeTable(ImGuiTable*) {} void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {} void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {} void ImGui::DebugNodeWindowsList(ImVector*, const char*) {} diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 89320593..7c0c4a7f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3619,7 +3619,9 @@ static void ShowDemoWindowTables() ImGui::TableNextRow(); for (int column = 0; column < 7; column++) { - ImGui::TableSetColumnIndex(column); + // Both TableNextCell() and TableSetColumnIndex() return false when a column is not visible, which can be used for clipping. + if (!ImGui::TableSetColumnIndex(column)) + continue; if (column == 0) ImGui::Text("Line %d", row); else diff --git a/imgui_internal.h b/imgui_internal.h index 6cddf0c9..f5678f83 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1848,6 +1848,7 @@ struct ImGuiTableColumn ImS16 NameOffset; // Offset into parent ColumnsName[] bool IsActive; // Is the column not marked Hidden by the user (regardless of clipping). We're not calling this "Visible" here because visibility also depends on clipping. bool NextIsActive; + bool IsClipped; // Set when not overlapping the host window clipping rectangle. We don't use the opposite "!Visible" name because Clipped can be altered by events. ImS8 IndexDisplayOrder; // Index within DisplayOrder[] (column may be reordered by users) ImS8 IndexWithinActiveSet; // Index within active set (<= IndexOrder) ImS8 DrawChannelCurrent; // Index within DrawSplitter.Channels[] @@ -1855,7 +1856,8 @@ struct ImGuiTableColumn ImS8 DrawChannelRowsAfterFreeze; ImS8 PrevActiveColumn; // Index of prev active column within Columns[], -1 if first active column ImS8 NextActiveColumn; // Index of next active column within Columns[], -1 if last active column - ImS8 AutoFitFrames; + ImS8 AutoFitQueue; // Queue of 8 values for the next 8 frames to request auto-fit + ImS8 CannotSkipItemsQueue; // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem ImS8 SortOrder; // -1: Not sorting on this column ImS8 SortDirection; // enum ImGuiSortDirection_ @@ -1869,7 +1871,7 @@ struct ImGuiTableColumn IndexDisplayOrder = IndexWithinActiveSet = -1; DrawChannelCurrent = DrawChannelRowsBeforeFreeze = DrawChannelRowsAfterFreeze = -1; PrevActiveColumn = NextActiveColumn = -1; - AutoFitFrames = 3; + AutoFitQueue = CannotSkipItemsQueue = (1 << 3) - 1; // Skip for three frames SortOrder = -1; SortDirection = ImGuiSortDirection_Ascending; } @@ -1884,6 +1886,7 @@ struct ImGuiTable ImVector DisplayOrder; // Store display order of columns (when not reordered, the values are 0...Count-1) ImU64 ActiveMaskByIndex; // Column Index -> IsActive map (Active == not hidden by user/api) in a format adequate for iterating column without touching cold data ImU64 ActiveMaskByDisplayOrder; // Column DisplayOrder -> IsActive map + ImU64 VisibleMaskByIndex; // Visible (== Active and not Clipped) ImGuiTableFlags SettingsSaveFlags; // Pre-compute which data we are going to save into the .ini file (e.g. when order is not altered we won't save order) int SettingsOffset; // Offset in g.SettingsTables int LastFrameActive; @@ -2179,7 +2182,7 @@ namespace ImGui //IMGUI_API bool SetTableColumnNo(int column_n); //IMGUI_API int GetTableLineNo(); IMGUI_API void TableBeginInitVisibility(ImGuiTable* table); - IMGUI_API void TableBeginInitDrawChannels(ImGuiTable* table); + IMGUI_API void TableUpdateDrawChannels(ImGuiTable* table); IMGUI_API void TableUpdateLayout(ImGuiTable* table); IMGUI_API void TableUpdateBorders(ImGuiTable* table); IMGUI_API void TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column, float width); @@ -2194,6 +2197,7 @@ namespace ImGui IMGUI_API void TableEndCell(ImGuiTable* table); IMGUI_API ImRect TableGetCellRect(); IMGUI_API const char* TableGetColumnName(ImGuiTable* table, int column_no); + IMGUI_API void TableSetColumnAutofit(ImGuiTable* table, int column_no); IMGUI_API void PushTableBackground(); IMGUI_API void PopTableBackground(); IMGUI_API void TableLoadSettings(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d545b45a..e847d477 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -65,13 +65,13 @@ // - BeginTable() user begin into a table // - BeginChild() - (if ScrollX/ScrollY is set) // - TableBeginInitVisibility() - lock columns visibility -// - TableBeginInitDrawChannels() - setup ImDrawList channels // - TableSetupColumn() user submit columns details (optional) // - TableAutoHeaders() or TableHeader() user submit a headers row (optional) // - TableSortSpecsClickColumn() // - TableGetSortSpecs() user queries updated sort specs (optional) // - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders() // - TableUpdateLayout() - called by the FIRST call to TableNextRow() +// - TableUpdateDrawChannels() - setup ImDrawList channels // - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission // - TableDrawContextMenu() - draw right-click context menu // - [...] user emit contents @@ -338,7 +338,6 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags } TableBeginInitVisibility(table); - TableBeginInitDrawChannels(table); // Grab a copy of window fields we will modify table->BackupSkipItems = inner_window->SkipItems; @@ -378,7 +377,7 @@ void ImGui::TableBeginInitVisibility(ImGuiTable* table) } if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_MultiSortable)) table->IsSortSpecsDirty = true; - if (column->AutoFitFrames > 0) + if (column->AutoFitQueue != 0x00) want_column_auto_fit = true; ImU64 index_mask = (ImU64)1 << column_n; @@ -405,6 +404,7 @@ void ImGui::TableBeginInitVisibility(ImGuiTable* table) } IM_ASSERT(column->IndexWithinActiveSet <= column->IndexDisplayOrder); } + table->VisibleMaskByIndex = table->ActiveMaskByIndex; // Columns will be masked out by TableUpdateLayout() when Clipped table->RightMostActiveColumn = (ImS8)(last_active_column ? table->Columns.index_from_ptr(last_active_column) : -1); // Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid @@ -413,7 +413,7 @@ void ImGui::TableBeginInitVisibility(ImGuiTable* table) table->InnerWindow->SkipItems = false; } -void ImGui::TableBeginInitDrawChannels(ImGuiTable* table) +void ImGui::TableUpdateDrawChannels(ImGuiTable* table) { // Allocate draw channels. // - We allocate them following the storage order instead of the display order so reordering won't needlessly increase overall dormant memory cost @@ -428,7 +428,7 @@ void ImGui::TableBeginInitDrawChannels(ImGuiTable* table) const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1; const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClipX) ? 1 : table->ColumnsActiveCount; const int channels_for_background = 1; - const int channels_for_dummy = (table->ColumnsActiveCount < table->ColumnsCount) ? +1 : 0; + const int channels_for_dummy = (table->ColumnsActiveCount < table->ColumnsCount || table->VisibleMaskByIndex != table->ActiveMaskByIndex) ? +1 : 0; const int channels_total = channels_for_background + (channels_for_row * freeze_row_multiplier) + channels_for_dummy; table->DrawSplitter.Split(table->InnerWindow->DrawList, channels_total); table->DummyDrawChannel = channels_for_dummy ? (ImS8)(channels_total - 1) : -1; @@ -437,7 +437,7 @@ void ImGui::TableBeginInitDrawChannels(ImGuiTable* table) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - if (column->IsActive) + if (!column->IsClipped) { column->DrawChannelRowsBeforeFreeze = (ImS8)(draw_channel_current); column->DrawChannelRowsAfterFreeze = (ImS8)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row : 0)); @@ -534,7 +534,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) { // Latch initial size for fixed columns count_fixed += 1; - const bool init_size = (column->AutoFitFrames > 0) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize); + const bool init_size = (column->AutoFitQueue != 0x00) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize); if (init_size) { // Combine width from regular rows + width from headers unless requested not to @@ -546,7 +546,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // FIXME-TABLE: Increase minimum size during init frame so avoid biasing auto-fitting widgets (e.g. TextWrapped) too much. // Otherwise what tends to happen is that TextWrapped would output a very large height (= first frame scrollbar display very off + clipper would skip lots of items) // This is merely making the side-effect less extreme, but doesn't properly fixes it. - if (column->AutoFitFrames > 1 && table->IsFirstFrame) + if (column->AutoFitQueue > 0x01 && table->IsFirstFrame) column->WidthRequested = ImMax(column->WidthRequested, min_column_width * 4.0f); } width_fixed += column->WidthRequested; @@ -559,10 +559,6 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (table->LeftMostStretchedColumnDisplayOrder == -1) table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->IndexDisplayOrder; } - - // Don't increment auto-fit until container window got a chance to submit its items - if (column->AutoFitFrames > 0 && table->BackupSkipItems == false) - column->AutoFitFrames--; } // Layout @@ -678,6 +674,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->ClipRect.Max.x = offset_x; column->ClipRect.Max.y = FLT_MAX; column->ClipRect.ClipWithFull(host_clip_rect); + column->IsClipped = true; continue; } @@ -693,27 +690,44 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->MinX = offset_x; column->MaxX = column->MinX + column->WidthGiven; - const float initial_max_pos_x = column->MinX + table->CellPaddingX1; - column->ContentMaxPosRowsFrozen = column->ContentMaxPosRowsUnfrozen = initial_max_pos_x; - column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersDesired = initial_max_pos_x; - - // Starting cursor position - column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1; - - // Alignment - // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in many cases. - // (To be able to honor this we might be able to store a log of cells width, per row, for visible rows, but nav/programmatic scroll would have visible artifacts.) - //if (column->Flags & ImGuiTableColumnFlags_AlignRight) - // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]); - //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) - // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]), 0.5f); - //// A one pixel padding on the right side makes clipping more noticeable and contents look less cramped. column->ClipRect.Min.x = column->MinX; column->ClipRect.Min.y = work_rect.Min.y; column->ClipRect.Max.x = column->MaxX;// -1.0f; column->ClipRect.Max.y = FLT_MAX; column->ClipRect.ClipWithFull(host_clip_rect); + + column->IsClipped = (column->ClipRect.Max.x <= column->ClipRect.Min.x) && (column->AutoFitQueue & 1) == 0 && (column->CannotSkipItemsQueue & 1) == 0; + if (column->IsClipped) + { + // Columns with the _WidthAlwaysAutoResize sizing policy will never be updated then. + table->VisibleMaskByIndex &= ~((ImU64)1 << column_n); + } + else + { + // Starting cursor position + column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1; + + // Alignment + // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in many cases. + // (To be able to honor this we might be able to store a log of cells width, per row, for visible rows, but nav/programmatic scroll would have visible artifacts.) + //if (column->Flags & ImGuiTableColumnFlags_AlignRight) + // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]); + //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) + // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]), 0.5f); + + // Reset content width variables + const float initial_max_pos_x = column->MinX + table->CellPaddingX1; + column->ContentMaxPosRowsFrozen = column->ContentMaxPosRowsUnfrozen = initial_max_pos_x; + column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersDesired = initial_max_pos_x; + } + + // Don't decrement auto-fit counters until container window got a chance to submit its items + if (table->BackupSkipItems == false) + { + column->AutoFitQueue >>= 1; + column->CannotSkipItemsQueue >>= 1; + } if (active_n < table->FreezeColumnsCount) host_clip_rect.Min.x = ImMax(host_clip_rect.Min.x, column->MaxX + 2.0f); @@ -727,6 +741,9 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (count_resizable == 0 && (table->Flags & ImGuiTableFlags_Resizable)) table->Flags &= ~ImGuiTableFlags_Resizable; + // Allocate draw channels + TableUpdateDrawChannels(table); + // Borders if (table->Flags & ImGuiTableFlags_Resizable) TableUpdateBorders(table); @@ -1067,7 +1084,7 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // - W1 F2 F3 resize from F2| --> FIXME should resize F2, F3 and not have effect on W1 (Stretch columns are _before_ the Fixed column). // Rules: - // - [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableSetupLayout(). + // - [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). // - [Resize Rule 2] Resizing from right-side of a Stretch column before a fixed column froward sizing to left-side of fixed column. // - [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to ensure that our left border won't move. @@ -1188,7 +1205,7 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) // 2019/10/22: (1) This is breaking table_2_draw_calls but I cannot seem to repro what it is attempting to fix... // cf git fce2e8dc "Fixed issue with clipping when outerwindow==innerwindow / support ScrollH without ScrollV." - // 2019/10/22: (2) Clamping code in TableSetupLayout() seemingly made this not necessary... + // 2019/10/22: (2) Clamping code in TableUpdateLayout() seemingly made this not necessary... #if 0 if (column->MinX < table->InnerClipRect.Min.x || column->MaxX > table->InnerClipRect.Max.x) merge_set_all_fit_within_inner_rect = false; @@ -1289,7 +1306,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) { column->WidthRequested = init_width_or_weight; - column->AutoFitFrames = 0; + column->AutoFitQueue = 0x00; } if (flags & ImGuiTableColumnFlags_WidthStretch) { @@ -1502,7 +1519,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) // FIXME-COLUMNS: Setup baseline, preserve across columns (how can we obtain first line baseline tho..) // window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); - window->SkipItems = column->IsActive ? table->BackupSkipItems : true; + window->SkipItems = column->IsClipped ? true : table->BackupSkipItems; if (table->Flags & ImGuiTableFlags_NoClipX) { table->DrawSplitter.SetCurrentChannel(window->DrawList, 1); @@ -1558,8 +1575,8 @@ bool ImGui::TableNextCell() TableNextRow(); } - ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; - return column->IsActive; + int column_n = table->CurrentColumn; + return (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) != 0; } const char* ImGui::TableGetColumnName(int column_n) @@ -1581,7 +1598,7 @@ bool ImGui::TableGetColumnIsVisible(int column_n) return false; if (column_n < 0) column_n = table->CurrentColumn; - return (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) != 0; + return (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) != 0; } int ImGui::TableGetColumnIndex() @@ -1608,7 +1625,7 @@ bool ImGui::TableSetColumnIndex(int column_idx) TableBeginCell(table, column_idx); } - return (table->ActiveMaskByIndex & ((ImU64)1 << column_idx)) != 0; + return (table->VisibleMaskByIndex & ((ImU64)1 << column_idx)) != 0; } ImRect ImGui::TableGetCellRect() @@ -1627,6 +1644,15 @@ const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_no) return &table->ColumnsNames.Buf[column->NameOffset]; } +void ImGui::TableSetColumnAutofit(ImGuiTable* table, int column_no) +{ + // Disable clipping then auto-fit, will take 2 frames + // (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) + ImGuiTableColumn* column = &table->Columns[column_no]; + column->CannotSkipItemsQueue = (1 << 0); + column->AutoFitQueue = (1 << 1); +} + void ImGui::PushTableBackground() { ImGuiContext& g = *GImGui; @@ -1664,7 +1690,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) { const bool can_resize = !(selected_column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && selected_column->IsActive; if (MenuItem("Size column to fit", NULL, false, can_resize)) - selected_column->AutoFitFrames = 1; + TableSetColumnAutofit(table, selected_column_n); } if (MenuItem("Size all columns to fit", NULL)) @@ -1673,7 +1699,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) { ImGuiTableColumn* column = &table->Columns[column_n]; if (column->IsActive) - column->AutoFitFrames = 1; + TableSetColumnAutofit(table, column_n); } } want_separator = true; @@ -2280,6 +2306,7 @@ void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHan // - DebugNodeTable() [Internal] //------------------------------------------------------------------------- +#ifndef IMGUI_DISABLE_METRICS_WINDOW void ImGui::DebugNodeTable(ImGuiTable* table) { char buf[256]; @@ -2296,11 +2323,11 @@ void ImGui::DebugNodeTable(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[n]; const char* name = TableGetColumnName(table, n); BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" - "Active: %d, DrawChannels: %d,%d\n" + "Active: %d, Clipped: %d, DrawChannels: %d,%d\n" "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", n, column->IndexDisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, - column->IsActive, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, + column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, column->WidthGiven, column->WidthRequested, column->ResizeWeight, column->UserID, column->Flags, (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", @@ -2324,6 +2351,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) TreePop(); } } +#endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW //------------------------------------------------------------------------- From 0c3d7bb1542f7aa06d19fac82d88f1a72dc848a6 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 28 Dec 2019 19:34:19 +0100 Subject: [PATCH 389/959] Tables: Double-clicking on fixed column to resize. Extracted code BeginTableEx(). # Conflicts: # imgui_internal.h --- imgui_internal.h | 2 ++ imgui_tables.cpp | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index f5678f83..ea9b552b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2181,6 +2181,8 @@ namespace ImGui //IMGUI_API int GetTableColumnNo(); //IMGUI_API bool SetTableColumnNo(int column_n); //IMGUI_API int GetTableLineNo(); + + IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void TableBeginInitVisibility(ImGuiTable* table); IMGUI_API void TableUpdateDrawChannels(ImGuiTable* table); IMGUI_API void TableUpdateLayout(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e847d477..4edcaad0 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -145,13 +145,18 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) // FIXME-TABLE: Replace enlarge vs fixed width by a flag. // Even if not really useful, we allow 'inner_scroll_width < outer_size.x' for consistency and to facilitate understanding of what the value does. bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) +{ + ImGuiID id = GetID(str_id); + return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width); +} + +bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) { ImGuiContext& g = *GImGui; ImGuiWindow* outer_window = GetCurrentWindow(); IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS && "Only 0..63 columns allowed!"); if (flags & ImGuiTableFlags_ScrollX) IM_ASSERT(inner_width >= 0.0f); - ImGuiID id = GetID(str_id); const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0; const ImVec2 avail_size = GetContentRegionAvail(); @@ -209,7 +214,7 @@ bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags // Create scrolling region (without border = zero window padding) ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; - BeginChildEx(str_id, instance_id, table->OuterRect.GetSize(), false, child_flags); + BeginChildEx(name, instance_id, table->OuterRect.GetSize(), false, child_flags); table->InnerWindow = g.CurrentWindow; table->WorkRect = table->InnerWindow->WorkRect; table->OuterRect = table->InnerWindow->Rect(); @@ -810,7 +815,14 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) KeepAliveID(column_id); bool hovered = false, held = false; - ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap); + bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick); + if (pressed && IsMouseDoubleClicked(0) && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + { + // FIXME-TABLE: Double-clicking on column edge could auto-fit weighted column? + TableSetColumnAutofit(table, column_n); + ClearActiveID(); + held = hovered = false; + } if (held) { table->ResizedColumn = (ImS8)column_n; From 81453ac42cd76aabe2664cd6394e2f335368d17b Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 29 Dec 2019 17:10:42 +0100 Subject: [PATCH 390/959] Tables: Comments, better assert, moved some internal flags out of the way. --- imgui.h | 52 +++++++++++++++++++++++++++--------------------- imgui_internal.h | 2 +- imgui_tables.cpp | 21 ++++++++++++------- 3 files changed, 44 insertions(+), 31 deletions(-) diff --git a/imgui.h b/imgui.h index 69ef0d42..a67a541a 100644 --- a/imgui.h +++ b/imgui.h @@ -671,6 +671,8 @@ namespace ImGui // - In most situations you can use TableNextRow() + TableSetColumnIndex() to populate a table. // - If you are using tables as a sort of grid, populating every columns with the same type of contents, // you may prefer using TableNextCell() instead of TableNextRow() + TableSetColumnIndex(). + // - See Demo->Tables for details. + // - See ImGuiTableFlags_ enums for a description of available flags. #define IMGUI_HAS_TABLE 1 IMGUI_API bool BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! @@ -678,14 +680,14 @@ namespace ImGui IMGUI_API bool TableNextCell(); // append into the next column (next column, or next row if currently in last column). Return true if column is visible. IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true if column is visible. IMGUI_API int TableGetColumnIndex(); // return current column index. - IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Use pass -1 to use current column. - IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Use pass -1 to use current column. - IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Use pass -1 to use current column. + IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. + IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Pass -1 to use current column. + IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Pass -1 to use current column. // Tables: Headers & Columns declaration - // - Use TableSetupColumn() to specify resizing policy, default width, name, id, specific flags etc. + // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. // - The name passed to TableSetupColumn() is used by TableAutoHeaders() and by the context-menu // - Use TableAutoHeaders() to submit the whole header row, otherwise you may treat the header row as a regular row, manually call TableHeader() and other widgets. - // - Headers are required to perform some interactions: reordering, sorting, context menu // FIXME-TABLES: remove context from this list! + // - Headers are required to perform some interactions: reordering, sorting, context menu // FIXME-TABLE: remove context from this list! IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = -1.0f, ImU32 user_id = 0); IMGUI_API void TableAutoHeaders(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu IMGUI_API void TableHeader(const char* label); // submit one header cell manually. @@ -1005,6 +1007,10 @@ enum ImGuiTabItemFlags_ }; // Flags for ImGui::BeginTable() +// - Columns can either varying resizing policy: "Fixed", "Stretch" or "AlwaysAutoResize". Toggling ScrollX needs to alter default sizing policy. +// - Sizing policy have many subtle side effects which may be hard to fully comprehend at first.. They'll eventually make sense. +// - with SizingPolicyFixedX (default is ScrollX is on): Columns can be enlarged as needed. Enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rect. Only Fixed columns allowed. Weighted columns will calculate their width assuming no scrolling. +// - with SizingPolicyStretchX (default is ScrollX is off): Fit all columns within available table width (so it doesn't make sense to use ScrollX with Stretch columns!). Fixed and Weighted columns allowed. enum ImGuiTableFlags_ { // Features @@ -1023,26 +1029,26 @@ enum ImGuiTableFlags_ ImGuiTableFlags_BordersFullHeight = 1 << 10, // Borders covers all lines even when Headers are being used, allow resizing all rows. ImGuiTableFlags_Borders = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersH, // Padding, Sizing - ImGuiTableFlags_NoClipX = 1 << 12, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items with be able to overflow) - ImGuiTableFlags_SizingPolicyStretchX = 1 << 13, // (Default if ScrollX is off) Columns will default to use ImGuiTableColumnFlags_WidthStretch. Fit all columns within available width. Fixed and Weighted columns allowed. - ImGuiTableFlags_SizingPolicyFixedX = 1 << 14, // (Default if ScrollX is on) Columns will default to use ImGuiTableColumnFlags_WidthFixed or WidthAuto. Enlarge as needed: enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rect. Only Fixed columns allowed. Weighted columns will calculate their width assuming no scrolling. - ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribute to automatic width calculation for every columns. + ImGuiTableFlags_NoClipX = 1 << 12, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow) + ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use WidthFixed or WidthAlwaysAutoResize policy. Read description above for more details. + ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use WidthStretch policy. Read description above for more details. + ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) // Scrolling ImGuiTableFlags_ScrollX = 1 << 17, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. ImGuiTableFlags_ScrollY = 1 << 18, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, - ImGuiTableFlags_ScrollFreezeRowsShift_ = 19, // We can lock 1 to 3 rows (starting from the top). Encode each of those values as dedicated flags. - ImGuiTableFlags_ScrollFreezeTopRow = 1 << ImGuiTableFlags_ScrollFreezeRowsShift_, - ImGuiTableFlags_ScrollFreeze2Rows = 2 << ImGuiTableFlags_ScrollFreezeRowsShift_, - ImGuiTableFlags_ScrollFreeze3Rows = 3 << ImGuiTableFlags_ScrollFreezeRowsShift_, - ImGuiTableFlags_ScrollFreezeColumnsShift_ = 21, // We can lock 1 to 3 columns (starting from the left). Encode each of those values as dedicated flags. - ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << ImGuiTableFlags_ScrollFreezeColumnsShift_, - ImGuiTableFlags_ScrollFreeze2Columns = 2 << ImGuiTableFlags_ScrollFreezeColumnsShift_, - ImGuiTableFlags_ScrollFreeze3Columns = 3 << ImGuiTableFlags_ScrollFreezeColumnsShift_, - - // Combinations and masks + ImGuiTableFlags_ScrollFreezeTopRow = 1 << 19, // We can lock 1 to 3 rows (starting from the top). Use with ScrollY enabled. + ImGuiTableFlags_ScrollFreeze2Rows = 2 << 19, + ImGuiTableFlags_ScrollFreeze3Rows = 3 << 19, + ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << 21, // We can lock 1 to 3 columns (starting from the left). Use with ScrollX enabled. + ImGuiTableFlags_ScrollFreeze2Columns = 2 << 21, + ImGuiTableFlags_ScrollFreeze3Columns = 3 << 21, + + // [Internal] Combinations and masks ImGuiTableFlags_SizingPolicyMaskX_ = ImGuiTableFlags_SizingPolicyStretchX | ImGuiTableFlags_SizingPolicyFixedX, + ImGuiTableFlags_ScrollFreezeRowsShift_ = 19, + ImGuiTableFlags_ScrollFreezeColumnsShift_ = 21, ImGuiTableFlags_ScrollFreezeRowsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeRowsShift_, ImGuiTableFlags_ScrollFreezeColumnsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeColumnsShift_ }; @@ -1066,13 +1072,13 @@ enum ImGuiTableColumnFlags_ ImGuiTableColumnFlags_NoHeaderWidth = 1 << 11, // Header width don't contribute to automatic column width. ImGuiTableColumnFlags_PreferSortAscending = 1 << 12, // Make the initial sort direction Ascending when first sorting on this column (default). ImGuiTableColumnFlags_PreferSortDescending = 1 << 13, // Make the initial sort direction Descending when first sorting on this column. - //ImGuiTableColumnFlags_AlignLeft = 1 << 14, - //ImGuiTableColumnFlags_AlignCenter = 1 << 15, - //ImGuiTableColumnFlags_AlignRight = 1 << 16, - // Combinations and masks + // [Internal] Combinations and masks ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthAlwaysAutoResize, ImGuiTableColumnFlags_NoDirectResize_ = 1 << 20 // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) + //ImGuiTableColumnFlags_AlignLeft = 1 << 14, + //ImGuiTableColumnFlags_AlignCenter = 1 << 15, + //ImGuiTableColumnFlags_AlignRight = 1 << 16, //ImGuiTableColumnFlags_AlignMask_ = ImGuiTableColumnFlags_AlignLeft | ImGuiTableColumnFlags_AlignCenter | ImGuiTableColumnFlags_AlignRight }; diff --git a/imgui_internal.h b/imgui_internal.h index ea9b552b..7f2dc1d9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1895,7 +1895,7 @@ struct ImGuiTable int CurrentColumn; int CurrentRow; ImS16 InstanceNo; // Count of BeginTable() calls with same ID in the same frame (generally 0) - ImS16 InstanceInteracted; + ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with float RowPosY1; float RowPosY2; float RowTextBaseline; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 4edcaad0..79ec8ef7 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -106,6 +106,7 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) flags |= ImGuiTableFlags_BordersV; // Adjust flags: disable top rows freezing if there's no scrolling + // In theory we could want to assert if ScrollFreeze was set without the corresponding scroll flag, but that would hinder demos. if ((flags & ImGuiTableFlags_ScrollX) == 0) flags &= ~ImGuiTableFlags_ScrollFreezeColumnsMask_; if ((flags & ImGuiTableFlags_ScrollY) == 0) @@ -154,6 +155,8 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG { ImGuiContext& g = *GImGui; ImGuiWindow* outer_window = GetCurrentWindow(); + + // Sanity checks IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS && "Only 0..63 columns allowed!"); if (flags & ImGuiTableFlags_ScrollX) IM_ASSERT(inner_width >= 0.0f); @@ -840,7 +843,7 @@ void ImGui::EndTable() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL); + IM_ASSERT(table != NULL && "Only call EndTable() is BeginTable() returns true!"); const ImGuiTableFlags flags = table->Flags; ImGuiWindow* inner_window = table->InnerWindow; @@ -1292,8 +1295,8 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Can only call TableSetupColumn() after BeginTable()!"); - IM_ASSERT(!table->IsLayoutLocked && "Can only call TableSetupColumn() before first row!"); + IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); + IM_ASSERT(!table->IsLayoutLocked && "Need to call call TableSetupColumn() before first row!"); IM_ASSERT(table->DeclColumnsCount >= 0 && table->DeclColumnsCount < table->ColumnsCount && "Called TableSetupColumn() too many times!"); ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; @@ -1505,7 +1508,8 @@ void ImGui::TableEndRow(ImGuiTable* table) table->IsInsideRow = false; } -// [Internal] This is called a lot, so we need to be mindful of unnecessary overhead! +// [Internal] Called by TableNextRow()TableNextCell()! +// This is called a lot, so we need to be mindful of unnecessary overhead. void ImGui::TableBeginCell(ImGuiTable* table, int column_no) { table->CurrentColumn = column_no; @@ -1550,7 +1554,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) } } -// [Internal] +// [Internal] Called by TableNextRow()TableNextCell()! void ImGui::TableEndCell(ImGuiTable* table) { ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; @@ -1684,6 +1688,7 @@ void ImGui::PopTableBackground() PopClipRect(); } +// Output context menu into current window (generally a popup) // FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) { @@ -1751,7 +1756,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) } } -// This is a helper to output headers based on the column names declared in TableSetupColumn() +// This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). // The intent is that advanced users would not need to use this helper and may create their own. void ImGui::TableAutoHeaders() { @@ -1761,7 +1766,8 @@ void ImGui::TableAutoHeaders() return; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table && table->CurrentRow == -1); + IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); + IM_ASSERT(table->CurrentRow == -1); int open_context_popup = INT_MAX; @@ -1852,6 +1858,7 @@ void ImGui::TableHeader(const char* label) return; ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); IM_ASSERT(table->CurrentColumn != -1); const int column_n = table->CurrentColumn; ImGuiTableColumn* column = &table->Columns[column_n]; From 046fad01f1185d34c203d4f58f5adc0b7d28eaa9 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 29 Dec 2019 17:12:09 +0100 Subject: [PATCH 391/959] Tables: Return false when window is Collapsed (consistent + helpful for doc) + Fix empty context menu. --- imgui_tables.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 79ec8ef7..2ea3a96b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -155,6 +155,8 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG { ImGuiContext& g = *GImGui; ImGuiWindow* outer_window = GetCurrentWindow(); + if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible. + return false; // Sanity checks IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS && "Only 0..63 columns allowed!"); @@ -1839,12 +1841,13 @@ void ImGui::TableAutoHeaders() // Context Menu if (open_context_popup != INT_MAX) - { - table->IsContextPopupOpen = true; - table->ContextPopupColumn = (ImS8)open_context_popup; - table->InstanceInteracted = table->InstanceNo; - OpenPopup("##TableContextMenu"); - } + if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + table->IsContextPopupOpen = true; + table->ContextPopupColumn = (ImS8)open_context_popup; + table->InstanceInteracted = table->InstanceNo; + OpenPopup("##TableContextMenu"); + } } // Emit a column header (text + optional sort order) From 78b12068d9d73ec91859fe52a7fad7b971b37f49 Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 29 Dec 2019 17:35:12 +0100 Subject: [PATCH 392/959] Tables: Disable initial output prior to NextRow call to avoid misleading users. Fixed some inconsistency with BeginTable/EndTable without row. Move some of the TableBegin() code in TableBeginUpdateColumns(). Allow to submit multiple header lines. --- imgui_internal.h | 2 +- imgui_tables.cpp | 88 ++++++++++++++++++++++++++++++------------------ 2 files changed, 56 insertions(+), 34 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 7f2dc1d9..ee6977dc 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2183,7 +2183,7 @@ namespace ImGui //IMGUI_API int GetTableLineNo(); IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); - IMGUI_API void TableBeginInitVisibility(ImGuiTable* table); + IMGUI_API void TableBeginUpdateColumns(ImGuiTable* table); IMGUI_API void TableUpdateDrawChannels(ImGuiTable* table); IMGUI_API void TableUpdateLayout(ImGuiTable* table); IMGUI_API void TableUpdateBorders(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2ea3a96b..3d04fae8 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -64,7 +64,7 @@ // Typical call flow: (root level is public API): // - BeginTable() user begin into a table // - BeginChild() - (if ScrollX/ScrollY is set) -// - TableBeginInitVisibility() - lock columns visibility +// - TableBeginUpdateColumns() - apply resize/order requests, lock columns active state, order // - TableSetupColumn() user submit columns details (optional) // - TableAutoHeaders() or TableHeader() user submit a headers row (optional) // - TableSortSpecsClickColumn() @@ -306,8 +306,26 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (table->IsFirstFrame || table->IsSettingsRequestLoad) TableLoadSettings(table); + // Grab a copy of window fields we will modify + table->BackupSkipItems = inner_window->SkipItems; + table->BackupWorkRect = inner_window->WorkRect; + table->BackupCursorMaxPos = inner_window->DC.CursorMaxPos; + + // Disable output until user calls TableNextRow() or TableNextCell() leading to the TableUpdateLayout() call.. + // This is not strictly necessary but will reduce cases were misleading "out of table" output will be confusing to the user. + // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. + inner_window->SkipItems = true; + + // Update/lock which columns will be Active for the frame + TableBeginUpdateColumns(table); + + return true; +} + +void ImGui::TableBeginUpdateColumns(ImGuiTable* table) +{ // Handle resizing request - // (We process this at the first beginning of the frame) + // (We process this at the first TableBegin of the frame) // FIXME-TABLE: Preserve contents width _while resizing down_ until releasing. // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling. if (table->InstanceNo == 0) @@ -341,29 +359,12 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Handle display order reset request if (table->IsResetDisplayOrderRequest) { - for (int n = 0; n < columns_count; n++) + for (int n = 0; n < table->ColumnsCount; n++) table->DisplayOrder[n] = table->Columns[n].IndexDisplayOrder = (ImU8)n; table->IsResetDisplayOrderRequest = false; table->IsSettingsDirty = true; } - TableBeginInitVisibility(table); - - // Grab a copy of window fields we will modify - table->BackupSkipItems = inner_window->SkipItems; - table->BackupWorkRect = inner_window->WorkRect; - table->BackupCursorMaxPos = inner_window->DC.CursorMaxPos; - - if (flags & ImGuiTableFlags_NoClipX) - table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 1); - else - inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false); - - return true; -} - -void ImGui::TableBeginInitVisibility(ImGuiTable* table) -{ // Setup and lock Active state and order table->ColumnsActiveCount = 0; table->IsDefaultDisplayOrder = true; @@ -706,7 +707,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->ClipRect.Max.x = column->MaxX;// -1.0f; column->ClipRect.Max.y = FLT_MAX; column->ClipRect.ClipWithFull(host_clip_rect); - + column->IsClipped = (column->ClipRect.Max.x <= column->ClipRect.Min.x) && (column->AutoFitQueue & 1) == 0 && (column->CannotSkipItemsQueue & 1) == 0; if (column->IsClipped) { @@ -776,6 +777,13 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->IsContextPopupOpen = false; } } + + // Initial state + ImGuiWindow* inner_window = table->InnerWindow; + if (table->Flags & ImGuiTableFlags_NoClipX) + table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 1); + else + inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false); } // Process interaction on resizing borders. Actual size change will be applied in EndTable() @@ -847,6 +855,15 @@ void ImGui::EndTable() ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Only call EndTable() is BeginTable() returns true!"); + // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some cases, + // and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) + //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?"); + + // If the user never got to call TableNextRow() or TableNextCell(), we call layout ourselves to ensure all our + // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc. + if (!table->IsLayoutLocked) + TableUpdateLayout(table); + const ImGuiTableFlags flags = table->Flags; ImGuiWindow* inner_window = table->InnerWindow; ImGuiWindow* outer_window = table->OuterWindow; @@ -1664,7 +1681,7 @@ const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_no) void ImGui::TableSetColumnAutofit(ImGuiTable* table, int column_no) { - // Disable clipping then auto-fit, will take 2 frames + // Disable clipping then auto-fit, will take 2 frames // (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) ImGuiTableColumn* column = &table->Columns[column_no]; column->CannotSkipItemsQueue = (1 << 0); @@ -1759,23 +1776,23 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) } // This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). -// The intent is that advanced users would not need to use this helper and may create their own. +// The intent is that advanced users willing to create customized headers would not need to use this helper and may create their own. +// However presently this function uses too many internal structures/calls. void ImGui::TableAutoHeaders() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - if (window->SkipItems) - return; ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); - IM_ASSERT(table->CurrentRow == -1); - int open_context_popup = INT_MAX; + TableNextRow(ImGuiTableRowFlags_Headers, GetTextLineHeight()); + if (window->SkipItems) + return; // This for loop is constructed to not make use of internal functions, // as this is intended to be a base template to copy and build from. - TableNextRow(ImGuiTableRowFlags_Headers, GetTextLineHeight()); + int open_context_popup = INT_MAX; const int columns_count = table->ColumnsCount; for (int column_n = 0; column_n < columns_count; column_n++) { @@ -1788,7 +1805,7 @@ void ImGui::TableAutoHeaders() #if 0 if (column_n < 2) { - static bool b[10] = {}; + static bool b[2] = {}; PushID(column_n); PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); Checkbox("##", &b[column_n]); @@ -1801,7 +1818,8 @@ void ImGui::TableAutoHeaders() // [DEBUG] //if (g.IO.KeyCtrl) { static char buf[32]; name = buf; ImGuiTableColumn* c = &table->Columns[column_n]; if (c->Flags & ImGuiTableColumnFlags_WidthStretch) ImFormatString(buf, 32, "%.3f>%.1f", c->ResizeWeight, c->WidthGiven); else ImFormatString(buf, 32, "%.1f", c->WidthGiven); } - PushID(table->InstanceNo * table->ColumnsCount + column_n); // Allow unnamed labels (generally accidental, but let's behave nicely with them) + // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them) + PushID(table->InstanceNo * table->ColumnsCount + column_n); TableHeader(name); PopID(); @@ -1811,15 +1829,19 @@ void ImGui::TableAutoHeaders() } // FIXME-TABLE: This is not user-land code any more... + // FIXME-TABLE: Need to explain why this is here! window->SkipItems = table->BackupSkipItems; // Allow opening popup from the right-most section after the last column // FIXME-TABLE: This is not user-land code any more... perhaps instead we should expose hovered column. // and allow some sort of row-centric IsItemHovered() for full flexibility? - const float unused_x1 = (table->RightMostActiveColumn != -1) ? table->Columns[table->RightMostActiveColumn].MaxX : table->WorkRect.Min.x; + float unused_x1 = table->WorkRect.Min.x; + if (table->RightMostActiveColumn != -1) + unused_x1 = ImMax(unused_x1, table->Columns[table->RightMostActiveColumn].MaxX); if (unused_x1 < table->WorkRect.Max.x) { - // FIXME: We inherit ClipRect/SkipItem from last submitted column (active or not), let's override + // FIXME: We inherit ClipRect/SkipItem from last submitted column (active or not), let's temporarily override it. + // Because we don't perform any rendering here we just overwrite window->ClipRect used by logic. window->ClipRect = table->InnerClipRect; ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; @@ -1839,7 +1861,7 @@ void ImGui::TableAutoHeaders() window->ClipRect = window->DrawList->_ClipRectStack.back(); } - // Context Menu + // Open Context Menu if (open_context_popup != INT_MAX) if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) { From 47b39f6371573dd181bef97d96ff9cf7a15c8cbe Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 29 Dec 2019 19:48:10 +0100 Subject: [PATCH 393/959] Tables: Demo: Moved Columns section into Tables & Columns section under a Legacy section. --- imgui_demo.cpp | 31 ++++++++++++------------------- 1 file changed, 12 insertions(+), 19 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 7c0c4a7f..b9278f46 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -484,7 +484,6 @@ void ImGui::ShowDemoWindow(bool* p_open) ShowDemoWindowLayout(); ShowDemoWindowPopups(); ShowDemoWindowTables(); - ShowDemoWindowColumns(); ShowDemoWindowMisc(); // End of ShowDemoWindow() @@ -3289,7 +3288,7 @@ const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL; static void ShowDemoWindowTables() { //ImGui::SetNextItemOpen(true, ImGuiCond_Once); - if (!ImGui::CollapsingHeader("Tables")) + if (!ImGui::CollapsingHeader("Tables & Columns")) return; ImGui::PushID("Tables"); @@ -4175,27 +4174,23 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } + ImGui::PopID(); + + ShowDemoWindowColumns(); + if (disable_indent) ImGui::PopStyleVar(); - ImGui::PopID(); } -// 2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful Tables API! +// Demonstrate old/legacy Columns API! +// [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] static void ShowDemoWindowColumns() { - if (!ImGui::CollapsingHeader("Columns")) - return; - - ImGui::PushID("Columns"); - - static bool disable_indent = false; - ImGui::Checkbox("Disable tree indentation", &disable_indent); + bool open = ImGui::TreeNode("Legacy Columns API"); ImGui::SameLine(); - HelpMarker("Disable the indenting of tree nodes so demo columns can use the full window width."); - if (disable_indent) - ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f); - - ImGui::TextWrapped("Note: Columns are under-featured and not maintained. Prefer using the more flexible and powerful Tables API!"); + HelpMarker("Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!"); + if (!open) + return; // Basic columns if (ImGui::TreeNode("Basic")) @@ -4407,9 +4402,7 @@ static void ShowDemoWindowColumns() ImGui::TreePop(); } - if (disable_indent) - ImGui::PopStyleVar(); - ImGui::PopID(); + ImGui::TreePop(); } static void ShowDemoWindowMisc() From 1db8d421cf650e21d0e01bcea5350033816da758 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 30 Dec 2019 13:01:36 +0100 Subject: [PATCH 394/959] Tables: Fix scroll when releasing resize for multi-instances. Comments. Renaming. --- imgui_internal.h | 12 ++++++------ imgui_tables.cpp | 28 ++++++++++++++-------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index ee6977dc..fdf19577 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1932,8 +1932,8 @@ struct ImGuiTable ImS8 HoveredColumnBody; // [DEBUG] Unlike HoveredColumnBorder this doesn't fulfill all Hovering rules properly. Used for debugging/tools for now. ImS8 HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). ImS8 ResizedColumn; // Index of column being resized. Reset by InstanceNo==0. - ImS8 HeadHeaderColumn; // Index of column header being held. - ImS8 LastResizedColumn; + ImS8 LastResizedColumn; // Index of column being resized from previous frame. + ImS8 HeldHeaderColumn; // Index of column header being held. ImS8 ReorderColumn; // Index of column being reordered. (not cleared) ImS8 ReorderColumnDir; // -1 or +1 ImS8 RightMostActiveColumn; // Index of right-most non-hidden column. @@ -1945,11 +1945,11 @@ struct ImGuiTable ImS8 FreezeColumnsRequest; // Requested frozen columns count ImS8 FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. - bool IsInsideRow; // Set if inside TableBeginRow()/TableEndRow(). - bool IsFirstFrame; + bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). + bool IsInitializing; bool IsSortSpecsDirty; - bool IsUsingHeaders; // Set if the first row had the ImGuiTableRowFlags_Headers flag. - bool IsContextPopupOpen; + 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 IsSettingsRequestLoad; bool IsSettingsLoaded; bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3d04fae8..f4dde061 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -61,6 +61,7 @@ // [SECTION] Widgets: BeginTable, EndTable, etc. //----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // Typical call flow: (root level is public API): // - BeginTable() user begin into a table // - BeginChild() - (if ScrollX/ScrollY is set) @@ -81,6 +82,7 @@ // - TableSetColumnWidth() - apply resizing width // - TableUpdateColumnsWeightFromWidth() // - EndChild() - (if ScrollX/ScrollY is set) +//----------------------------------------------------------------------------- // Configuration static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders. @@ -190,12 +192,12 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Initialize table->ID = id; table->Flags = flags; - table->IsFirstFrame = (table->LastFrameActive == -1); table->InstanceNo = (ImS16)instance_no; table->LastFrameActive = g.FrameCount; table->OuterWindow = table->InnerWindow = outer_window; table->ColumnsCount = columns_count; table->ColumnsNames.Buf.resize(0); + table->IsInitializing = false; table->IsLayoutLocked = false; table->InnerWidth = inner_width; table->OuterRect = outer_rect; @@ -256,11 +258,9 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->FreezeColumnsCount = (inner_window->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); table->DeclColumnsCount = 0; - table->LastResizedColumn = table->ResizedColumn; table->HoveredColumnBody = -1; table->HoveredColumnBorder = -1; table->RightMostActiveColumn = -1; - table->IsFirstFrame = false; // FIXME-TABLE FIXME-STYLE: Using opaque colors facilitate overlapping elements of the grid //table->BorderOuterColor = GetColorU32(ImGuiCol_Separator, 1.00f); @@ -289,8 +289,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Setup default columns state if (table->Columns.Size == 0) { - table->IsFirstFrame = true; - table->IsSortSpecsDirty = true; + table->IsInitializing = table->IsSettingsRequestLoad = table->IsSortSpecsDirty = true; table->Columns.reserve(columns_count); table->DisplayOrder.reserve(columns_count); for (int n = 0; n < columns_count; n++) @@ -303,7 +302,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG } // Load settings - if (table->IsFirstFrame || table->IsSettingsRequestLoad) + if (table->IsSettingsRequestLoad) TableLoadSettings(table); // Grab a copy of window fields we will modify @@ -332,6 +331,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) { if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX) TableSetColumnWidth(table, &table->Columns[table->ResizedColumn], table->ResizedColumnNextWidth); + table->LastResizedColumn = table->ResizedColumn; table->ResizedColumnNextWidth = FLT_MAX; table->ResizedColumn = -1; } @@ -340,9 +340,9 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) // Note: we don't clear ReorderColumn after handling the request. if (table->InstanceNo == 0) { - if (table->HeadHeaderColumn == -1 && table->ReorderColumn != -1) + if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1) table->ReorderColumn = -1; - table->HeadHeaderColumn = -1; + table->HeldHeaderColumn = -1; if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0) { IM_ASSERT(table->ReorderColumnDir == -1 || table->ReorderColumnDir == +1); @@ -554,10 +554,10 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) width_request = ImMax(width_request, (float)column->ContentWidthHeadersDesired); column->WidthRequested = ImMax(width_request + padding_auto_x, min_column_width); - // FIXME-TABLE: Increase minimum size during init frame so avoid biasing auto-fitting widgets (e.g. TextWrapped) too much. + // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets (e.g. TextWrapped) too much. // Otherwise what tends to happen is that TextWrapped would output a very large height (= first frame scrollbar display very off + clipper would skip lots of items) // This is merely making the side-effect less extreme, but doesn't properly fixes it. - if (column->AutoFitQueue > 0x01 && table->IsFirstFrame) + if (column->AutoFitQueue > 0x01 && table->IsInitializing) column->WidthRequested = ImMax(column->WidthRequested, min_column_width * 4.0f); } width_fixed += column->WidthRequested; @@ -929,7 +929,7 @@ void ImGui::EndTable() { inner_window->Scroll.x = 0.0f; } - else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX) + else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceNo) { ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn]; if (column->MaxX < table->InnerClipRect.Min.x) @@ -1333,7 +1333,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flags = column->Flags; // Initialize defaults - if (table->IsFirstFrame && !table->IsSettingsLoaded) + if (table->IsInitializing && !table->IsSettingsLoaded) { // Init width or weight // Disable auto-fit if a default fixed width has been specified @@ -1913,7 +1913,7 @@ void ImGui::TableHeader(const char* label) const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld, ImVec2(0.0f, row_height)); const bool held = IsItemActive(); if (held) - table->HeadHeaderColumn = (ImS8)column_n; + table->HeldHeaderColumn = (ImS8)column_n; window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f; // Drag and drop: re-order columns. Frozen columns are not reorderable. @@ -2123,7 +2123,7 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) } // Fallback default sort order (if no column has the ImGuiTableColumnFlags_DefaultSort flag) - if (sort_order_count == 0 && table->IsFirstFrame) + if (sort_order_count == 0 && table->IsInitializing) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; From 17578e215a4b04f1d8ca725d099dcaf5b0ff59ae Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 30 Dec 2019 15:14:15 +0100 Subject: [PATCH 395/959] Tables: Separating inner/outer borders flags per axis so it is possible to remove outer vertical borders to mimic old columns. VInner or VOuter only don't have correct padding/spacing. --- imgui.h | 15 +++++--- imgui_demo.cpp | 43 +++++++++++++++------- imgui_internal.h | 4 +-- imgui_tables.cpp | 93 ++++++++++++++++++++++++++++++------------------ 4 files changed, 101 insertions(+), 54 deletions(-) diff --git a/imgui.h b/imgui.h index a67a541a..c9920866 100644 --- a/imgui.h +++ b/imgui.h @@ -1023,11 +1023,16 @@ enum ImGuiTableFlags_ ImGuiTableFlags_NoSavedSettings = 1 << 5, // Disable persisting columns order, width and sort settings in the .ini file. // Decoration ImGuiTableFlags_RowBg = 1 << 6, // Use ImGuiCol_TableRowBg and ImGuiCol_TableRowBgAlt colors behind each rows. - ImGuiTableFlags_BordersOuter = 1 << 7, // Draw outer borders. - ImGuiTableFlags_BordersV = 1 << 8, // Draw vertical borders between columns. - ImGuiTableFlags_BordersH = 1 << 9, // Draw horizontal borders between rows. - ImGuiTableFlags_BordersFullHeight = 1 << 10, // Borders covers all lines even when Headers are being used, allow resizing all rows. - ImGuiTableFlags_Borders = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersH, + ImGuiTableFlags_BordersHInner = 1 << 7, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersHOuter = 1 << 8, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersVInner = 1 << 9, // Draw vertical borders between columns. + ImGuiTableFlags_BordersVOuter = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersHInner | ImGuiTableFlags_BordersHOuter, // Draw horizontal borders. + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersVInner | ImGuiTableFlags_BordersVOuter, // Draw vertical borders. + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersVInner | ImGuiTableFlags_BordersHInner, // Draw inner borders. + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersVOuter | ImGuiTableFlags_BordersHOuter, // Draw outer borders. + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. + ImGuiTableFlags_BordersVFullHeight = 1 << 11, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. // Padding, Sizing ImGuiTableFlags_NoClipX = 1 << 12, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow) ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use WidthFixed or WidthAlwaysAutoResize policy. Read description above for more details. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b9278f46..d4c8f643 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3379,17 +3379,31 @@ static void ShowDemoWindowTables() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); - if (ImGui::TreeNode("With borders, background")) + if (ImGui::TreeNode("Borders, background")) { // Expose a few Borders related flags interactively static ImGuiTableFlags flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; static bool display_width = false; ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&flags, ImGuiTableFlags_Borders); - ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersOuter\n | ImGuiTableFlags_BordersV\n | ImGuiTableFlags_BordersH"); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersVInner\n | ImGuiTableFlags_BordersVOuter\n | ImGuiTableFlags_BordersHInner\n | ImGuiTableFlags_BordersHOuter"); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersHOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersHOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersHInner", (unsigned int*)&flags, ImGuiTableFlags_BordersHInner); + ImGui::Unindent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::Indent(); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersVOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersVOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersVInner", (unsigned int*)&flags, ImGuiTableFlags_BordersVInner); + ImGui::Unindent(); + + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", (unsigned int*)&flags, ImGuiTableFlags_BordersInner); + ImGui::Unindent(); ImGui::Checkbox("Debug Display width", &display_width); if (ImGui::BeginTable("##table1", 3, flags)) @@ -3696,7 +3710,7 @@ static void ShowDemoWindowTables() { HelpMarker("This demonstrate embedding a table into another table cell."); - if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersVFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("A0"); ImGui::TableSetupColumn("A1"); @@ -3705,7 +3719,7 @@ static void ShowDemoWindowTables() ImGui::TableNextRow(); ImGui::Text("A0 Cell 0"); { float rows_height = ImGui::GetTextLineHeightWithSpacing() * 2; - if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersVFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("B0"); ImGui::TableSetupColumn("B1"); @@ -3737,13 +3751,15 @@ static void ShowDemoWindowTables() { HelpMarker("This section allows you to interact and see the effect of StretchX vs FixedX sizing policies depending on whether Scroll is enabled and the contents of your columns."); enum ContentsType { CT_ShortText, CT_LongText, CT_Button, CT_StretchButton, CT_InputText }; - static int contents_type = CT_ShortText; + static int contents_type = CT_StretchButton; ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); ImGui::Combo("Contents", &contents_type, "Short Text\0Long Text\0Button\0Stretch Button\0InputText\0"); static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; - ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersHInner", (unsigned int*)&flags, ImGuiTableFlags_BordersHInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersHOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersHOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersVInner", (unsigned int*)&flags, ImGuiTableFlags_BordersVInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersVOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersVOuter); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) @@ -3952,10 +3968,13 @@ static void ShowDemoWindowTables() ImGui::BulletText("Decoration:"); ImGui::Indent(); ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersFullHeight", (unsigned int*)&flags, ImGuiTableFlags_BordersFullHeight); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersVOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersVOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersVInner", (unsigned int*)&flags, ImGuiTableFlags_BordersVInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersHOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersHOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersHInner", (unsigned int*)&flags, ImGuiTableFlags_BordersHInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersVFullHeight", (unsigned int*)&flags, ImGuiTableFlags_BordersVFullHeight); ImGui::Unindent(); ImGui::BulletText("Padding, Sizing:"); diff --git a/imgui_internal.h b/imgui_internal.h index fdf19577..f897815c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1903,8 +1903,8 @@ struct ImGuiTable ImGuiTableRowFlags LastRowFlags : 16; int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper) ImU32 RowBgColor; // Request for current row background color - ImU32 BorderOuterColor; - ImU32 BorderInnerColor; + ImU32 BorderColorStrong; + ImU32 BorderColorLight; float BorderX1; float BorderX2; float CellPaddingX1; // Padding from each borders diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f4dde061..f36eccd5 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -105,7 +105,7 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) // Adjust flags: enforce borders when resizable if (flags & ImGuiTableFlags_Resizable) - flags |= ImGuiTableFlags_BordersV; + flags |= ImGuiTableFlags_BordersVInner; // Adjust flags: disable top rows freezing if there's no scrolling // In theory we could want to assert if ScrollFreeze was set without the corresponding scroll flag, but that would hinder demos. @@ -232,18 +232,23 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG PushID(instance_id); } - const bool has_cell_padding_x = (flags & (ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV)) != 0; - ImGuiWindow* inner_window = table->InnerWindow; - table->CurrentColumn = -1; - table->CurrentRow = -1; - table->RowBgColorCounter = 0; - table->LastRowFlags = ImGuiTableRowFlags_None; + // Borders + // - None ........Content..... Pad .....Content........ + // - VOuter | Pad ..Content..... Pad .....Content.. Pad | // FIXME-TABLE: Not handled properly + // - VInner ........Content.. Pad | Pad ..Content........ // FIXME-TABLE: Not handled properly + // - VOuter+VInner | Pad ..Content.. Pad | Pad ..Content.. Pad | + const bool has_cell_padding_x = (flags & ImGuiTableFlags_BordersVOuter) != 0; + ImGuiWindow* inner_window = table->InnerWindow; table->CellPaddingX1 = has_cell_padding_x ? g.Style.CellPadding.x + 1.0f : 0.0f; table->CellPaddingX2 = has_cell_padding_x ? g.Style.CellPadding.x : 0.0f; table->CellPaddingY = g.Style.CellPadding.y; table->CellSpacingX = has_cell_padding_x ? 0.0f : g.Style.CellPadding.x; + table->CurrentColumn = -1; + table->CurrentRow = -1; + table->RowBgColorCounter = 0; + table->LastRowFlags = ImGuiTableRowFlags_None; table->HostClipRect = inner_window->ClipRect; table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width @@ -265,8 +270,8 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // FIXME-TABLE FIXME-STYLE: Using opaque colors facilitate overlapping elements of the grid //table->BorderOuterColor = GetColorU32(ImGuiCol_Separator, 1.00f); //table->BorderInnerColor = GetColorU32(ImGuiCol_Separator, 0.60f); - table->BorderOuterColor = GetColorU32(ImVec4(0.31f, 0.31f, 0.35f, 1.00f)); - table->BorderInnerColor = GetColorU32(ImVec4(0.23f, 0.23f, 0.25f, 1.00f)); + table->BorderColorStrong = GetColorU32(ImVec4(0.31f, 0.31f, 0.35f, 1.00f)); + table->BorderColorLight = GetColorU32(ImVec4(0.23f, 0.23f, 0.25f, 1.00f)); //table->BorderOuterColor = IM_COL32(255, 0, 0, 255); //table->BorderInnerColor = IM_COL32(255, 255, 0, 255); table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f); @@ -798,7 +803,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) // the final height from last frame. Because this is only affecting _interaction_ with columns, it is not really problematic. // (whereas the actual visual will be displayed in EndTable() and using the current frame height) // Actual columns highlight/render will be performed in EndTable() and not be affected. - const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersFullHeight); + const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersVFullHeight); const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS; const float hit_y1 = table->OuterRect.Min.y; const float hit_y2_full = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight); @@ -979,6 +984,7 @@ void ImGui::EndTable() g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL; } +// FIXME-TABLE: This is a mess, need to redesign how we render borders. void ImGui::TableDrawBorders(ImGuiTable* table) { ImGuiWindow* inner_window = table->InnerWindow; @@ -986,28 +992,29 @@ void ImGui::TableDrawBorders(ImGuiTable* table) table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0); if (inner_window->Hidden || !table->HostClipRect.Overlaps(table->InnerClipRect)) return; + ImDrawList* inner_drawlist = inner_window->DrawList; + ImDrawList* outer_drawlist = outer_window->DrawList; // Draw inner border and resizing feedback const float draw_y1 = table->OuterRect.Min.y; float draw_y2_base = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight; float draw_y2_full = table->OuterRect.Max.y; ImU32 border_base_col; - if (!table->IsUsingHeaders || (table->Flags & ImGuiTableFlags_BordersFullHeight)) + if (!table->IsUsingHeaders || (table->Flags & ImGuiTableFlags_BordersVFullHeight)) { draw_y2_base = draw_y2_full; - border_base_col = table->BorderInnerColor; + border_base_col = table->BorderColorLight; } else { - border_base_col = table->BorderOuterColor; + border_base_col = table->BorderColorStrong; } - if (table->Flags & ImGuiTableFlags_BordersV) - { - const bool draw_left_most_border = (table->Flags & ImGuiTableFlags_BordersOuter) == 0; - if (draw_left_most_border) - inner_window->DrawList->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, 1.0f); + if ((table->Flags & ImGuiTableFlags_BordersVOuter) && (table->InnerWindow == table->OuterWindow)) + inner_drawlist->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, 1.0f); + if (table->Flags & ImGuiTableFlags_BordersVInner) + { for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) @@ -1017,7 +1024,10 @@ void ImGui::TableDrawBorders(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; const bool is_hovered = (table->HoveredColumnBorder == column_n); const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceNo); - const bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered); + const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; + bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered); + if (column->NextActiveColumn == -1 && !is_resizable) + draw_right_border = false; if (draw_right_border && column->MaxX > column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. { // Draw in outer window so right-most column won't be clipped @@ -1030,7 +1040,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) float draw_y2 = draw_y2_base; if (is_hovered || is_resized || (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1)) draw_y2 = draw_y2_full; - inner_window->DrawList->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, 1.0f); + inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, 1.0f); } } } @@ -1044,16 +1054,28 @@ void ImGui::TableDrawBorders(ImGuiTable* table) // and the part that's over scrollbars in the outer window..) // Either solution currently won't allow us to use a larger border size: the border would clipped. ImRect outer_border = table->OuterRect; + const ImU32 outer_col = table->BorderColorStrong; if (inner_window != outer_window) outer_border.Expand(1.0f); - outer_window->DrawList->AddRect(outer_border.Min, outer_border.Max, table->BorderOuterColor); // IM_COL32(255, 0, 0, 255)); + if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) + outer_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col); + else if (table->Flags & ImGuiTableFlags_BordersVOuter) + { + outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col); + outer_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col); + } + else if (table->Flags & ImGuiTableFlags_BordersHOuter) + { + outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col); + outer_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col); + } } - else if (table->Flags & ImGuiTableFlags_BordersH) + if ((table->Flags & ImGuiTableFlags_BordersHInner) && table->RowPosY2 < table->OuterRect.Max.y) { - // Draw bottom-most border + // Draw bottom-most row border const float border_y = table->RowPosY2; if (border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y) - inner_window->DrawList->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderOuterColor); + inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight); } } @@ -1451,21 +1473,22 @@ void ImGui::TableEndRow(ImGuiTable* table) else if (table->Flags & ImGuiTableFlags_RowBg) bg_col = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg); - // Decide of separating border color + // Decide of top border color ImU32 border_col = 0; if (table->CurrentRow != 0 || table->InnerWindow == table->OuterWindow) { - if (table->Flags & ImGuiTableFlags_BordersH) + if (table->Flags & ImGuiTableFlags_BordersHInner) { - if (table->CurrentRow == 0 && table->InnerWindow == table->OuterWindow) - border_col = table->BorderOuterColor; - else if (!(table->LastRowFlags & ImGuiTableRowFlags_Headers)) - border_col = table->BorderInnerColor; + //if (table->CurrentRow == 0 && table->InnerWindow == table->OuterWindow) + // border_col = table->BorderOuterColor; + //else + if (table->CurrentRow > 0)// && !(table->LastRowFlags & ImGuiTableRowFlags_Headers)) + border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight; } else { - if (table->RowFlags & ImGuiTableRowFlags_Headers) - border_col = table->BorderOuterColor; + //if (table->RowFlags & ImGuiTableRowFlags_Headers) + // border_col = table->BorderOuterColor; } } @@ -1491,10 +1514,10 @@ void ImGui::TableEndRow(ImGuiTable* table) const bool unfreeze_rows = (table->CurrentRow + 1 == table->FreezeRowsCount && table->FreezeRowsCount > 0); // Draw bottom border (always strong) - const bool draw_separating_border = unfreeze_rows || (table->RowFlags & ImGuiTableRowFlags_Headers); + const bool draw_separating_border = unfreeze_rows;// || (table->RowFlags & ImGuiTableRowFlags_Headers); if (draw_separating_border) if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y) - window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderOuterColor); + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong); // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and get the new cursor position. @@ -1801,7 +1824,7 @@ void ImGui::TableAutoHeaders() const char* name = TableGetColumnName(column_n); - // FIXME-TABLE: Test custom user elements + // [DEBUG] Test custom user elements #if 0 if (column_n < 2) { From 325b4c69ba97aea5c7919fec13ff917dd658d03f Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 30 Dec 2019 16:31:18 +0100 Subject: [PATCH 396/959] Tables: Moved border colors to the Style (maybe temporarily?) instead of hardcoding them. --- imgui.cpp | 2 ++ imgui.h | 2 ++ imgui_demo.cpp | 10 ++++++---- imgui_draw.cpp | 6 ++++++ imgui_tables.cpp | 10 +++------- 5 files changed, 19 insertions(+), 11 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 660e2b55..90ff9eff 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2550,6 +2550,8 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TableHeaderBg: return "TableHeaderBg"; + case ImGuiCol_TableBorderStrong: return "TableBorderStrong"; + case ImGuiCol_TableBorderLight: return "TableBorderLight"; case ImGuiCol_TableRowBg: return "TableRowBg"; case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; diff --git a/imgui.h b/imgui.h index c9920866..006f4ee9 100644 --- a/imgui.h +++ b/imgui.h @@ -1324,6 +1324,8 @@ enum ImGuiCol_ ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TableHeaderBg, // Table header background + ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here) + ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) ImGuiCol_TableRowBg, // Table row background (even rows) ImGuiCol_TableRowBgAlt, // Table row background (odd rows) ImGuiCol_TextSelectedBg, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index d4c8f643..10c67cbf 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3313,10 +3313,12 @@ static void ShowDemoWindowTables() // About Styling of tables // Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs. // There are however a few settings that a shared and part of the ImGuiStyle structure: - // style.CellPadding // Padding within each cell - // style.Colors[ImGuiCol_TableHeaderBg] // Table header background - // style.Colors[ImGuiCol_TableRowBg] // Table row background when ImGuiTableFlags_RowBg is enabled (even rows) - // style.Colors[ImGuiCol_TableRowBgAlt] // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) + // style.CellPadding // Padding within each cell + // style.Colors[ImGuiCol_TableHeaderBg] // Table header background + // style.Colors[ImGuiCol_TableBorderStrong] // Table outer and header borders + // style.Colors[ImGuiCol_TableBorderLight] // Table inner borders + // style.Colors[ImGuiCol_TableRowBg] // Table row background when ImGuiTableFlags_RowBg is enabled (even rows) + // style.Colors[ImGuiCol_TableRowBgAlt] // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) // Demos if (open_action != -1) diff --git a/imgui_draw.cpp b/imgui_draw.cpp index e915dd76..dfe11f43 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -223,6 +223,8 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); @@ -281,6 +283,8 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); colors[ImGuiCol_TableHeaderBg] = ImVec4(0.27f, 0.27f, 0.38f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.45f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.26f, 0.26f, 0.28f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); @@ -340,6 +344,8 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f); colors[ImGuiCol_TableHeaderBg] = ImVec4(0.78f, 0.87f, 0.98f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.57f, 0.57f, 0.64f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.68f, 0.68f, 0.74f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.07f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f36eccd5..2bac1155 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -267,13 +267,9 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->HoveredColumnBorder = -1; table->RightMostActiveColumn = -1; - // FIXME-TABLE FIXME-STYLE: Using opaque colors facilitate overlapping elements of the grid - //table->BorderOuterColor = GetColorU32(ImGuiCol_Separator, 1.00f); - //table->BorderInnerColor = GetColorU32(ImGuiCol_Separator, 0.60f); - table->BorderColorStrong = GetColorU32(ImVec4(0.31f, 0.31f, 0.35f, 1.00f)); - table->BorderColorLight = GetColorU32(ImVec4(0.23f, 0.23f, 0.25f, 1.00f)); - //table->BorderOuterColor = IM_COL32(255, 0, 0, 255); - //table->BorderInnerColor = IM_COL32(255, 255, 0, 255); + // Using opaque colors facilitate overlapping elements of the grid + table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong); + table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight); table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f); table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f); From 416e9bb38d14b52f624ee6f878da670a612bbaa8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 Jan 2020 00:31:06 +0100 Subject: [PATCH 397/959] Tables: Clarify internal calculations of row height so that TableGetCellRect() include expected paddings. Add demo code. Comments. Remove misleading commented-out flags for now. --- imgui.h | 4 ---- imgui_demo.cpp | 21 +++++++++++++++++++++ imgui_tables.cpp | 20 ++++++++++++-------- 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/imgui.h b/imgui.h index 006f4ee9..3577fe28 100644 --- a/imgui.h +++ b/imgui.h @@ -1081,10 +1081,6 @@ enum ImGuiTableColumnFlags_ // [Internal] Combinations and masks ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthAlwaysAutoResize, ImGuiTableColumnFlags_NoDirectResize_ = 1 << 20 // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) - //ImGuiTableColumnFlags_AlignLeft = 1 << 14, - //ImGuiTableColumnFlags_AlignCenter = 1 << 15, - //ImGuiTableColumnFlags_AlignRight = 1 << 16, - //ImGuiTableColumnFlags_AlignMask_ = ImGuiTableColumnFlags_AlignLeft | ImGuiTableColumnFlags_AlignCenter | ImGuiTableColumnFlags_AlignRight }; // Flags for ImGui::TableNextRow() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 10c67cbf..25d035b5 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3842,6 +3842,27 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Row height")) + { + HelpMarker("You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\n\nWe cannot honor a _maximum_ row height as that would requires a unique clipping rectangle per row."); + if (ImGui::BeginTable("##2ways", 2, ImGuiTableFlags_Borders)) + { + float min_row_height = ImGui::GetFontSize() + ImGui::GetStyle().CellPadding.y * 2.0f; + ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); + ImGui::Text("min_row_height = %.2f", min_row_height); + for (int row = 0; row < 10; row++) + { + min_row_height = (float)(int)(ImGui::GetFontSize() * 0.30f * row); + ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); + ImGui::Text("min_row_height = %.2f", min_row_height); + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + static const char* template_items_names[] = { "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2bac1155..d33654c9 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -724,9 +724,9 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in many cases. // (To be able to honor this we might be able to store a log of cells width, per row, for visible rows, but nav/programmatic scroll would have visible artifacts.) //if (column->Flags & ImGuiTableColumnFlags_AlignRight) - // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]); + // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->ContentWidthRowsUnfrozen); //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) - // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]), 0.5f); + // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f); // Reset content width variables const float initial_max_pos_x = column->MinX + table->CellPaddingX1; @@ -1401,8 +1401,10 @@ void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float min_row_height) table->RowFlags = row_flags; TableBeginRow(table); - // We honor min_height requested by user, but cannot guarantee per-row maximum height as that would essentially require a unique clipping rectangle per-cell. - table->RowPosY2 += min_row_height; + // We honor min_row_height requested by user, but cannot guarantee per-row maximum height, + // because that would essentially require a unique clipping rectangle per-cell. + table->RowPosY2 += table->CellPaddingY * 2.0f; + table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + min_row_height); TableBeginCell(table, 0); } @@ -1447,8 +1449,6 @@ void ImGui::TableEndRow(ImGuiTable* table) TableEndCell(table); - table->RowPosY2 += table->CellPaddingY; - // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. // However it is likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. window->DC.CursorPos.y = table->RowPosY2; @@ -1605,7 +1605,7 @@ void ImGui::TableEndCell(ImGuiTable* table) else p_max_pos_x = table->IsFreezeRowsPassed ? &column->ContentMaxPosRowsUnfrozen : &column->ContentMaxPosRowsFrozen; *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x); - table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y); + table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->CellPaddingY); // Propagate text baseline for the entire row // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one. @@ -1682,6 +1682,9 @@ bool ImGui::TableSetColumnIndex(int column_idx) return (table->VisibleMaskByIndex & ((ImU64)1 << column_idx)) != 0; } +// Return the cell rectangle based on currently known height. +// Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations. +// The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it. ImRect ImGui::TableGetCellRect() { ImGuiContext& g = *GImGui; @@ -1805,7 +1808,7 @@ void ImGui::TableAutoHeaders() ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); - TableNextRow(ImGuiTableRowFlags_Headers, GetTextLineHeight()); + TableNextRow(ImGuiTableRowFlags_Headers, GetTextLineHeight() + g.Style.CellPadding.y * 2.0f); if (window->SkipItems) return; @@ -1909,6 +1912,7 @@ void ImGui::TableHeader(const char* label) float row_height = GetTextLineHeight(); ImRect cell_r = TableGetCellRect(); + //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] ImRect work_r = cell_r; work_r.Min.x = window->DC.CursorPos.x; work_r.Max.y = work_r.Min.y + row_height; From e85c226da40f9bd30f5dc562fe32d590b913ca3c Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 3 Jan 2020 18:27:11 +0100 Subject: [PATCH 398/959] Tables: Fix reordering across hidden columns. Fix for frozen columns to never be larger than scrolling visible rect width. --- imgui_tables.cpp | 43 ++++++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d33654c9..b17c1369 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -346,12 +346,26 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) table->HeldHeaderColumn = -1; if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0) { - IM_ASSERT(table->ReorderColumnDir == -1 || table->ReorderColumnDir == +1); + // We need to handle reordering across hidden columns. + // In the configuration below, moving C to the right of E will lead to: + // ... C [D] E ---> ... [D] E C (Column name/index) + // ... 2 3 4 ... 2 3 4 (Display order) + const int reorder_dir = table->ReorderColumnDir; + IM_ASSERT(reorder_dir == -1 || reorder_dir == +1); IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); - ImGuiTableColumn* dragged_column = &table->Columns[table->ReorderColumn]; - ImGuiTableColumn* target_column = &table->Columns[(table->ReorderColumnDir == -1) ? dragged_column->PrevActiveColumn : dragged_column->NextActiveColumn]; - ImSwap(table->DisplayOrder[dragged_column->IndexDisplayOrder], table->DisplayOrder[target_column->IndexDisplayOrder]); - ImSwap(dragged_column->IndexDisplayOrder, target_column->IndexDisplayOrder); + ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn]; + ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevActiveColumn : src_column->NextActiveColumn]; + IM_UNUSED(dst_column); + const int src_order = src_column->IndexDisplayOrder; + const int dst_order = dst_column->IndexDisplayOrder; + src_column->IndexDisplayOrder = (ImS8)dst_order; + for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir) + table->Columns[table->DisplayOrder[order_n]].IndexDisplayOrder -= (ImS8)reorder_dir; + IM_ASSERT(dst_column->IndexDisplayOrder == dst_order - reorder_dir); + + // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[], rebuild the later from the former. + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + table->DisplayOrder[table->Columns[column_n].IndexDisplayOrder] = (ImS8)column_n; table->ReorderColumnDir = 0; table->IsSettingsDirty = true; } @@ -690,14 +704,21 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) continue; } - // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. - // Because of this we also know that all of the columns will always fit in table->WorkRect and therefore in table->InnerRect (because ScrollX is off) - if (!(table->Flags & ImGuiTableFlags_ScrollX)) + float max_x = FLT_MAX; + if (table->Flags & ImGuiTableFlags_ScrollX) + { + // Frozen columns can't reach beyond visible width else scrolling will naturally break. + if (order_n < table->FreezeColumnsRequest) + max_x = table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - order_n) * min_column_width; + } + else { - float max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width; - if (offset_x + column->WidthGiven > max_x) - column->WidthGiven = ImMax(max_x - offset_x, min_column_width); + // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. + // Because of this we also know that all of the columns will always fit in table->WorkRect and therefore in table->InnerRect (because ScrollX is off) + max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width; } + if (offset_x + column->WidthGiven > max_x) + column->WidthGiven = ImMax(max_x - offset_x, min_column_width); column->MinX = offset_x; column->MaxX = column->MinX + column->WidthGiven; From 164caa2db7c64ab5c4c8dd059d5e548e985e64b2 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 Jan 2020 11:53:04 +0100 Subject: [PATCH 399/959] Tables: Support for multi-line columns name. Renaming of some fields from BackupXXX to HostXXX. Comments. --- imgui.cpp | 2 +- imgui.h | 5 ++-- imgui_demo.cpp | 2 ++ imgui_internal.h | 8 +++--- imgui_tables.cpp | 63 ++++++++++++++++++++++++++++-------------------- 5 files changed, 47 insertions(+), 33 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 90ff9eff..c8023fdb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2142,7 +2142,7 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) static bool GetSkipItemForListClipping() { ImGuiContext& g = *GImGui; - return (g.CurrentTable ? g.CurrentTable->BackupSkipItems : g.CurrentWindow->SkipItems); + return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems); } // Helper to calculate coarse clipping of large list of evenly sized items. diff --git a/imgui.h b/imgui.h index 3577fe28..e0f51274 100644 --- a/imgui.h +++ b/imgui.h @@ -693,7 +693,8 @@ namespace ImGui IMGUI_API void TableHeader(const char* label); // submit one header cell manually. // Tables: Sorting // - Call TableGetSortSpecs() to retrieve latest sort specs for the table. Return value will be NULL if no sorting. - // - Read ->SpecsChanged to tell if the specs have changed since last call. + // - You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since last call, or the first time. + // - Don't hold on this structure over multiple frames. IMGUI_API const ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). // Tab Bars, Tabs @@ -1856,7 +1857,7 @@ struct ImGuiTableSortSpecs { const ImGuiTableSortSpecsColumn* Specs; // Pointer to sort spec array. int SpecsCount; // Sort spec count. Most often 1 unless e.g. ImGuiTableFlags_MultiSortable is enabled. - bool SpecsChanged; // Set to true by TableGetSortSpecs() call if the specs have changed since the previous call. + bool SpecsChanged; // Set to true by TableGetSortSpecs() call if the specs have changed since the previous call. Use this to sort again! ImU64 ColumnsMask; // Set to the mask of column indexes included in the Specs array. e.g. (1 << N) when column N is sorted. ImGuiTableSortSpecs() { Specs = NULL; SpecsCount = 0; SpecsChanged = false; ColumnsMask = 0x00; } diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 25d035b5..f1c40e0b 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3916,6 +3916,7 @@ static void ShowDemoWindowTables() { MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); + MyItem::s_current_sort_specs = NULL; } // Display data @@ -4104,6 +4105,7 @@ static void ShowDemoWindowTables() { MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); + MyItem::s_current_sort_specs = NULL; } items_need_sort = false; diff --git a/imgui_internal.h b/imgui_internal.h index f897815c..9b980e0d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1918,9 +1918,11 @@ struct ImGuiTable float ResizedColumnNextWidth; ImRect OuterRect; // Note: OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). ImRect WorkRect; - ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. ImRect InnerClipRect; ImRect BackgroundClipRect; // We use this to cpu-clip cell background color fill + ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. + ImRect HostWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() + ImVec2 HostCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() ImGuiWindow* OuterWindow; // Parent window for the table ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names @@ -1956,9 +1958,7 @@ struct ImGuiTable bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) bool IsResetDisplayOrderRequest; bool IsFreezeRowsPassed; // Set when we got past the frozen row (the first one). - bool BackupSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis - ImRect BackupWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() - ImVec2 BackupCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() + bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis ImGuiTable() { diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b17c1369..24519c97 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -232,6 +232,13 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG PushID(instance_id); } + // Backup a copy of host window members we will modify + ImGuiWindow* inner_window = table->InnerWindow; + table->HostClipRect = inner_window->ClipRect; + table->HostSkipItems = inner_window->SkipItems; + table->HostWorkRect = inner_window->WorkRect; + table->HostCursorMaxPos = inner_window->DC.CursorMaxPos; + // Borders // - None ........Content..... Pad .....Content........ // - VOuter | Pad ..Content..... Pad .....Content.. Pad | // FIXME-TABLE: Not handled properly @@ -239,7 +246,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // - VOuter+VInner | Pad ..Content.. Pad | Pad ..Content.. Pad | const bool has_cell_padding_x = (flags & ImGuiTableFlags_BordersVOuter) != 0; - ImGuiWindow* inner_window = table->InnerWindow; table->CellPaddingX1 = has_cell_padding_x ? g.Style.CellPadding.x + 1.0f : 0.0f; table->CellPaddingX2 = has_cell_padding_x ? g.Style.CellPadding.x : 0.0f; table->CellPaddingY = g.Style.CellPadding.y; @@ -249,7 +255,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->CurrentRow = -1; table->RowBgColorCounter = 0; table->LastRowFlags = ImGuiTableRowFlags_None; - table->HostClipRect = inner_window->ClipRect; table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width table->InnerClipRect.ClipWith(table->HostClipRect); @@ -306,11 +311,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (table->IsSettingsRequestLoad) TableLoadSettings(table); - // Grab a copy of window fields we will modify - table->BackupSkipItems = inner_window->SkipItems; - table->BackupWorkRect = inner_window->WorkRect; - table->BackupCursorMaxPos = inner_window->DC.CursorMaxPos; - // Disable output until user calls TableNextRow() or TableNextCell() leading to the TableUpdateLayout() call.. // This is not strictly necessary but will reduce cases were misleading "out of table" output will be confusing to the user. // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. @@ -756,7 +756,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } // Don't decrement auto-fit counters until container window got a chance to submit its items - if (table->BackupSkipItems == false) + if (table->HostSkipItems == false) { column->AutoFitQueue >>= 1; column->CannotSkipItemsQueue >>= 1; @@ -896,8 +896,8 @@ void ImGui::EndTable() TableEndRow(table); // Finalize table height - inner_window->SkipItems = table->BackupSkipItems; - inner_window->DC.CursorMaxPos = table->BackupCursorMaxPos; + inner_window->SkipItems = table->HostSkipItems; + inner_window->DC.CursorMaxPos = table->HostCursorMaxPos; if (inner_window != outer_window) { table->OuterRect.Max.y = ImMax(table->OuterRect.Max.y, inner_window->Pos.y + inner_window->Size.y); @@ -970,8 +970,8 @@ void ImGui::EndTable() } // Layout in outer window - inner_window->WorkRect = table->BackupWorkRect; - inner_window->SkipItems = table->BackupSkipItems; + inner_window->WorkRect = table->HostWorkRect; + inner_window->SkipItems = table->HostSkipItems; outer_window->DC.CursorPos = table->OuterRect.Min; outer_window->DC.ColumnsOffset.x = 0.0f; if (inner_window != outer_window) @@ -1594,7 +1594,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) // FIXME-COLUMNS: Setup baseline, preserve across columns (how can we obtain first line baseline tho..) // window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); - window->SkipItems = column->IsClipped ? true : table->BackupSkipItems; + window->SkipItems = column->IsClipped ? true : table->HostSkipItems; if (table->Flags & ImGuiTableFlags_NoClipX) { table->DrawSplitter.SetCurrentChannel(window->DrawList, 1); @@ -1828,15 +1828,23 @@ void ImGui::TableAutoHeaders() ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); + const int columns_count = table->ColumnsCount; + + // Calculate row height (for the unlikely case that labels may be are multi-line) + float row_height = GetTextLineHeight(); + for (int column_n = 0; column_n < columns_count; column_n++) + if (TableGetColumnIsVisible(column_n)) + row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y); + row_height += g.Style.CellPadding.y * 2.0f; - TableNextRow(ImGuiTableRowFlags_Headers, GetTextLineHeight() + g.Style.CellPadding.y * 2.0f); + // Open row + TableNextRow(ImGuiTableRowFlags_Headers, row_height); if (window->SkipItems) return; // This for loop is constructed to not make use of internal functions, // as this is intended to be a base template to copy and build from. int open_context_popup = INT_MAX; - const int columns_count = table->ColumnsCount; for (int column_n = 0; column_n < columns_count; column_n++) { if (!TableSetColumnIndex(column_n)) @@ -1873,7 +1881,7 @@ void ImGui::TableAutoHeaders() // FIXME-TABLE: This is not user-land code any more... // FIXME-TABLE: Need to explain why this is here! - window->SkipItems = table->BackupSkipItems; + window->SkipItems = table->HostSkipItems; // Allow opening popup from the right-most section after the last column // FIXME-TABLE: This is not user-land code any more... perhaps instead we should expose hovered column. @@ -1918,6 +1926,7 @@ void ImGui::TableAutoHeaders() // Emit a column header (text + optional sort order) // We cpu-clip text here so that all columns headers can be merged into a same draw call. // FIXME-TABLE: Should hold a selection state. +// FIXME-TABLE: Style confusion between CellPadding.y and FramePadding.y void ImGui::TableHeader(const char* label) { ImGuiContext& g = *GImGui; @@ -1931,19 +1940,21 @@ void ImGui::TableHeader(const char* label) const int column_n = table->CurrentColumn; ImGuiTableColumn* column = &table->Columns[column_n]; - float row_height = GetTextLineHeight(); - ImRect cell_r = TableGetCellRect(); - //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] - ImRect work_r = cell_r; - work_r.Min.x = window->DC.CursorPos.x; - work_r.Max.y = work_r.Min.y + row_height; - // Label if (label == NULL) label = ""; const char* label_end = FindRenderedTextEnd(label); ImVec2 label_size = CalcTextSize(label, label_end, true); ImVec2 label_pos = window->DC.CursorPos; + + // If we already got a row height, there's use that. + ImRect cell_r = TableGetCellRect(); + float label_height = ImMax(label_size.y, cell_r.GetHeight() - g.Style.CellPadding.y * 2.0f); + + //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] + ImRect work_r = cell_r; + work_r.Min.x = window->DC.CursorPos.x; + work_r.Max.y = work_r.Min.y + label_height; float ellipsis_max = work_r.Max.x; // Selectable @@ -1954,7 +1965,7 @@ void ImGui::TableHeader(const char* label) // Keep header highlighted when context menu is open. (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceNo); - const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld, ImVec2(0.0f, row_height)); + const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld, ImVec2(0.0f, label_height)); const bool held = IsItemActive(); if (held) table->HeldHeaderColumn = (ImS8)column_n; @@ -2016,7 +2027,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 + row_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size); + 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); // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging. // FIXME-TABLE: Clarify policies of how label width and potential decorations (arrows) fit into auto-resize of the column @@ -2066,7 +2077,7 @@ void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* click } // Return NULL if no sort specs. -// Return ->WantSort == true when the specs have changed since the last query. +// You can sort your data again when 'SpecsChanged == true'.It will be true with sorting specs have changed since last call, or the first time. const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() { ImGuiContext& g = *GImGui; From 31de16106632bdf93763653fa9f3e71621aff883 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 Jan 2020 12:21:15 +0100 Subject: [PATCH 400/959] Tables: Fix for hiding first column (fix fcceff5c + reading PrevLineTextBaseOffset in EndCell of inactive column). --- imgui_tables.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 24519c97..b3958d23 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1449,6 +1449,7 @@ void ImGui::TableBeginRow(ImGuiTable* table) table->RowPosY1 = table->RowPosY2 = next_y1; table->RowTextBaseline = 0.0f; + window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.CursorMaxPos.y = next_y1; // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging. @@ -1569,6 +1570,7 @@ void ImGui::TableEndRow(ImGuiTable* table) // [Internal] Called by TableNextRow()TableNextCell()! // This is called a lot, so we need to be mindful of unnecessary overhead. +// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. void ImGui::TableBeginCell(ImGuiTable* table, int column_no) { table->CurrentColumn = column_no; @@ -1839,7 +1841,7 @@ void ImGui::TableAutoHeaders() // Open row TableNextRow(ImGuiTableRowFlags_Headers, row_height); - if (window->SkipItems) + if (table->HostSkipItems) // Merely an optimization return; // This for loop is constructed to not make use of internal functions, @@ -1879,8 +1881,7 @@ void ImGui::TableAutoHeaders() open_context_popup = column_n; } - // FIXME-TABLE: This is not user-land code any more... - // FIXME-TABLE: Need to explain why this is here! + // FIXME-TABLE: This is not user-land code any more + need to explain WHY this is here! window->SkipItems = table->HostSkipItems; // Allow opening popup from the right-most section after the last column From 2958e3731009bb9e8e16c633fed87e003cb934fd Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 Jan 2020 17:31:26 +0100 Subject: [PATCH 401/959] Tables: Storing per-column SkipItems as a shortcut. Comments, Spacings. # Conflicts: # imgui_internal.h --- imgui.h | 2 +- imgui_demo.cpp | 2 +- imgui_internal.h | 21 +++++++++------------ imgui_tables.cpp | 34 ++++++++++++++++++---------------- 4 files changed, 29 insertions(+), 30 deletions(-) diff --git a/imgui.h b/imgui.h index e0f51274..e03b8985 100644 --- a/imgui.h +++ b/imgui.h @@ -694,7 +694,7 @@ namespace ImGui // Tables: Sorting // - Call TableGetSortSpecs() to retrieve latest sort specs for the table. Return value will be NULL if no sorting. // - You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since last call, or the first time. - // - Don't hold on this structure over multiple frames. + // - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! IMGUI_API const ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). // Tab Bars, Tabs diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f1c40e0b..5c300e54 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3618,7 +3618,7 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); - + if (ImGui::BeginTable("##table1", 7, flags, size)) { ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of ImGuiTableFlags_ScrollFreezeLeftColumn diff --git a/imgui_internal.h b/imgui_internal.h index 9b980e0d..1b3eb592 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1823,11 +1823,12 @@ struct ImGuiTabBar #define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code #define IMGUI_TABLE_MAX_COLUMNS 64 // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64. -// [Internal] sizeof() ~ 96 +// [Internal] sizeof() ~ 100 struct ImGuiTableColumn { + ImRect ClipRect; // Clipping rectangle for the column ImGuiID UserID; // Optional, value passed to TableSetupColumn() - ImGuiTableColumnFlags FlagsIn; // Flags as input by user. See ImGuiTableColumnFlags_ + ImGuiTableColumnFlags FlagsIn; // Flags as they were provided by user. See ImGuiTableColumnFlags_ ImGuiTableColumnFlags Flags; // Effective flags. See ImGuiTableColumnFlags_ float ResizeWeight; // ~1.0f. Master width data when (Flags & _WidthStretch) float MinX; // Absolute positions @@ -1836,19 +1837,19 @@ struct ImGuiTableColumn float WidthGiven; // == (MaxX - MinX). FIXME-TABLE: Store all persistent width in multiple of FontSize? float StartXRows; // Start position for the frame, currently ~(MinX + CellPaddingX) float StartXHeaders; - ImS16 ContentWidthRowsFrozen; // Contents width. Because freezing is non correlated from headers we need all 4 variants (ImDrawCmd merging uses different data than alignment code). - ImS16 ContentWidthRowsUnfrozen; // (encoded as ImS16 because we actually rarely use those width) - ImS16 ContentWidthHeadersUsed; // TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls - ImS16 ContentWidthHeadersDesired; float ContentMaxPosRowsFrozen; // Submitted contents absolute maximum position, from which we can infer width. float ContentMaxPosRowsUnfrozen; // (kept as float because we need to manipulate those between each cell change) float ContentMaxPosHeadersUsed; float ContentMaxPosHeadersDesired; - ImRect ClipRect; - ImS16 NameOffset; // Offset into parent ColumnsName[] + ImS16 ContentWidthRowsFrozen; // Contents width. Because row freezing is not correlated with headers/not-headers we need all 4 variants (ImDrawCmd merging uses different data than alignment code). + ImS16 ContentWidthRowsUnfrozen; // (encoded as ImS16 because we actually rarely use those width) + ImS16 ContentWidthHeadersUsed; // TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls + ImS16 ContentWidthHeadersDesired; + ImS16 NameOffset; // Offset into parent ColumnsNames[] bool IsActive; // Is the column not marked Hidden by the user (regardless of clipping). We're not calling this "Visible" here because visibility also depends on clipping. bool NextIsActive; bool IsClipped; // Set when not overlapping the host window clipping rectangle. We don't use the opposite "!Visible" name because Clipped can be altered by events. + bool SkipItems; ImS8 IndexDisplayOrder; // Index within DisplayOrder[] (column may be reordered by users) ImS8 IndexWithinActiveSet; // Index within active set (<= IndexOrder) ImS8 DrawChannelCurrent; // Index within DrawSplitter.Channels[] @@ -2178,10 +2179,6 @@ namespace ImGui IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); // Tables - //IMGUI_API int GetTableColumnNo(); - //IMGUI_API bool SetTableColumnNo(int column_n); - //IMGUI_API int GetTableLineNo(); - IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void TableBeginUpdateColumns(ImGuiTable* table); IMGUI_API void TableUpdateDrawChannels(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b3958d23..781392b8 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -68,20 +68,22 @@ // - TableBeginUpdateColumns() - apply resize/order requests, lock columns active state, order // - TableSetupColumn() user submit columns details (optional) // - TableAutoHeaders() or TableHeader() user submit a headers row (optional) -// - TableSortSpecsClickColumn() +// - TableSortSpecsClickColumn() - when clicked: alter sort order and sort direction // - TableGetSortSpecs() user queries updated sort specs (optional) // - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders() -// - TableUpdateLayout() - called by the FIRST call to TableNextRow() -// - TableUpdateDrawChannels() - setup ImDrawList channels -// - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission -// - TableDrawContextMenu() - draw right-click context menu +// - TableUpdateLayout() - called by the FIRST call to TableNextRow()! +// - TableUpdateDrawChannels() - setup ImDrawList channels +// - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +// - TableDrawContextMenu() - draw right-click context menu +// - TableEndCell() - close existing cell if not the first time +// - TableBeginCell() - enter into current cell // - [...] user emit contents // - EndTable() user ends the table // - TableDrawBorders() - draw outer borders, inner vertical borders // - TableDrawMergeChannels() - merge draw channels if clipping isn't required // - TableSetColumnWidth() - apply resizing width -// - TableUpdateColumnsWeightFromWidth() -// - EndChild() - (if ScrollX/ScrollY is set) +// - TableUpdateColumnsWeightFromWidth() - recompute columns weights (of weighted columns) from their respective width +// - EndChild() - (if ScrollX/ScrollY is set) //----------------------------------------------------------------------------- // Configuration @@ -700,7 +702,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->ClipRect.Max.x = offset_x; column->ClipRect.Max.y = FLT_MAX; column->ClipRect.ClipWithFull(host_clip_rect); - column->IsClipped = true; + column->IsClipped = column->SkipItems = true; continue; } @@ -731,6 +733,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->ClipRect.ClipWithFull(host_clip_rect); column->IsClipped = (column->ClipRect.Max.x <= column->ClipRect.Min.x) && (column->AutoFitQueue & 1) == 0 && (column->CannotSkipItemsQueue & 1) == 0; + column->SkipItems = column->IsClipped || table->HostSkipItems; if (column->IsClipped) { // Columns with the _WidthAlwaysAutoResize sizing policy will never be updated then. @@ -1580,9 +1583,10 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) const float start_x = (table->RowFlags & ImGuiTableRowFlags_Headers) ? column->StartXHeaders : column->StartXRows; window->DC.LastItemId = 0; - window->DC.CursorPos = ImVec2(start_x, table->RowPosY1 + table->CellPaddingY); + window->DC.CursorPos.x = start_x; + window->DC.CursorPos.y = table->RowPosY1 + table->CellPaddingY; window->DC.CursorMaxPos.x = window->DC.CursorPos.x; - window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT // FIXME-TABLE: Recurse + window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT window->DC.CurrLineTextBaseOffset = table->RowTextBaseline; window->WorkRect.Min.y = window->DC.CursorPos.y; @@ -1593,10 +1597,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) if (!column->IsActive) window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2); - // FIXME-COLUMNS: Setup baseline, preserve across columns (how can we obtain first line baseline tho..) - // window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); - - window->SkipItems = column->IsClipped ? true : table->HostSkipItems; + window->SkipItems = column->SkipItems; if (table->Flags & ImGuiTableFlags_NoClipX) { table->DrawSplitter.SetCurrentChannel(window->DrawList, 1); @@ -1615,7 +1616,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) } } -// [Internal] Called by TableNextRow()TableNextCell()! +// [Internal] Called by TableNextRow()/TableNextCell()! void ImGui::TableEndCell(ImGuiTable* table) { ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; @@ -2078,7 +2079,8 @@ void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* click } // Return NULL if no sort specs. -// You can sort your data again when 'SpecsChanged == true'.It will be true with sorting specs have changed since last call, or the first time. +// You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since last call, or the first time. +// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() { ImGuiContext& g = *GImGui; From 0e7b3f2f2f9e0008462ce6acfd64c4b520390e00 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 Jan 2020 21:10:45 +0100 Subject: [PATCH 402/959] Tables: Made only first column honor Indent by default (like Columns api) and exposed flags. Added simple Tree demo. --- imgui.h | 3 ++ imgui_demo.cpp | 81 ++++++++++++++++++++++++++++++++++++++++++++++-- imgui_internal.h | 1 + imgui_tables.cpp | 7 ++++- 4 files changed, 89 insertions(+), 3 deletions(-) diff --git a/imgui.h b/imgui.h index e03b8985..47dfe1b9 100644 --- a/imgui.h +++ b/imgui.h @@ -1078,9 +1078,12 @@ enum ImGuiTableColumnFlags_ ImGuiTableColumnFlags_NoHeaderWidth = 1 << 11, // Header width don't contribute to automatic column width. ImGuiTableColumnFlags_PreferSortAscending = 1 << 12, // Make the initial sort direction Ascending when first sorting on this column (default). ImGuiTableColumnFlags_PreferSortDescending = 1 << 13, // Make the initial sort direction Descending when first sorting on this column. + ImGuiTableColumnFlags_IndentEnable = 1 << 14, // Use current Indent value when entering cell (default for 1st column). + ImGuiTableColumnFlags_IndentDisable = 1 << 15, // Ignore current Indent value when entering cell (default for columns after the 1st one). Indentation changes _within_ the cell will still be honored. // [Internal] Combinations and masks ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthAlwaysAutoResize, + ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, ImGuiTableColumnFlags_NoDirectResize_ = 1 << 20 // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 5c300e54..570fa75c 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3679,6 +3679,8 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("_NoSortDescending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoSortDescending); ImGui::CheckboxFlags("_PreferSortAscending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_PreferSortAscending); ImGui::CheckboxFlags("_PreferSortDescending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_PreferSortDescending); + ImGui::CheckboxFlags("_IndentEnable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentEnable); + ImGui::CheckboxFlags("_IndentDisable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentDisable); ImGui::PopID(); ImGui::PopStyleVar(2); } @@ -3687,20 +3689,23 @@ static void ShowDemoWindowTables() // Create the real table we care about for the example! const ImGuiTableFlags flags = ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable; - if (ImGui::BeginTable("##table1", column_count, flags)) + if (ImGui::BeginTable("##table", column_count, flags)) { for (int column = 0; column < column_count; column++) ImGui::TableSetupColumn(column_names[column], column_flags[column]); ImGui::TableAutoHeaders(); for (int row = 0; row < 8; row++) { + ImGui::Indent(2.0f); // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags. ImGui::TableNextRow(); for (int column = 0; column < column_count; column++) { ImGui::TableSetColumnIndex(column); - ImGui::Text("Hello %s", ImGui::TableGetColumnName(column)); + ImGui::Text("%s %s", (column == 0) ? "Indented" : "Hello", ImGui::TableGetColumnName(column)); } } + ImGui::Unindent(2.0f * 8.0f); + ImGui::EndTable(); } ImGui::TreePop(); @@ -3863,6 +3868,78 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Tree view")) + { + static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersHOuter | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg; + //ImGui::CheckboxFlags("ImGuiTableFlags_Scroll", (unsigned int*)&flags, ImGuiTableFlags_Scroll); + //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); + + if (ImGui::BeginTable("##3ways", 3, flags)) + { + // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On + ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); + ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 10); + ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 20); + ImGui::TableAutoHeaders(); + + // Simple storage to output a dummy file-system. + struct MyTreeNode + { + const char* Name; + const char* Type; + int Size; + int ChildIdx; + int ChildCount; + static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes) + { + ImGui::TableNextRow(); + const bool is_folder = (node->ChildCount > 0); + if (is_folder) + { + bool open = ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextCell(); + ImGui::TextDisabled("--"); + ImGui::TableNextCell(); + ImGui::TextUnformatted(node->Type); + if (open) + { + for (int child_n = 0; child_n < node->ChildCount; child_n++) + DisplayNode(&all_nodes[node->ChildIdx + child_n], all_nodes); + ImGui::TreePop(); + } + } + else + { + ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth); + ImGui::TableNextCell(); + ImGui::Text("%d", node->Size); + ImGui::TableNextCell(); + ImGui::TextUnformatted(node->Type); + } + } + }; + static const MyTreeNode nodes[] = + { + { "Root", "Folder", -1, 1, 3 }, // 0 + { "Music", "Folder", -1, 4, 2 }, // 1 + { "Textures", "Folder", -1, 6, 3 }, // 2 + { "desktop.ini", "System file", 1024, -1,-1 }, // 3 + { "File1_a.wav", "Audio file", 123000, -1,-1 }, // 4 + { "File1_b.wav", "Audio file", 456000, -1,-1 }, // 5 + { "Image001.png", "Image file", 203128, -1,-1 }, // 6 + { "Copy of Image001.png", "Image file", 203256, -1,-1 }, // 7 + { "Copy of Image001 (Final2).png","Image file", 203512, -1,-1 }, // 8 + }; + + MyTreeNode::DisplayNode(&nodes[0], nodes); + + ImGui::EndTable(); + } + ImGui::TreePop(); + } + static const char* template_items_names[] = { "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", diff --git a/imgui_internal.h b/imgui_internal.h index 1b3eb592..8fdffd6c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1908,6 +1908,7 @@ struct ImGuiTable ImU32 BorderColorLight; float BorderX1; float BorderX2; + float HostIndentX; float CellPaddingX1; // Padding from each borders float CellPaddingX2; float CellPaddingY; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 781392b8..905375fe 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -236,6 +236,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Backup a copy of host window members we will modify ImGuiWindow* inner_window = table->InnerWindow; + table->HostIndentX = inner_window->DC.Indent.x; table->HostClipRect = inner_window->ClipRect; table->HostSkipItems = inner_window->SkipItems; table->HostWorkRect = inner_window->WorkRect; @@ -552,6 +553,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Adjust flags: default width mode + weighted columns are not allowed when auto extending // FIXME-TABLE: Clarify why we need to do this again here and not just in TableSetupColumn() column->Flags = TableFixColumnFlags(table, column->FlagsIn); + if ((column->Flags & ImGuiTableColumnFlags_IndentMask_) == 0) + column->Flags |= (column_n == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable; // We have a unusual edge case where if the user doesn't call TableGetSortSpecs() but has sorting enabled // or varying sorting flags, we still want the sorting arrows to honor those flags. @@ -1580,7 +1583,9 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) ImGuiTableColumn* column = &table->Columns[column_no]; ImGuiWindow* window = table->InnerWindow; - const float start_x = (table->RowFlags & ImGuiTableRowFlags_Headers) ? column->StartXHeaders : column->StartXRows; + float start_x = (table->RowFlags & ImGuiTableRowFlags_Headers) ? column->StartXHeaders : column->StartXRows; + if (column->Flags & ImGuiTableColumnFlags_IndentEnable) + start_x += window->DC.Indent.x - table->HostIndentX; window->DC.LastItemId = 0; window->DC.CursorPos.x = start_x; From 5431cbd3f026f98c3f7cec6d41be0c11a108b178 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 9 Jan 2020 22:02:16 +0100 Subject: [PATCH 403/959] Tables: Honor width/weight passed to TableSetupColumn() after .ini load since we don't actually restore that data currently. Demo: Remove filter from Advanced Table demo since it's breaking with clipping. --- imgui_demo.cpp | 22 +++++++++++----------- imgui_internal.h | 5 ++--- imgui_tables.cpp | 11 ++++++++--- 3 files changed, 21 insertions(+), 17 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 570fa75c..02a12522 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3661,14 +3661,14 @@ static void ShowDemoWindowTables() { for (int column = 0; column < column_count; column++) { - ImGui::TableNextCell(); // Make the UI compact because there are so many fields + ImGui::TableNextCell(); ImGuiStyle& style = ImGui::GetStyle(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, 2)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, 2)); ImGui::PushID(column); ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation - ImGui::Text("Column '%s'", column_names[column]); + ImGui::Text("Flags for '%s'", column_names[column]); ImGui::CheckboxFlags("_NoResize", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoResize); ImGui::CheckboxFlags("_NoClipX", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoClipX); ImGui::CheckboxFlags("_NoHide", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoHide); @@ -3880,8 +3880,8 @@ static void ShowDemoWindowTables() { // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); - ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 10); - ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 20); + ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 6); + ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 10); ImGui::TableAutoHeaders(); // Simple storage to output a dummy file-system. @@ -4043,10 +4043,10 @@ static void ShowDemoWindowTables() static float inner_width_without_scroll = 0.0f; // Fill static float inner_width_with_scroll = 0.0f; // Auto-extend static bool outer_size_enabled = true; - static bool lock_left_column_visibility = false; + static bool lock_first_column_visibility = false; static bool show_headers = true; static bool show_wrapped_text = false; - static ImGuiTextFilter filter; + //static ImGuiTextFilter filter; //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which affects sizing if (ImGui::TreeNodeEx("Options")) { @@ -4130,10 +4130,10 @@ static void ShowDemoWindowTables() ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); ImGui::DragInt("items_count", &items_count, 0.1f, 0, 5000); ImGui::Combo("contents_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names)); - filter.Draw("filter"); + //filter.Draw("filter"); ImGui::Checkbox("show_headers", &show_headers); ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); - ImGui::Checkbox("lock_left_column_visibility", &lock_left_column_visibility); + ImGui::Checkbox("lock_first_column_visibility", &lock_first_column_visibility); ImGui::Unindent(); ImGui::PopItemWidth(); @@ -4168,7 +4168,7 @@ static void ShowDemoWindowTables() // Declare columns // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! - ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | (lock_left_column_visibility ? ImGuiTableColumnFlags_NoHide : 0), -1.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | (lock_first_column_visibility ? ImGuiTableColumnFlags_NoHide : 0), -1.0f, MyItemColumnID_ID); ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Name); ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Action); ImGui::TableSetupColumn("Quantity Long Label", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 1.0f, MyItemColumnID_Quantity);// , ImGuiTableColumnFlags_None | ImGuiTableColumnFlags_WidthAlwaysAutoResize); @@ -4209,8 +4209,8 @@ static void ShowDemoWindowTables() #endif { MyItem* item = &items[row_n]; - if (!filter.PassFilter(item->Name)) - continue; + //if (!filter.PassFilter(item->Name)) + // continue; const bool item_is_selected = selection.contains(item->ID); ImGui::PushID(item->ID); diff --git a/imgui_internal.h b/imgui_internal.h index 8fdffd6c..af10d17e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1830,9 +1830,9 @@ struct ImGuiTableColumn ImGuiID UserID; // Optional, value passed to TableSetupColumn() ImGuiTableColumnFlags FlagsIn; // Flags as they were provided by user. See ImGuiTableColumnFlags_ ImGuiTableColumnFlags Flags; // Effective flags. See ImGuiTableColumnFlags_ - float ResizeWeight; // ~1.0f. Master width data when (Flags & _WidthStretch) float MinX; // Absolute positions float MaxX; + float ResizeWeight; // ~1.0f. Master width data when (Flags & _WidthStretch) float WidthRequested; // Master width data when !(Flags & _WidthStretch) float WidthGiven; // == (MaxX - MinX). FIXME-TABLE: Store all persistent width in multiple of FontSize? float StartXRows; // Start position for the frame, currently ~(MinX + CellPaddingX) @@ -1865,8 +1865,7 @@ struct ImGuiTableColumn ImGuiTableColumn() { memset(this, 0, sizeof(*this)); - ResizeWeight = 1.0f; - WidthRequested = WidthGiven = -1.0f; + ResizeWeight = WidthRequested = WidthGiven = -1.0f; NameOffset = -1; IsActive = NextIsActive = true; IndexDisplayOrder = IndexWithinActiveSet = -1; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 905375fe..1e1f73d7 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -585,7 +585,9 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) else { IM_ASSERT(column->Flags & ImGuiTableColumnFlags_WidthStretch); - IM_ASSERT(column->ResizeWeight > 0.0f); + const int init_size = (column->ResizeWeight < 0.0f); + if (init_size) + column->ResizeWeight = 1.0f; total_weights += column->ResizeWeight; if (table->LeftMostStretchedColumnDisplayOrder == -1) table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->IndexDisplayOrder; @@ -1378,7 +1380,8 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flags = column->Flags; // Initialize defaults - if (table->IsInitializing && !table->IsSettingsLoaded) + // FIXME-TABLE: We don't restore widths/weight so let's avoid using IsSettingsLoaded for now + if (table->IsInitializing && column->WidthRequested < 0.0f && column->ResizeWeight < 0.0f)// && !table->IsSettingsLoaded) { // Init width or weight // Disable auto-fit if a default fixed width has been specified @@ -1396,7 +1399,9 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, { column->ResizeWeight = 1.0f; } - + } + if (table->IsInitializing && !table->IsSettingsLoaded) + { // Init default visibility/sort state if (flags & ImGuiTableColumnFlags_DefaultHide) column->IsActive = column->NextIsActive = false; From f5eee210a0e3d15a6f694cbc69dbf94aa413f421 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 20 Jan 2020 12:41:23 +0100 Subject: [PATCH 404/959] Tables: TableHeader() uses provided row min header rather than incremental one to allow multi-item multi-line in header cells. Demo TableHeader() - will caveat, comments. --- imgui_demo.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ imgui_internal.h | 1 + imgui_tables.cpp | 8 +++++--- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 02a12522..4ee5b0f7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3940,6 +3940,54 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } + // Demonstrate using TableHeader() calls instead of TableAutoHeaders() + // FIXME-TABLE: Currently this doesn't get us feature-parity with TableAutoHeaders(), e.g. missing context menu. Tables API needs some work! + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Custom headers")) + { + const int COLUMNS_COUNT = 3; + if (ImGui::BeginTable("##table1", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable)) + { + ImGui::TableSetupColumn("Apricot"); + ImGui::TableSetupColumn("Banana"); + ImGui::TableSetupColumn("Cherry"); + + // Dummy entire-column selection storage + // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. + static bool column_selected[3] = {}; + + // Instead of calling TableAutoHeaders() we'll submit custom headers ourselves + ImGui::TableNextRow(ImGuiTableRowFlags_Headers); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + ImGui::TableSetColumnIndex(column); + const char* column_name = ImGui::TableGetColumnName(column); // Retrieve name passed to TableSetupColumn() + ImGui::PushID(column); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); + ImGui::Checkbox("##checkall", &column_selected[column]); + ImGui::PopStyleVar(); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::TableHeader(column_name); + ImGui::PopID(); + } + + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + char buf[32]; + sprintf(buf, "Cell %d,%d", row, column); + ImGui::TableSetColumnIndex(column); + ImGui::Selectable(buf, column_selected[column]); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + static const char* template_items_names[] = { "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", diff --git a/imgui_internal.h b/imgui_internal.h index af10d17e..efb04012 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1898,6 +1898,7 @@ struct ImGuiTable ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with float RowPosY1; float RowPosY2; + float RowMinHeight; // Height submitted to TableNextRow() float RowTextBaseline; ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ ImGuiTableRowFlags LastRowFlags : 16; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 1e1f73d7..87eb64fe 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1419,7 +1419,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, } // Starts into the first cell of a new row -void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float min_row_height) +void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height) { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; @@ -1431,12 +1431,13 @@ void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float min_row_height) table->LastRowFlags = table->RowFlags; table->RowFlags = row_flags; + table->RowMinHeight = row_min_height; TableBeginRow(table); // We honor min_row_height requested by user, but cannot guarantee per-row maximum height, // because that would essentially require a unique clipping rectangle per-cell. table->RowPosY2 += table->CellPaddingY * 2.0f; - table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + min_row_height); + table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height); TableBeginCell(table, 0); } @@ -1937,6 +1938,7 @@ void ImGui::TableAutoHeaders() // Emit a column header (text + optional sort order) // We cpu-clip text here so that all columns headers can be merged into a same draw call. +// Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() // FIXME-TABLE: Should hold a selection state. // FIXME-TABLE: Style confusion between CellPadding.y and FramePadding.y void ImGui::TableHeader(const char* label) @@ -1961,7 +1963,7 @@ void ImGui::TableHeader(const char* label) // If we already got a row height, there's use that. ImRect cell_r = TableGetCellRect(); - float label_height = ImMax(label_size.y, cell_r.GetHeight() - g.Style.CellPadding.y * 2.0f); + float label_height = ImMax(label_size.y, table->RowMinHeight - g.Style.CellPadding.y * 2.0f); //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] ImRect work_r = cell_r; From 787a309445d18db5823857c0fb43268f4d1b2efe Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 22 Jan 2020 17:04:54 +0100 Subject: [PATCH 405/959] Tables: Fixed headers closing popups. --- imgui_tables.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 87eb64fe..0f3475bb 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1979,7 +1979,7 @@ void ImGui::TableHeader(const char* label) // Keep header highlighted when context menu is open. (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceNo); - const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld, ImVec2(0.0f, label_height)); + const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld | ImGuiSelectableFlags_DontClosePopups, ImVec2(0.0f, label_height)); const bool held = IsItemActive(); if (held) table->HeldHeaderColumn = (ImS8)column_n; From 104ec408a890a56778e9980dd5ae3790b71ab4cf Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 6 Feb 2020 18:34:37 +0100 Subject: [PATCH 406/959] Tables: Fixed content size calculation creating feedback loops. Fixed handling of _DefaultSort with _PreferSortXXXflags (@parbo). Comments. --- imgui.h | 4 ++-- imgui_demo.cpp | 2 +- imgui_tables.cpp | 13 ++++++++++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/imgui.h b/imgui.h index 47dfe1b9..3be894f8 100644 --- a/imgui.h +++ b/imgui.h @@ -1066,9 +1066,9 @@ enum ImGuiTableColumnFlags_ ImGuiTableColumnFlags_None = 0, ImGuiTableColumnFlags_DefaultHide = 1 << 0, // Default as a hidden column. ImGuiTableColumnFlags_DefaultSort = 1 << 1, // Default as a sorting column. - ImGuiTableColumnFlags_WidthFixed = 1 << 2, // Column will keep a fixed size, preferable with horizontal scrolling enabled (default if table sizing policy is SizingPolicyFixedX). + ImGuiTableColumnFlags_WidthFixed = 1 << 2, // Column will keep a fixed size, preferable with horizontal scrolling enabled (default if table sizing policy is SizingPolicyFixedX and table is resizable). ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch, preferable with horizontal scrolling disabled (default if table sizing policy is SizingPolicyStretchX). - ImGuiTableColumnFlags_WidthAlwaysAutoResize = 1 << 4, // Column will keep resizing based on submitted contents (with a one frame delay) == Fixed with auto resize + ImGuiTableColumnFlags_WidthAlwaysAutoResize = 1 << 4, // Column will keep resizing based on submitted contents (with a one frame delay) == Fixed with auto resize (default if table sizing policy is SizingPolicyFixedX and table is not resizable). ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. ImGuiTableColumnFlags_NoClipX = 1 << 6, // Disable clipping for this column (all NoClipX columns will render in a same draw command). ImGuiTableColumnFlags_NoSort = 1 << 7, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 4ee5b0f7..22338f79 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3795,7 +3795,7 @@ static void ShowDemoWindowTables() case CT_LongText: ImGui::Text("Some longer text %d,%d\nOver two lines..", row, column); break; case CT_Button: ImGui::Button(label); break; case CT_StretchButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break; - case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText(label, text_buf, IM_ARRAYSIZE(text_buf)); break; + case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_ARRAYSIZE(text_buf)); break; } } } diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0f3475bb..9798f432 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -487,6 +487,7 @@ static ImGuiTableColumnFlags TableFixColumnFlags(ImGuiTable* table, ImGuiTableCo // Sizing Policy if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0) { + // FIXME-TABLE: Inconsistent to promote columns to WidthAlwaysAutoResize if (table->Flags & ImGuiTableFlags_SizingPolicyFixedX) flags |= ((table->Flags & ImGuiTableFlags_Resizable) && !(flags & ImGuiTableColumnFlags_NoResize)) ? ImGuiTableColumnFlags_WidthFixed : ImGuiTableColumnFlags_WidthAlwaysAutoResize; else @@ -536,7 +537,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Compute offset, clip rect for the frame const ImRect work_rect = table->WorkRect; - const float padding_auto_x = table->CellPaddingX1; // Can't make auto padding larger than what WorkRect knows about so right-alignment matches. + const float padding_auto_x = table->CellPaddingX2; // Can't make auto padding larger than what WorkRect knows about so right-alignment matches. const float min_column_width = TableGetMinColumnWidth(); int count_fixed = 0; @@ -595,12 +596,13 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } // Layout + // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible const float width_spacings = table->CellSpacingX * (table->ColumnsActiveCount - 1); float width_avail; if ((table->Flags & ImGuiTableFlags_ScrollX) && (table->InnerWidth == 0.0f)) width_avail = table->InnerClipRect.GetWidth() - width_spacings - 1.0f; else - width_avail = work_rect.GetWidth() - width_spacings - 1.0f; // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible + width_avail = work_rect.GetWidth() - width_spacings - 1.0f; const float width_avail_for_stretched_columns = width_avail - width_fixed; float width_remaining_for_stretched_columns = width_avail_for_stretched_columns; @@ -1406,7 +1408,10 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, if (flags & ImGuiTableColumnFlags_DefaultHide) column->IsActive = column->NextIsActive = false; if (flags & ImGuiTableColumnFlags_DefaultSort) + { column->SortOrder = 0; // Multiple columns using _DefaultSort will be reordered when building the sort specs. + column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); + } } // Store name (append with zero-terminator in contiguous buffer) @@ -2090,7 +2095,7 @@ void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* click table->IsSortSpecsDirty = true; } -// Return NULL if no sort specs. +// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set) // You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since last call, or the first time. // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() @@ -2439,10 +2444,12 @@ void ImGui::DebugNodeTable(ImGuiTable* table) BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" "Active: %d, Clipped: %d, DrawChannels: %d,%d\n" "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" + "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Desired %d/%d\n" "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", n, column->IndexDisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, column->WidthGiven, column->WidthRequested, column->ResizeWeight, + column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersDesired, column->UserID, column->Flags, (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "", From 643cf6fc8cfe7e489c7f1f6395d237efffbe1756 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 10 Feb 2020 15:48:08 +0100 Subject: [PATCH 407/959] Tables: Added ImGuiTableFlags_NoKeepColumnsVisible wip flag useful for layout purpose. (WIP) --- imgui.h | 21 +++++++++++---------- imgui_tables.cpp | 3 ++- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/imgui.h b/imgui.h index 3be894f8..067c4f21 100644 --- a/imgui.h +++ b/imgui.h @@ -1040,21 +1040,22 @@ enum ImGuiTableFlags_ ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use WidthStretch policy. Read description above for more details. ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 17, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small. // Scrolling - ImGuiTableFlags_ScrollX = 1 << 17, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - ImGuiTableFlags_ScrollY = 1 << 18, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + ImGuiTableFlags_ScrollX = 1 << 18, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 19, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, - ImGuiTableFlags_ScrollFreezeTopRow = 1 << 19, // We can lock 1 to 3 rows (starting from the top). Use with ScrollY enabled. - ImGuiTableFlags_ScrollFreeze2Rows = 2 << 19, - ImGuiTableFlags_ScrollFreeze3Rows = 3 << 19, - ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << 21, // We can lock 1 to 3 columns (starting from the left). Use with ScrollX enabled. - ImGuiTableFlags_ScrollFreeze2Columns = 2 << 21, - ImGuiTableFlags_ScrollFreeze3Columns = 3 << 21, + ImGuiTableFlags_ScrollFreezeTopRow = 1 << 20, // We can lock 1 to 3 rows (starting from the top). Use with ScrollY enabled. + ImGuiTableFlags_ScrollFreeze2Rows = 2 << 20, + ImGuiTableFlags_ScrollFreeze3Rows = 3 << 20, + ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << 22, // We can lock 1 to 3 columns (starting from the left). Use with ScrollX enabled. + ImGuiTableFlags_ScrollFreeze2Columns = 2 << 22, + ImGuiTableFlags_ScrollFreeze3Columns = 3 << 22, // [Internal] Combinations and masks ImGuiTableFlags_SizingPolicyMaskX_ = ImGuiTableFlags_SizingPolicyStretchX | ImGuiTableFlags_SizingPolicyFixedX, - ImGuiTableFlags_ScrollFreezeRowsShift_ = 19, - ImGuiTableFlags_ScrollFreezeColumnsShift_ = 21, + ImGuiTableFlags_ScrollFreezeRowsShift_ = 20, + ImGuiTableFlags_ScrollFreezeColumnsShift_ = 22, ImGuiTableFlags_ScrollFreezeRowsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeRowsShift_, ImGuiTableFlags_ScrollFreezeColumnsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeColumnsShift_ }; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 9798f432..fedf1b35 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -724,7 +724,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) { // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. // Because of this we also know that all of the columns will always fit in table->WorkRect and therefore in table->InnerRect (because ScrollX is off) - max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width; + if (!(table->Flags & ImGuiTableFlags_NoKeepColumnsVisible)) + max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width; } if (offset_x + column->WidthGiven > max_x) column->WidthGiven = ImMax(max_x - offset_x, min_column_width); From ae6fc48f6048b171996ad985bd20c23aef221a40 Mon Sep 17 00:00:00 2001 From: Omar Date: Mon, 17 Feb 2020 15:09:50 +0100 Subject: [PATCH 408/959] Tables: Fix sort direction (issue 3023). Remove SortOrder from ImGuiTableSortSpecsColumn. Made sort arrow smaller. Added debug stuff in metrics. --- imgui.h | 19 +++++++++---------- imgui_demo.cpp | 6 +++--- imgui_tables.cpp | 16 ++++++++++------ 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/imgui.h b/imgui.h index 067c4f21..cc380ea0 100644 --- a/imgui.h +++ b/imgui.h @@ -1846,23 +1846,22 @@ struct ImGuiPayload // Sorting specification for one column of a table (sizeof == 8 bytes) struct ImGuiTableSortSpecsColumn { - ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) - ImU8 ColumnIndex; // Index of the column - ImU8 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) - ImS8 SortSign; // +1 or -1 (you can use this or SortDirection, whichever is more convenient for your sort function) - ImS8 SortDirection; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function) + ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) + ImU8 ColumnIndex; // Index of the column + ImU8 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) + ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function) - ImGuiTableSortSpecsColumn() { ColumnUserID = 0; ColumnIndex = 0; SortOrder = 0; SortSign = +1; SortDirection = ImGuiSortDirection_Ascending; } + ImGuiTableSortSpecsColumn() { ColumnUserID = 0; ColumnIndex = 0; SortOrder = 0; SortDirection = ImGuiSortDirection_Ascending; } }; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) // Obtained by calling TableGetSortSpecs() struct ImGuiTableSortSpecs { - const ImGuiTableSortSpecsColumn* Specs; // Pointer to sort spec array. - int SpecsCount; // Sort spec count. Most often 1 unless e.g. ImGuiTableFlags_MultiSortable is enabled. - bool SpecsChanged; // Set to true by TableGetSortSpecs() call if the specs have changed since the previous call. Use this to sort again! - ImU64 ColumnsMask; // Set to the mask of column indexes included in the Specs array. e.g. (1 << N) when column N is sorted. + const ImGuiTableSortSpecsColumn* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1 unless e.g. ImGuiTableFlags_MultiSortable is enabled. + bool SpecsChanged; // Set to true by TableGetSortSpecs() call if the specs have changed since the previous call. Use this to sort again! + ImU64 ColumnsMask; // Set to the mask of column indexes included in the Specs array. e.g. (1 << N) when column N is sorted. ImGuiTableSortSpecs() { Specs = NULL; SpecsCount = 0; SpecsChanged = false; ColumnsMask = 0x00; } }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 22338f79..b91392ae 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3271,10 +3271,10 @@ struct MyItem case MyItemColumnID_Description: delta = (strcmp(a->Name, b->Name)); break; default: IM_ASSERT(0); break; } - if (delta < 0) - return -1 * sort_spec->SortSign; if (delta > 0) - return +1 * sort_spec->SortSign; + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1; + if (delta < 0) + return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1; } // qsort() is instable so always return a way to differenciate items. diff --git a/imgui_tables.cpp b/imgui_tables.cpp index fedf1b35..c2b219d9 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2011,7 +2011,7 @@ void ImGui::TableHeader(const char* label) float w_sort_text = 0.0f; if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort)) { - const float ARROW_SCALE = 0.75f; + const float ARROW_SCALE = 0.65f; w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);// table->CellPadding.x); if (column->SortOrder != -1) { @@ -2036,7 +2036,7 @@ void ImGui::TableHeader(const char* label) PopStyleColor(); x += w_sort_text; } - RenderArrow(window->DrawList, ImVec2(x, y), col, column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Down : ImGuiDir_Up, ARROW_SCALE); + RenderArrow(window->DrawList, ImVec2(x, y), col, column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); } // Handle clicking on column header to adjust Sort Order @@ -2126,7 +2126,6 @@ const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() sort_spec->ColumnUserID = column->UserID; sort_spec->ColumnIndex = (ImU8)column_n; sort_spec->SortOrder = (ImU8)column->SortOrder; - sort_spec->SortSign = (column->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1; sort_spec->SortDirection = column->SortDirection; table->SortSpecs.ColumnsMask |= (ImU64)1 << column_n; } @@ -2298,7 +2297,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) // We skip saving some data in the .ini file when they are unnecessary to restore our state // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet. if (column->IndexDisplayOrder != n) - settings->SaveFlags |= ImGuiTableFlags_Reorderable;; + settings->SaveFlags |= ImGuiTableFlags_Reorderable; if (column_settings->SortOrder != -1) settings->SaveFlags |= ImGuiTableFlags_Sortable; if (column_settings->Visible != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) @@ -2446,11 +2445,13 @@ void ImGui::DebugNodeTable(ImGuiTable* table) "Active: %d, Clipped: %d, DrawChannels: %d,%d\n" "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Desired %d/%d\n" + "SortOrder: %d, SortDir: %s\n" "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", n, column->IndexDisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, column->WidthGiven, column->WidthRequested, column->ResizeWeight, column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersDesired, + column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? "Ascending" : (column->SortDirection == ImGuiSortDirection_Descending) ? "Descending" : "None", column->UserID, column->Flags, (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "", @@ -2465,8 +2466,11 @@ void ImGui::DebugNodeTable(ImGuiTable* table) for (int n = 0; n < settings->ColumnsCount; n++) { ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n]; - BulletText("Column %d Order %d SortOrder %d Visible %d UserID 0x%08X WidthOrWeight %.3f", - n, column_settings->DisplayOrder, column_settings->SortOrder, column_settings->Visible, column_settings->UserID, column_settings->WidthOrWeight); + ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? column_settings->SortDirection : ImGuiSortDirection_None; + BulletText("Column %d Order %d SortOrder %d %s Visible %d UserID 0x%08X WidthOrWeight %.3f", + n, column_settings->DisplayOrder, column_settings->SortOrder, + (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---", + column_settings->Visible, column_settings->UserID, column_settings->WidthOrWeight); } TreePop(); } From f130db51ae2b749219fe25ad0d8de6109cdb01cf Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 5 Mar 2020 14:31:13 +0100 Subject: [PATCH 409/959] Tables: Added TableSetColumnWidth() api variant aimed at becoming public facing. --- imgui_internal.h | 1 + imgui_tables.cpp | 14 +++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index efb04012..21882beb 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2185,6 +2185,7 @@ namespace ImGui IMGUI_API void TableUpdateDrawChannels(ImGuiTable* table); IMGUI_API void TableUpdateLayout(ImGuiTable* table); IMGUI_API void TableUpdateBorders(ImGuiTable* table); + IMGUI_API void TableSetColumnWidth(int column_n, float width); IMGUI_API void TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column, float width); IMGUI_API void TableDrawBorders(ImGuiTable* table); IMGUI_API void TableDrawMergeChannels(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index c2b219d9..2053c007 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -886,7 +886,7 @@ void ImGui::EndTable() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Only call EndTable() is BeginTable() returns true!"); + IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!"); // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some cases, // and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) @@ -1134,6 +1134,18 @@ static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table) } } +// Public wrapper +void ImGui::TableSetColumnWidth(int column_n, float width) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL); + IM_ASSERT(table->IsLayoutLocked == false); + IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount); + TableSetColumnWidth(table, &table->Columns[column_n], width); +} + +// [Internal] void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, float column_0_width) { // Constraints From 0190b619cfc30981fe5d65b37b8dadda16c1119e Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 9 Mar 2020 11:09:54 +0100 Subject: [PATCH 410/959] Tables: Fixed demo layout when clipped. Fixed warnings. --- imgui_demo.cpp | 35 ++++++++++++++++++----------------- imgui_tables.cpp | 4 ++-- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b91392ae..6c84e023 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4209,6 +4209,8 @@ static void ShowDemoWindowTables() const ImDrawList* parent_draw_list = ImGui::GetWindowDrawList(); const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size; + ImVec2 table_scroll_cur, table_scroll_max; // For debug display + const ImDrawList* table_draw_list = NULL; // " const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : inner_width_without_scroll; if (ImGui::BeginTable("##table", 5, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use)) @@ -4322,23 +4324,22 @@ static void ShowDemoWindowTables() } ImGui::PopButtonRepeat(); - const ImVec2 table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY()); - const ImVec2 table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY()); - const ImDrawList* table_draw_list = ImGui::GetWindowDrawList(); + table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY()); + table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY()); + table_draw_list = ImGui::GetWindowDrawList(); ImGui::EndTable(); - - static bool show_debug_details = false; - ImGui::Checkbox("Debug details", &show_debug_details); - if (show_debug_details) - { - ImGui::SameLine(0.0f, 0.0f); - const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size; - if (table_draw_list == parent_draw_list) - ImGui::Text(": DrawCmd: +%d (in same window)", table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count); - else - ImGui::Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)", - table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y); - } + } + static bool show_debug_details = false; + ImGui::Checkbox("Debug details", &show_debug_details); + if (show_debug_details && table_draw_list) + { + ImGui::SameLine(0.0f, 0.0f); + const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size; + if (table_draw_list == parent_draw_list) + ImGui::Text(": DrawCmd: +%d (in same window)", table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count); + else + ImGui::Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)", + table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y); } ImGui::TreePop(); } @@ -5076,9 +5077,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) ImGui::Text("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("CellPadding", (float*)&style.CellPadding, 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("CellPadding", (float*)&style.CellPadding, 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"); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2053c007..d380acc9 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1342,7 +1342,7 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) continue; ImDrawChannel* channel = &splitter->_Channels[n]; IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect))); - channel->_CmdBuffer[0].ClipRect = *(ImVec4*)&merge_clip_rect; + channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4(); memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); merge_channels_mask &= ~n_mask; } @@ -2478,7 +2478,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) for (int n = 0; n < settings->ColumnsCount; n++) { ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n]; - ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? column_settings->SortDirection : ImGuiSortDirection_None; + ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None; BulletText("Column %d Order %d SortOrder %d %s Visible %d UserID 0x%08X WidthOrWeight %.3f", n, column_settings->DisplayOrder, column_settings->SortOrder, (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---", From 7277ab6530032bdb318acc05cc87c8091576ca47 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Mar 2020 11:49:52 +0100 Subject: [PATCH 411/959] Tables: Comments, renamed merge_set_xxx to merge_group_xxx. Removed unused array and incorrect assert, replaced with earlier correct assert. (3058) --- imgui_tables.cpp | 78 +++++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 38 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d380acc9..508acbb4 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -445,9 +445,9 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) void ImGui::TableUpdateDrawChannels(ImGuiTable* table) { // Allocate draw channels. - // - We allocate them following the storage order instead of the display order so reordering won't needlessly increase overall dormant memory cost + // - We allocate them following the storage order instead of the display order so reordering columns won't needlessly increase overall dormant memory cost. // - We isolate headers draw commands in their own channels instead of just altering clip rects. This is in order to facilitate merging of draw commands. - // - After crossing FreezeRowsCount, all columns see their current draw channel increased. + // - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of draw channels. // - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. // Draw channel allocation (before merging): // - NoClip --> 1+1 channels: background + foreground (same clip rect == 1 draw call) @@ -1232,13 +1232,13 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // // Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). // When the contents of a column didn't stray off its limit, we move its channels into the corresponding group -// based on its position (within frozen rows/columns set or not). +// based on its position (within frozen rows/columns groups or not). // At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect, and they will be merged by the DrawSplitter.Merge() call. // // Column channels will not be merged into one of the 1-4 groups in the following cases: // - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). -// Direct ImDrawList calls won't be noticed so if you use them make sure the ImGui:: bounds matches, by e.g. calling SetCursorScreenPos(). -// - The channel uses more than one draw command itself (we drop all our merging stuff here.. we could do better but it's going to be rare) +// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds matches, by e.g. calling SetCursorScreenPos(). +// - The channel uses more than one draw command itself. We drop all our merging stuff here.. we could do better but it's going to be rare. // // This function is particularly tricky to understand.. take a breath. void ImGui::TableDrawMergeChannels(ImGuiTable* table) @@ -1248,15 +1248,16 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) const bool is_frozen_v = (table->FreezeRowsCount > 0); const bool is_frozen_h = (table->FreezeColumnsCount > 0); - int merge_set_mask = 0; - int merge_set_channels_count[4] = { 0 }; - ImU64 merge_set_channels_mask[4] = { 0 }; - ImRect merge_set_clip_rect[4]; - for (int n = 0; n < IM_ARRAYSIZE(merge_set_clip_rect); n++) - merge_set_clip_rect[n] = ImVec4(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); - bool merge_set_all_fit_within_inner_rect = (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0; + // Track which groups (1-4) we are going to attempt to merge, and which channels goes into each group. + int merge_group_mask = 0x00; + int merge_group_channels_count[4] = { 0 }; + ImU64 merge_group_channels_mask[4] = { 0 }; + ImRect merge_group_clip_rect[4]; + for (int n = 0; n < IM_ARRAYSIZE(merge_group_clip_rect); n++) + merge_group_clip_rect[n] = ImVec4(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + bool merge_groups_all_fit_within_inner_rect = (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0; - // 1. Scan channels and take note of those who can be merged + // 1. Scan channels and take note of those which can be merged for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) @@ -1264,37 +1265,37 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) const int column_n = table->DisplayOrder[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; - const int merge_set_sub_count = is_frozen_v ? 2 : 1; - for (int merge_set_sub_n = 0; merge_set_sub_n < merge_set_sub_count; merge_set_sub_n++) + const int merge_group_sub_count = is_frozen_v ? 2 : 1; + for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++) { - const int channel_no = (merge_set_sub_n == 0) ? column->DrawChannelRowsBeforeFreeze : column->DrawChannelRowsAfterFreeze; + const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelRowsBeforeFreeze : column->DrawChannelRowsAfterFreeze; - // Don't attempt to merge if there are multiple calls within the column + // Don't attempt to merge if there are multiple draw calls within the column ImDrawChannel* src_channel = &splitter->_Channels[channel_no]; if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0) src_channel->_CmdBuffer.pop_back(); if (src_channel->_CmdBuffer.Size != 1) continue; - // Find out the width of this merge set and check if it will fit in our column. + // Find out the width of this merge group and check if it will fit in our column. float width_contents; - if (merge_set_sub_count == 1) // No row freeze (same as testing !is_frozen_v) + if (merge_group_sub_count == 1) // No row freeze (same as testing !is_frozen_v) width_contents = ImMax(column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed); - else if (merge_set_sub_n == 0) // Row freeze: use width before freeze + else if (merge_group_sub_n == 0) // Row freeze: use width before freeze width_contents = ImMax(column->ContentWidthRowsFrozen, column->ContentWidthHeadersUsed); - else // Row freeze: use width after freeze + else // Row freeze: use width after freeze width_contents = column->ContentWidthRowsUnfrozen; if (width_contents > column->WidthGiven && !(column->Flags & ImGuiTableColumnFlags_NoClipX)) continue; - const int dst_merge_set_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_set_sub_n : 1); - IM_ASSERT(merge_set_channels_count[dst_merge_set_n] < (int)sizeof(merge_set_channels_mask[dst_merge_set_n]) * 8); - merge_set_mask |= (1 << dst_merge_set_n); - merge_set_channels_mask[dst_merge_set_n] |= (ImU64)1 << channel_no; - merge_set_channels_count[dst_merge_set_n]++; - merge_set_clip_rect[dst_merge_set_n].Add(src_channel->_CmdBuffer[0].ClipRect); + const int dst_merge_group_idx = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1); + IM_ASSERT(channel_no < 64); + merge_group_mask |= (1 << dst_merge_group_idx); + merge_group_channels_mask[dst_merge_group_idx] |= (ImU64)1 << channel_no; + merge_group_channels_count[dst_merge_group_idx]++; + merge_group_clip_rect[dst_merge_group_idx].Add(src_channel->_CmdBuffer[0].ClipRect); - // If we end with a single set and hosted by the outer window, we'll attempt to merge our draw command with + // If we end with a single group and hosted by the outer window, we'll attempt to merge our draw command with // the existing outer window command. But we can only do so if our columns all fit within the expected clip rect, // otherwise clipping will be incorrect when ScrollX is disabled. // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column don't fit within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect @@ -1304,7 +1305,7 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) // 2019/10/22: (2) Clamping code in TableUpdateLayout() seemingly made this not necessary... #if 0 if (column->MinX < table->InnerClipRect.Min.x || column->MaxX > table->InnerClipRect.Max.x) - merge_set_all_fit_within_inner_rect = false; + merge_groups_all_fit_within_inner_rect = false; #endif } @@ -1312,25 +1313,26 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) column->DrawChannelCurrent = -1; } + // 2. Rewrite channel list in our preferred order - if (merge_set_mask != 0) + if (merge_group_mask != 0) { // Use shared temporary storage so the allocation gets amortized g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - 1); ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data; - ImU64 remaining_mask = ((splitter->_Count < 64) ? ((ImU64)1 << splitter->_Count) - 1 : ~(ImU64)0) & ~1; - const bool may_extend_clip_rect_to_host_rect = ImIsPowerOfTwo(merge_set_mask); - for (int merge_set_n = 0; merge_set_n < 4; merge_set_n++) - if (merge_set_channels_count[merge_set_n]) + ImU64 remaining_mask = (splitter->_Count < 64) ? ((ImU64)1 << splitter->_Count) - 1 : ~(ImU64)0; + remaining_mask &= (ImU64)~1; // Background channel 0 not part of the merge (see channel allocation in TableUpdateDrawChannels) + const bool may_extend_clip_rect_to_host_rect = ImIsPowerOfTwo(merge_group_mask); + for (int merge_group_n = 0; merge_group_n < 4; merge_group_n++) + if (ImU64 merge_channels_mask = merge_group_channels_mask[merge_group_n]) { - ImU64 merge_channels_mask = merge_set_channels_mask[merge_set_n]; - ImRect merge_clip_rect = merge_set_clip_rect[merge_set_n]; + ImRect merge_clip_rect = merge_group_clip_rect[merge_group_n]; if (may_extend_clip_rect_to_host_rect) { //GetOverlayDrawList()->AddRect(table->HostClipRect.Min, table->HostClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 3.0f); //GetOverlayDrawList()->AddRect(table->InnerClipRect.Min, table->InnerClipRect.Max, IM_COL32(0, 255, 0, 200), 0.0f, ~0, 1.0f); //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 2.0f); - merge_clip_rect.Add(merge_set_all_fit_within_inner_rect ? table->HostClipRect : table->InnerClipRect); + merge_clip_rect.Add(merge_groups_all_fit_within_inner_rect ? table->HostClipRect : table->InnerClipRect); //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(0, 255, 0, 200)); } remaining_mask &= ~merge_channels_mask; @@ -1348,7 +1350,7 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) } } - // Append channels that we didn't reorder at the end of the list + // Append unmergeable channels that we didn't reorder at the end of the list for (int n = 0; n < splitter->_Count && remaining_mask != 0; n++) { const ImU64 n_mask = (ImU64)1 << n; From d37cef40f25da88f84920df7a6d50669c33b1dd9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Mar 2020 16:16:20 +0100 Subject: [PATCH 412/959] Tables: Tidying up TableDrawMergeChannels() with a struct. (3058) --- imgui_tables.cpp | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 508acbb4..b8c0fcaa 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1248,13 +1248,16 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) const bool is_frozen_v = (table->FreezeRowsCount > 0); const bool is_frozen_h = (table->FreezeColumnsCount > 0); - // Track which groups (1-4) we are going to attempt to merge, and which channels goes into each group. + // Track which groups we are going to attempt to merge, and which channels goes into each group. + struct MergeGroup + { + ImRect ClipRect; + ImU64 ChannelsMask; + int ChannelsCount; + }; int merge_group_mask = 0x00; - int merge_group_channels_count[4] = { 0 }; - ImU64 merge_group_channels_mask[4] = { 0 }; - ImRect merge_group_clip_rect[4]; - for (int n = 0; n < IM_ARRAYSIZE(merge_group_clip_rect); n++) - merge_group_clip_rect[n] = ImVec4(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + MergeGroup merge_groups[4]; + memset(merge_groups, 0, sizeof(merge_groups)); bool merge_groups_all_fit_within_inner_rect = (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0; // 1. Scan channels and take note of those which can be merged @@ -1288,12 +1291,15 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) if (width_contents > column->WidthGiven && !(column->Flags & ImGuiTableColumnFlags_NoClipX)) continue; - const int dst_merge_group_idx = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1); + const int merge_group_dst_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1); IM_ASSERT(channel_no < 64); - merge_group_mask |= (1 << dst_merge_group_idx); - merge_group_channels_mask[dst_merge_group_idx] |= (ImU64)1 << channel_no; - merge_group_channels_count[dst_merge_group_idx]++; - merge_group_clip_rect[dst_merge_group_idx].Add(src_channel->_CmdBuffer[0].ClipRect); + MergeGroup* merge_group = &merge_groups[merge_group_dst_n]; + if (merge_group->ChannelsCount == 0) + merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); + merge_group->ChannelsMask |= (ImU64)1 << channel_no; + merge_group->ChannelsCount++; + merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect); + merge_group_mask |= (1 << merge_group_dst_n); // If we end with a single group and hosted by the outer window, we'll attempt to merge our draw command with // the existing outer window command. But we can only do so if our columns all fit within the expected clip rect, @@ -1313,7 +1319,6 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) column->DrawChannelCurrent = -1; } - // 2. Rewrite channel list in our preferred order if (merge_group_mask != 0) { @@ -1324,9 +1329,9 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) remaining_mask &= (ImU64)~1; // Background channel 0 not part of the merge (see channel allocation in TableUpdateDrawChannels) const bool may_extend_clip_rect_to_host_rect = ImIsPowerOfTwo(merge_group_mask); for (int merge_group_n = 0; merge_group_n < 4; merge_group_n++) - if (ImU64 merge_channels_mask = merge_group_channels_mask[merge_group_n]) + if (ImU64 merge_channels_mask = merge_groups[merge_group_n].ChannelsMask) { - ImRect merge_clip_rect = merge_group_clip_rect[merge_group_n]; + ImRect merge_clip_rect = merge_groups[merge_group_n].ClipRect; if (may_extend_clip_rect_to_host_rect) { //GetOverlayDrawList()->AddRect(table->HostClipRect.Min, table->HostClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 3.0f); From 054c67079ad0033666fde310fe6317686160f9f6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 13 Mar 2020 18:58:55 +0100 Subject: [PATCH 413/959] Tables: Fix scrolling with more than 32 columns (3058). Fix limit of 63 columms instead of 64. Added BitArray. --- imgui_internal.h | 19 +++++++++++++++++-- imgui_tables.cpp | 37 +++++++++++++++++++++---------------- 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 21882beb..3c6009d0 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -476,6 +476,20 @@ inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2) } } +// Helper: ImBitArray class (wrapper over ImBitArray functions) +// Store 1-bit per value. NOT CLEARED by constructor. +template +struct IMGUI_API ImBitArray +{ + ImU32 Storage[(BITCOUNT + 31) >> 5]; + ImBitArray() { } + void ClearBits() { memset(Storage, 0, sizeof(Storage)); } + bool TestBit(int n) const { IM_ASSERT(n < BITCOUNT); return ImBitArrayTestBit(Storage, n); } + void SetBit(int n) { IM_ASSERT(n < BITCOUNT); ImBitArraySetBit(Storage, n); } + void ClearBit(int n) { IM_ASSERT(n < BITCOUNT); ImBitArrayClearBit(Storage, n); } + void SetBitRange(int n1, int n2) { ImBitArraySetBitRange(Storage, n1, n2); } +}; + // Helper: ImBitVector // Store 1-bit per value. struct IMGUI_API ImBitVector @@ -1820,8 +1834,9 @@ struct ImGuiTabBar #ifdef IMGUI_HAS_TABLE -#define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code -#define IMGUI_TABLE_MAX_COLUMNS 64 // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64. +#define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code +#define IMGUI_TABLE_MAX_COLUMNS 64 // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64. +#define IMGUI_TABLE_MAX_DRAW_CHANNELS (2 + 64 * 2) // See TableUpdateDrawChannels() // [Internal] sizeof() ~ 100 struct ImGuiTableColumn diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b8c0fcaa..ed55fb35 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -163,7 +163,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG return false; // Sanity checks - IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS && "Only 0..63 columns allowed!"); + IM_ASSERT(columns_count > 0 && columns_count <= IMGUI_TABLE_MAX_COLUMNS && "Only 1..64 columns allowed!"); if (flags & ImGuiTableFlags_ScrollX) IM_ASSERT(inner_width >= 0.0f); @@ -1252,8 +1252,8 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) struct MergeGroup { ImRect ClipRect; - ImU64 ChannelsMask; int ChannelsCount; + ImBitArray ChannelsMask; }; int merge_group_mask = 0x00; MergeGroup merge_groups[4]; @@ -1292,11 +1292,11 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) continue; const int merge_group_dst_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1); - IM_ASSERT(channel_no < 64); + IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS); MergeGroup* merge_group = &merge_groups[merge_group_dst_n]; if (merge_group->ChannelsCount == 0) merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); - merge_group->ChannelsMask |= (ImU64)1 << channel_no; + merge_group->ChannelsMask.SetBit(channel_no); merge_group->ChannelsCount++; merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect); merge_group_mask |= (1 << merge_group_dst_n); @@ -1325,12 +1325,15 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) // Use shared temporary storage so the allocation gets amortized g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - 1); ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data; - ImU64 remaining_mask = (splitter->_Count < 64) ? ((ImU64)1 << splitter->_Count) - 1 : ~(ImU64)0; - remaining_mask &= (ImU64)~1; // Background channel 0 not part of the merge (see channel allocation in TableUpdateDrawChannels) + ImBitArray remaining_mask; + remaining_mask.ClearBits(); + remaining_mask.SetBitRange(1, splitter->_Count - 1); // Background channel 0 not part of the merge (see channel allocation in TableUpdateDrawChannels) + int remaining_count = splitter->_Count - 1; const bool may_extend_clip_rect_to_host_rect = ImIsPowerOfTwo(merge_group_mask); for (int merge_group_n = 0; merge_group_n < 4; merge_group_n++) - if (ImU64 merge_channels_mask = merge_groups[merge_group_n].ChannelsMask) + if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount) { + MergeGroup* merge_group = &merge_groups[merge_group_n]; ImRect merge_clip_rect = merge_groups[merge_group_n].ClipRect; if (may_extend_clip_rect_to_host_rect) { @@ -1340,30 +1343,32 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) merge_clip_rect.Add(merge_groups_all_fit_within_inner_rect ? table->HostClipRect : table->InnerClipRect); //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(0, 255, 0, 200)); } - remaining_mask &= ~merge_channels_mask; - for (int n = 0; n < splitter->_Count && merge_channels_mask != 0; n++) + remaining_count -= merge_group->ChannelsCount; + for (int n = 0; n < IM_ARRAYSIZE(remaining_mask.Storage); n++) + remaining_mask.Storage[n] &= ~merge_group->ChannelsMask.Storage[n]; + for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++) { // Copy + overwrite new clip rect - const ImU64 n_mask = (ImU64)1 << n; - if ((merge_channels_mask & n_mask) == 0) + if (!merge_group->ChannelsMask.TestBit(n)) continue; + merge_group->ChannelsMask.ClearBit(n); + merge_channels_count--; + ImDrawChannel* channel = &splitter->_Channels[n]; IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect))); channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4(); memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); - merge_channels_mask &= ~n_mask; } } // Append unmergeable channels that we didn't reorder at the end of the list - for (int n = 0; n < splitter->_Count && remaining_mask != 0; n++) + for (int n = 0; n < splitter->_Count && remaining_count != 0; n++) { - const ImU64 n_mask = (ImU64)1 << n; - if ((remaining_mask & n_mask) == 0) + if (!remaining_mask.TestBit(n)) continue; ImDrawChannel* channel = &splitter->_Channels[n]; memcpy(dst_tmp++, channel, sizeof(ImDrawChannel)); - remaining_mask &= ~n_mask; + remaining_count--; } IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size); memcpy(splitter->_Channels.Data + 1, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - 1) * sizeof(ImDrawChannel)); From 182115409ab3d4c76ea125c538c46ed38c332162 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 18 Mar 2020 12:20:53 +0100 Subject: [PATCH 414/959] Internals: added ImSpan helper structure + 2020/10/01 stricter bound checking --- imgui_internal.h | 29 +++++++++++++++++++++++++++++ misc/natvis/imgui.natvis | 10 ++++++++++ 2 files changed, 39 insertions(+) diff --git a/imgui_internal.h b/imgui_internal.h index 3c6009d0..12e67fda 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -249,6 +249,7 @@ namespace ImStb // - Helper: ImRect // - Helper: ImBitArray // - Helper: ImBitVector +// - Helper: ImSpan<> // - Helper: ImPool<> // - Helper: ImChunkStream<> //----------------------------------------------------------------------------- @@ -502,6 +503,34 @@ struct IMGUI_API ImBitVector void ClearBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArrayClearBit(Storage.Data, n); } }; +// Helper: ImSpan<> +// Pointing to a span of data we don't own. +template +struct ImSpan +{ + T* Data; + T* DataEnd; + + // Constructors, destructor + inline ImSpan() { Data = DataEnd = NULL; } + inline ImSpan(T* data, int size) { Data = data; DataEnd = data + size; } + inline ImSpan(T* data, T* data_end) { Data = data; DataEnd = data_end; } + + inline void set(T* data, int size) { Data = data; DataEnd = data + size; } + inline void set(T* data, T* data_end) { Data = data; DataEnd = data_end; } + inline int size() const { return (int)(ptrdiff_t)(DataEnd - Data); } + inline T& operator[](int i) { T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } + inline const T& operator[](int i) const { const T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } + + inline T* begin() { return Data; } + inline const T* begin() const { return Data; } + inline T* end() { return DataEnd; } + inline const T* end() const { return DataEnd; } + + // Utilities + inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < DataEnd); const ptrdiff_t off = it - Data; return (int)off; } +}; + // 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. diff --git a/misc/natvis/imgui.natvis b/misc/natvis/imgui.natvis index cc768bfb..25d72fb6 100644 --- a/misc/natvis/imgui.natvis +++ b/misc/natvis/imgui.natvis @@ -13,6 +13,16 @@ + + + {{Size={DataEnd-Data} }} + + + DataEnd-Data + Data + + + {{x={x,g} y={y,g}}} From 6dff06130998712209657d26fe612c7dfce7014b Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 18 Mar 2020 17:49:13 +0100 Subject: [PATCH 415/959] Internals: added ImSpanAllocator<> helper. --- imgui_internal.h | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 12e67fda..0530130a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -249,7 +249,7 @@ namespace ImStb // - Helper: ImRect // - Helper: ImBitArray // - Helper: ImBitVector -// - Helper: ImSpan<> +// - Helper: ImSpan<>, ImSpanAllocator<> // - Helper: ImPool<> // - Helper: ImChunkStream<> //----------------------------------------------------------------------------- @@ -531,6 +531,26 @@ struct ImSpan inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < DataEnd); const ptrdiff_t off = it - Data; return (int)off; } }; +// Helper: ImSpanAllocator<> +// Facilitate storing multiple chunks into a single large block (the "arena") +template +struct ImSpanAllocator +{ + char* BasePtr; + int TotalSize; + int CurrSpan; + int Offsets[CHUNKS]; + + ImSpanAllocator() { memset(this, 0, sizeof(*this)); } + inline void ReserveBytes(int n, size_t sz) { IM_ASSERT(n == CurrSpan && n < CHUNKS); Offsets[CurrSpan++] = TotalSize; TotalSize += (int)sz; } + inline int GetArenaSizeInBytes() { return TotalSize; } + inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; } + inline void* GetSpanPtrBegin(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrSpan == CHUNKS); return (void*)(BasePtr + Offsets[n]); } + inline void* GetSpanPtrEnd(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrSpan == CHUNKS); return (n + 1 < CHUNKS) ? BasePtr + Offsets[n + 1] : (void*)(BasePtr + TotalSize); } + template + inline void GetSpan(int n, ImSpan* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); } +}; + // 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. From a956629b40843e01c59dd4b8b05c1ecee85764d0 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 18 Mar 2020 18:17:22 +0100 Subject: [PATCH 416/959] Tables: Using same allocation for our Columns and DisplayOrder array. Mostly designed to facilitate adding new arrays. --- imgui_internal.h | 7 ++++--- imgui_tables.cpp | 37 +++++++++++++++++++------------------ 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 0530130a..a8055b26 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1946,8 +1946,9 @@ struct ImGuiTable { ImGuiID ID; ImGuiTableFlags Flags; - ImVector Columns; - ImVector DisplayOrder; // Store display order of columns (when not reordered, the values are 0...Count-1) + ImVector RawData; + ImSpan Columns; // Point within RawData[] + ImSpan DisplayOrder; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) ImU64 ActiveMaskByIndex; // Column Index -> IsActive map (Active == not hidden by user/api) in a format adequate for iterating column without touching cold data ImU64 ActiveMaskByDisplayOrder; // Column DisplayOrder -> IsActive map ImU64 VisibleMaskByIndex; // Visible (== Active and not Clipped) @@ -1992,7 +1993,7 @@ struct ImGuiTable ImGuiWindow* OuterWindow; // Parent window for the table ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names - ImDrawListSplitter DrawSplitter; // We carry our own ImDrawList splitter to allow recursion (could be stored outside?) + ImDrawListSplitter DrawSplitter; // We carry our own ImDrawList splitter to allow recursion (FIXME: could be stored outside, worst case we need 1 splitter per recursing table) ImVector SortSpecsData; // FIXME-OPT: Fixed-size array / small-vector pattern, optimize for single sort spec ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() ImS8 SortSpecsCount; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ed55fb35..fbb6de8b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -288,26 +288,27 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if ((table_last_flags & ImGuiTableFlags_Reorderable) && !(flags & ImGuiTableFlags_Reorderable)) table->IsResetDisplayOrderRequest = true; - // Clear data if columns count changed - if (table->Columns.Size != 0 && table->Columns.Size != columns_count) - { - table->Columns.resize(0); - table->DisplayOrder.resize(0); - } + // Setup default columns state. Clear data if columns count changed + const int stored_size = table->Columns.size(); + if (stored_size != 0 && stored_size != columns_count) + table->RawData.resize(0); + if (table->RawData.Size == 0) + { + // Allocate single buffer for our arrays + ImSpanAllocator<2> span_allocator; + span_allocator.ReserveBytes(0, columns_count * sizeof(ImGuiTableColumn)); + span_allocator.ReserveBytes(1, columns_count * sizeof(ImS8)); + table->RawData.resize(span_allocator.GetArenaSizeInBytes()); + span_allocator.SetArenaBasePtr(table->RawData.Data); + span_allocator.GetSpan(0, &table->Columns); + span_allocator.GetSpan(1, &table->DisplayOrder); - // Setup default columns state - if (table->Columns.Size == 0) - { - table->IsInitializing = table->IsSettingsRequestLoad = table->IsSortSpecsDirty = true; - table->Columns.reserve(columns_count); - table->DisplayOrder.reserve(columns_count); for (int n = 0; n < columns_count; n++) { - ImGuiTableColumn column; - column.IndexDisplayOrder = (ImS8)n; - table->Columns.push_back(column); - table->DisplayOrder.push_back(column.IndexDisplayOrder); + table->Columns[n] = ImGuiTableColumn(); + table->Columns[n].IndexDisplayOrder = table->DisplayOrder[n] = (ImS8)n; } + table->IsInitializing = table->IsSettingsRequestLoad = table->IsSortSpecsDirty = true; } // Load settings @@ -378,7 +379,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) if (table->IsResetDisplayOrderRequest) { for (int n = 0; n < table->ColumnsCount; n++) - table->DisplayOrder[n] = table->Columns[n].IndexDisplayOrder = (ImU8)n; + table->DisplayOrder[n] = table->Columns[n].IndexDisplayOrder = (ImS8)n; table->IsResetDisplayOrderRequest = false; table->IsSettingsDirty = true; } @@ -2376,7 +2377,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) // FIXME-TABLE: Need to validate .ini data for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - table->DisplayOrder[table->Columns[column_n].IndexDisplayOrder] = (ImU8)column_n; + table->DisplayOrder[table->Columns[column_n].IndexDisplayOrder] = (ImS8)column_n; } void* ImGui::TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) From 5ffc9e084618770b6f6afc82309af311af2d4eb6 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 18 Mar 2020 18:20:17 +0100 Subject: [PATCH 417/959] Tables: Renaming Table's DisplayOrder[] -> DisplayOrderToIndex[], Columns's IndexDisplayOrder -> DisplayOrder --- imgui_internal.h | 6 +++--- imgui_tables.cpp | 52 ++++++++++++++++++++++++------------------------ 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index a8055b26..789e71a1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1914,7 +1914,7 @@ struct ImGuiTableColumn bool NextIsActive; bool IsClipped; // Set when not overlapping the host window clipping rectangle. We don't use the opposite "!Visible" name because Clipped can be altered by events. bool SkipItems; - ImS8 IndexDisplayOrder; // Index within DisplayOrder[] (column may be reordered by users) + ImS8 DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) ImS8 IndexWithinActiveSet; // Index within active set (<= IndexOrder) ImS8 DrawChannelCurrent; // Index within DrawSplitter.Channels[] ImS8 DrawChannelRowsBeforeFreeze; @@ -1932,7 +1932,7 @@ struct ImGuiTableColumn ResizeWeight = WidthRequested = WidthGiven = -1.0f; NameOffset = -1; IsActive = NextIsActive = true; - IndexDisplayOrder = IndexWithinActiveSet = -1; + DisplayOrder = IndexWithinActiveSet = -1; DrawChannelCurrent = DrawChannelRowsBeforeFreeze = DrawChannelRowsAfterFreeze = -1; PrevActiveColumn = NextActiveColumn = -1; AutoFitQueue = CannotSkipItemsQueue = (1 << 3) - 1; // Skip for three frames @@ -1948,7 +1948,7 @@ struct ImGuiTable ImGuiTableFlags Flags; ImVector RawData; ImSpan Columns; // Point within RawData[] - ImSpan DisplayOrder; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) + ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) ImU64 ActiveMaskByIndex; // Column Index -> IsActive map (Active == not hidden by user/api) in a format adequate for iterating column without touching cold data ImU64 ActiveMaskByDisplayOrder; // Column DisplayOrder -> IsActive map ImU64 VisibleMaskByIndex; // Visible (== Active and not Clipped) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index fbb6de8b..f79bc73d 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -301,12 +301,12 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->RawData.resize(span_allocator.GetArenaSizeInBytes()); span_allocator.SetArenaBasePtr(table->RawData.Data); span_allocator.GetSpan(0, &table->Columns); - span_allocator.GetSpan(1, &table->DisplayOrder); + span_allocator.GetSpan(1, &table->DisplayOrderToIndex); for (int n = 0; n < columns_count; n++) { table->Columns[n] = ImGuiTableColumn(); - table->Columns[n].IndexDisplayOrder = table->DisplayOrder[n] = (ImS8)n; + table->Columns[n].DisplayOrder = table->DisplayOrderToIndex[n] = (ImS8)n; } table->IsInitializing = table->IsSettingsRequestLoad = table->IsSortSpecsDirty = true; } @@ -360,16 +360,16 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn]; ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevActiveColumn : src_column->NextActiveColumn]; IM_UNUSED(dst_column); - const int src_order = src_column->IndexDisplayOrder; - const int dst_order = dst_column->IndexDisplayOrder; - src_column->IndexDisplayOrder = (ImS8)dst_order; + const int src_order = src_column->DisplayOrder; + const int dst_order = dst_column->DisplayOrder; + src_column->DisplayOrder = (ImS8)dst_order; for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir) - table->Columns[table->DisplayOrder[order_n]].IndexDisplayOrder -= (ImS8)reorder_dir; - IM_ASSERT(dst_column->IndexDisplayOrder == dst_order - reorder_dir); + table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImS8)reorder_dir; + IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir); // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[], rebuild the later from the former. for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - table->DisplayOrder[table->Columns[column_n].IndexDisplayOrder] = (ImS8)column_n; + table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImS8)column_n; table->ReorderColumnDir = 0; table->IsSettingsDirty = true; } @@ -379,7 +379,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) if (table->IsResetDisplayOrderRequest) { for (int n = 0; n < table->ColumnsCount; n++) - table->DisplayOrder[n] = table->Columns[n].IndexDisplayOrder = (ImS8)n; + table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImS8)n; table->IsResetDisplayOrderRequest = false; table->IsSettingsDirty = true; } @@ -391,7 +391,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) bool want_column_auto_fit = false; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { - const int column_n = table->DisplayOrder[order_n]; + const int column_n = table->DisplayOrderToIndex[order_n]; if (column_n != order_n) table->IsDefaultDisplayOrder = false; ImGuiTableColumn* column = &table->Columns[column_n]; @@ -411,7 +411,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) want_column_auto_fit = true; ImU64 index_mask = (ImU64)1 << column_n; - ImU64 display_order_mask = (ImU64)1 << column->IndexDisplayOrder; + ImU64 display_order_mask = (ImU64)1 << column->DisplayOrder; if (column->IsActive) { column->PrevActiveColumn = column->NextActiveColumn = -1; @@ -432,7 +432,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) table->ActiveMaskByIndex &= ~index_mask; table->ActiveMaskByDisplayOrder &= ~display_order_mask; } - IM_ASSERT(column->IndexWithinActiveSet <= column->IndexDisplayOrder); + IM_ASSERT(column->IndexWithinActiveSet <= column->DisplayOrder); } table->VisibleMaskByIndex = table->ActiveMaskByIndex; // Columns will be masked out by TableUpdateLayout() when Clipped table->RightMostActiveColumn = (ImS8)(last_active_column ? table->Columns.index_from_ptr(last_active_column) : -1); @@ -549,7 +549,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; - const int column_n = table->DisplayOrder[order_n]; + const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; // Adjust flags: default width mode + weighted columns are not allowed when auto extending @@ -592,7 +592,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->ResizeWeight = 1.0f; total_weights += column->ResizeWeight; if (table->LeftMostStretchedColumnDisplayOrder == -1) - table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->IndexDisplayOrder; + table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->DisplayOrder; } } @@ -615,7 +615,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; - ImGuiTableColumn* column = &table->Columns[table->DisplayOrder[order_n]]; + ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]]; // Allocate width for stretched/weighted columns if (column->Flags & ImGuiTableColumnFlags_WidthStretch) @@ -678,7 +678,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; - ImGuiTableColumn* column = &table->Columns[table->DisplayOrder[order_n]]; + ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]]; if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch)) continue; column->WidthRequested += 1.0f; @@ -692,7 +692,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) ImRect host_clip_rect = table->InnerClipRect; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { - const int column_n = table->DisplayOrder[order_n]; + const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == active_n) @@ -844,7 +844,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; - const int column_n = table->DisplayOrder[order_n]; + const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; // Detect hovered column: @@ -1049,7 +1049,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; - const int column_n = table->DisplayOrder[order_n]; + const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; const bool is_hovered = (table->HoveredColumnBorder == column_n); const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceNo); @@ -1190,7 +1190,7 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to // ensure that our left border won't move, which we can do by making sure column_a/column_b resizes cancels each others. if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed)) - if (table->LeftMostStretchedColumnDisplayOrder != -1 && table->LeftMostStretchedColumnDisplayOrder < column_0->IndexDisplayOrder) + if (table->LeftMostStretchedColumnDisplayOrder != -1 && table->LeftMostStretchedColumnDisplayOrder < column_0->DisplayOrder) { // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) float column_1_width = ImMax(column_1->WidthRequested - (column_0_width - column_0->WidthRequested), min_width); @@ -1266,7 +1266,7 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; - const int column_n = table->DisplayOrder[order_n]; + const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; const int merge_group_sub_count = is_frozen_v ? 2 : 1; @@ -2314,14 +2314,14 @@ void ImGui::TableSaveSettings(ImGuiTable* table) { //column_settings->WidthOrWeight = column->WidthRequested; // FIXME-WIP column_settings->Index = (ImS8)n; - column_settings->DisplayOrder = column->IndexDisplayOrder; + column_settings->DisplayOrder = column->DisplayOrder; column_settings->SortOrder = column->SortOrder; column_settings->SortDirection = column->SortDirection; column_settings->Visible = column->IsActive; // We skip saving some data in the .ini file when they are unnecessary to restore our state // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet. - if (column->IndexDisplayOrder != n) + if (column->DisplayOrder != n) settings->SaveFlags |= ImGuiTableFlags_Reorderable; if (column_settings->SortOrder != -1) settings->SaveFlags |= ImGuiTableFlags_Sortable; @@ -2366,7 +2366,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; //column->WidthRequested = column_settings->WidthOrWeight; // FIXME-WIP if (column_settings->DisplayOrder != -1) - column->IndexDisplayOrder = column_settings->DisplayOrder; + column->DisplayOrder = column_settings->DisplayOrder; if (column_settings->SortOrder != -1) { column->SortOrder = column_settings->SortOrder; @@ -2377,7 +2377,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) // FIXME-TABLE: Need to validate .ini data for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - table->DisplayOrder[table->Columns[column_n].IndexDisplayOrder] = (ImS8)column_n; + table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImS8)column_n; } void* ImGui::TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) @@ -2472,7 +2472,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Desired %d/%d\n" "SortOrder: %d, SortDir: %s\n" "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", - n, column->IndexDisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, + n, column->DisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, column->WidthGiven, column->WidthRequested, column->ResizeWeight, column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersDesired, From b7fa96679e96e46c968df66f4204668b2aec2d0d Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 19 Mar 2020 14:55:42 +0100 Subject: [PATCH 418/959] Tables: Locking IndentX per-row so multiple columns with IndentEnabled don't get indent shearing. --- imgui_internal.h | 8 ++++---- imgui_tables.cpp | 26 ++++++++++++++------------ 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 789e71a1..bb4e4b2e 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1941,7 +1941,6 @@ struct ImGuiTableColumn } }; -// FIXME-OPT: Since CountColumns is invariant, we could use a single alloc for ImGuiTable + the three vectors it is carrying. struct ImGuiTable { ImGuiID ID; @@ -1965,6 +1964,7 @@ struct ImGuiTable float RowPosY2; float RowMinHeight; // Height submitted to TableNextRow() float RowTextBaseline; + float RowIndentOffsetX; ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ ImGuiTableRowFlags LastRowFlags : 16; int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper) @@ -2259,11 +2259,11 @@ namespace ImGui IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); IMGUI_API void TableBeginRow(ImGuiTable* table); IMGUI_API void TableEndRow(ImGuiTable* table); - IMGUI_API void TableBeginCell(ImGuiTable* table, int column_no); + IMGUI_API void TableBeginCell(ImGuiTable* table, int column_n); IMGUI_API void TableEndCell(ImGuiTable* table); IMGUI_API ImRect TableGetCellRect(); - IMGUI_API const char* TableGetColumnName(ImGuiTable* table, int column_no); - IMGUI_API void TableSetColumnAutofit(ImGuiTable* table, int column_no); + IMGUI_API const char* TableGetColumnName(ImGuiTable* table, int column_n); + IMGUI_API void TableSetColumnAutofit(ImGuiTable* table, int column_n); IMGUI_API void PushTableBackground(); IMGUI_API void PopTableBackground(); IMGUI_API void TableLoadSettings(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index f79bc73d..123b886d 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1492,6 +1492,7 @@ void ImGui::TableBeginRow(ImGuiTable* table) table->RowPosY1 = table->RowPosY2 = next_y1; table->RowTextBaseline = 0.0f; + table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.CursorMaxPos.y = next_y1; @@ -1611,25 +1612,26 @@ void ImGui::TableEndRow(ImGuiTable* table) table->IsInsideRow = false; } -// [Internal] Called by TableNextRow()TableNextCell()! -// This is called a lot, so we need to be mindful of unnecessary overhead. +// [Internal] Called by TableNextCell()! +// This is called very frequently, so we need to be mindful of unnecessary overhead. // FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. -void ImGui::TableBeginCell(ImGuiTable* table, int column_no) +void ImGui::TableBeginCell(ImGuiTable* table, int column_n) { - table->CurrentColumn = column_no; - ImGuiTableColumn* column = &table->Columns[column_no]; + table->CurrentColumn = column_n; + ImGuiTableColumn* column = &table->Columns[column_n]; ImGuiWindow* window = table->InnerWindow; + // Start position is roughly ~~ CellRect.Min + CellPadding + Indent float start_x = (table->RowFlags & ImGuiTableRowFlags_Headers) ? column->StartXHeaders : column->StartXRows; if (column->Flags & ImGuiTableColumnFlags_IndentEnable) - start_x += window->DC.Indent.x - table->HostIndentX; + start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row. - window->DC.LastItemId = 0; window->DC.CursorPos.x = start_x; window->DC.CursorPos.y = table->RowPosY1 + table->CellPaddingY; window->DC.CursorMaxPos.x = window->DC.CursorPos.x; window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT window->DC.CurrLineTextBaseOffset = table->RowTextBaseline; + window->DC.LastItemId = 0; window->WorkRect.Min.y = window->DC.CursorPos.y; window->WorkRect.Min.x = column->MinX + table->CellPaddingX1; @@ -1653,7 +1655,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_no) //window->DrawList->UpdateClipRect(); window->DrawList->PopClipRect(); window->DrawList->PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); - //IMGUI_DEBUG_LOG("%d (%.0f,%.0f)(%.0f,%.0f)\n", column_no, column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y); + //IMGUI_DEBUG_LOG("%d (%.0f,%.0f)(%.0f,%.0f)\n", column_n, column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y); window->ClipRect = window->DrawList->_ClipRectStack.back(); } } @@ -1759,19 +1761,19 @@ ImRect ImGui::TableGetCellRect() return ImRect(column->MinX, table->RowPosY1, column->MaxX, table->RowPosY2); } -const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_no) +const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_n) { - ImGuiTableColumn* column = &table->Columns[column_no]; + ImGuiTableColumn* column = &table->Columns[column_n]; if (column->NameOffset == -1) return NULL; return &table->ColumnsNames.Buf[column->NameOffset]; } -void ImGui::TableSetColumnAutofit(ImGuiTable* table, int column_no) +void ImGui::TableSetColumnAutofit(ImGuiTable* table, int column_n) { // Disable clipping then auto-fit, will take 2 frames // (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) - ImGuiTableColumn* column = &table->Columns[column_no]; + ImGuiTableColumn* column = &table->Columns[column_n]; column->CannotSkipItemsQueue = (1 << 0); column->AutoFitQueue = (1 << 1); } From 104b11051ff912ca26524e7043218a63d954ba39 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 20 Mar 2020 18:53:44 +0100 Subject: [PATCH 419/959] Tables: Added ImGuiTableColumnFlags_NoReorder. --- imgui.h | 1 + imgui_demo.cpp | 7 ++++++- imgui_internal.h | 7 ++++--- imgui_tables.cpp | 28 +++++++++++++++++----------- 4 files changed, 28 insertions(+), 15 deletions(-) diff --git a/imgui.h b/imgui.h index cc380ea0..998909c8 100644 --- a/imgui.h +++ b/imgui.h @@ -1081,6 +1081,7 @@ enum ImGuiTableColumnFlags_ ImGuiTableColumnFlags_PreferSortDescending = 1 << 13, // Make the initial sort direction Descending when first sorting on this column. ImGuiTableColumnFlags_IndentEnable = 1 << 14, // Use current Indent value when entering cell (default for 1st column). ImGuiTableColumnFlags_IndentDisable = 1 << 15, // Ignore current Indent value when entering cell (default for columns after the 1st one). Indentation changes _within_ the cell will still be honored. + ImGuiTableColumnFlags_NoReorder = 1 << 16, // Disable reordering this column, this will also prevent other columns from crossing over this column. // [Internal] Combinations and masks ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthAlwaysAutoResize, diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 6c84e023..93168cbd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3672,6 +3672,7 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("_NoResize", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoResize); ImGui::CheckboxFlags("_NoClipX", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoClipX); ImGui::CheckboxFlags("_NoHide", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoHide); + ImGui::CheckboxFlags("_NoReorder", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoReorder); ImGui::CheckboxFlags("_DefaultSort", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_DefaultSort); ImGui::CheckboxFlags("_DefaultHide", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_DefaultHide); ImGui::CheckboxFlags("_NoSort", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoSort); @@ -4213,7 +4214,7 @@ static void ShowDemoWindowTables() const ImDrawList* table_draw_list = NULL; // " const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : inner_width_without_scroll; - if (ImGui::BeginTable("##table", 5, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use)) + if (ImGui::BeginTable("##table", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use)) { // Declare columns // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. @@ -4223,6 +4224,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Action); ImGui::TableSetupColumn("Quantity Long Label", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 1.0f, MyItemColumnID_Quantity);// , ImGuiTableColumnFlags_None | ImGuiTableColumnFlags_WidthAlwaysAutoResize); ImGui::TableSetupColumn("Description", ImGuiTableColumnFlags_WidthStretch, 1.0f, MyItemColumnID_Description);// , ImGuiTableColumnFlags_WidthAlwaysAutoResize); + ImGui::TableSetupColumn("Hidden", ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort); // Sort our data if sort specs have been changed! const ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs(); @@ -4319,6 +4321,9 @@ static void ShowDemoWindowTables() else ImGui::Text("Lorem ipsum dolor sit amet"); + ImGui::TableNextCell(); + ImGui::Text("1234"); + ImGui::PopID(); } } diff --git a/imgui_internal.h b/imgui_internal.h index bb4e4b2e..b75119ec 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1888,6 +1888,7 @@ struct ImGuiTabBar #define IMGUI_TABLE_MAX_DRAW_CHANNELS (2 + 64 * 2) // See TableUpdateDrawChannels() // [Internal] sizeof() ~ 100 +// We use the terminology "Active" to refer to a column that is not Hidden by user or programmatically. We don't use the term "Visible" because it is ambiguous since an Active column can be non-visible because of scrolling. struct ImGuiTableColumn { ImRect ClipRect; // Clipping rectangle for the column @@ -1911,11 +1912,11 @@ struct ImGuiTableColumn ImS16 ContentWidthHeadersDesired; ImS16 NameOffset; // Offset into parent ColumnsNames[] bool IsActive; // Is the column not marked Hidden by the user (regardless of clipping). We're not calling this "Visible" here because visibility also depends on clipping. - bool NextIsActive; + bool IsActiveNextFrame; bool IsClipped; // Set when not overlapping the host window clipping rectangle. We don't use the opposite "!Visible" name because Clipped can be altered by events. bool SkipItems; ImS8 DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) - ImS8 IndexWithinActiveSet; // Index within active set (<= IndexOrder) + ImS8 IndexWithinActiveSet; // Index within active/visible set (<= IndexToDisplayOrder) ImS8 DrawChannelCurrent; // Index within DrawSplitter.Channels[] ImS8 DrawChannelRowsBeforeFreeze; ImS8 DrawChannelRowsAfterFreeze; @@ -1931,7 +1932,7 @@ struct ImGuiTableColumn memset(this, 0, sizeof(*this)); ResizeWeight = WidthRequested = WidthGiven = -1.0f; NameOffset = -1; - IsActive = NextIsActive = true; + IsActive = IsActiveNextFrame = true; DisplayOrder = IndexWithinActiveSet = -1; DrawChannelCurrent = DrawChannelRowsBeforeFreeze = DrawChannelRowsAfterFreeze = -1; PrevActiveColumn = NextActiveColumn = -1; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 123b886d..5a9f7627 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -397,10 +397,10 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; column->NameOffset = -1; if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide)) - column->NextIsActive = true; - if (column->IsActive != column->NextIsActive) + column->IsActiveNextFrame = true; + if (column->IsActive != column->IsActiveNextFrame) { - column->IsActive = column->NextIsActive; + column->IsActive = column->IsActiveNextFrame; table->IsSettingsDirty = true; if (!column->IsActive && column->SortOrder != -1) table->IsSortSpecsDirty = true; @@ -1432,7 +1432,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, { // Init default visibility/sort state if (flags & ImGuiTableColumnFlags_DefaultHide) - column->IsActive = column->NextIsActive = false; + column->IsActive = column->IsActiveNextFrame = false; if (flags & ImGuiTableColumnFlags_DefaultSort) { column->SortOrder = 0; // Multiple columns using _DefaultSort will be reordered when building the sort specs. @@ -1859,7 +1859,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) if (column->IsActive && table->ColumnsActiveCount <= 1) menu_item_active = false; if (MenuItem(name, NULL, column->IsActive, menu_item_active)) - column->NextIsActive = !column->IsActive; + column->IsActiveNextFrame = !column->IsActive; } PopItemFlag(); } @@ -2018,19 +2018,25 @@ void ImGui::TableHeader(const char* label) table->HeldHeaderColumn = (ImS8)column_n; window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f; - // Drag and drop: re-order columns. Frozen columns are not reorderable. + // Drag and drop to re-order columns. // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone. if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive) { // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x table->ReorderColumn = (ImS8)column_n; table->InstanceInteracted = table->InstanceNo; + + // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder. if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x) - if (column->PrevActiveColumn != -1 && (column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (table->Columns[column->PrevActiveColumn].IndexWithinActiveSet < table->FreezeColumnsRequest)) - table->ReorderColumnDir = -1; + if (ImGuiTableColumn* prev_column = (column->PrevActiveColumn != -1) ? &table->Columns[column->PrevActiveColumn] : NULL) + if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder)) + if ((column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinActiveSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = -1; if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x) - if (column->NextActiveColumn != -1 && (column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (table->Columns[column->NextActiveColumn].IndexWithinActiveSet < table->FreezeColumnsRequest)) - table->ReorderColumnDir = +1; + if (ImGuiTableColumn* next_column = (column->NextActiveColumn != -1) ? &table->Columns[column->NextActiveColumn] : NULL) + if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder)) + if ((column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (next_column->IndexWithinActiveSet < table->FreezeColumnsRequest)) + table->ReorderColumnDir = +1; } // Sort order arrow @@ -2374,7 +2380,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) column->SortOrder = column_settings->SortOrder; column->SortDirection = column_settings->SortDirection; } - column->IsActive = column->NextIsActive = column_settings->Visible; + column->IsActive = column->IsActiveNextFrame = column_settings->Visible; } // FIXME-TABLE: Need to validate .ini data From e60b5a3f75a7b69e0308a778443dbee7efdcce1b Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 6 Apr 2020 17:20:17 +0200 Subject: [PATCH 420/959] Tables: Internals: Added TableGetColumnResizeID(), renamed InstanceNo > InstanceCurrent. --- imgui_internal.h | 5 +++-- imgui_tables.cpp | 34 +++++++++++++++++++++------------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b75119ec..12a5f983 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1959,7 +1959,7 @@ struct ImGuiTable int ColumnsActiveCount; // Number of non-hidden columns (<= ColumnsCount) int CurrentColumn; int CurrentRow; - ImS16 InstanceNo; // Count of BeginTable() calls with same ID in the same frame (generally 0) + ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple table with same ID look are multiple tables, they are just synched. ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with float RowPosY1; float RowPosY2; @@ -2001,7 +2001,7 @@ struct ImGuiTable ImS8 DeclColumnsCount; // Count calls to TableSetupColumn() ImS8 HoveredColumnBody; // [DEBUG] Unlike HoveredColumnBorder this doesn't fulfill all Hovering rules properly. Used for debugging/tools for now. ImS8 HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). - ImS8 ResizedColumn; // Index of column being resized. Reset by InstanceNo==0. + ImS8 ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0. ImS8 LastResizedColumn; // Index of column being resized from previous frame. ImS8 HeldHeaderColumn; // Index of column header being held. ImS8 ReorderColumn; // Index of column being reordered. (not cleared) @@ -2264,6 +2264,7 @@ namespace ImGui IMGUI_API void TableEndCell(ImGuiTable* table); IMGUI_API ImRect TableGetCellRect(); IMGUI_API const char* TableGetColumnName(ImGuiTable* table, int column_n); + IMGUI_API ImGuiID TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no = 0); IMGUI_API void TableSetColumnAutofit(ImGuiTable* table, int column_n); IMGUI_API void PushTableBackground(); IMGUI_API void PopTableBackground(); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5a9f7627..9d7acc24 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -186,7 +186,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Acquire storage for the table ImGuiTable* table = g.Tables.GetOrAddByKey(id); const ImGuiTableFlags table_last_flags = table->Flags; - const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceNo + 1; + const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceCurrent + 1; const ImGuiID instance_id = id + instance_no; if (instance_no > 0) IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID"); @@ -194,7 +194,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Initialize table->ID = id; table->Flags = flags; - table->InstanceNo = (ImS16)instance_no; + table->InstanceCurrent = (ImS16)instance_no; table->LastFrameActive = g.FrameCount; table->OuterWindow = table->InnerWindow = outer_window; table->ColumnsCount = columns_count; @@ -332,7 +332,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) // (We process this at the first TableBegin of the frame) // FIXME-TABLE: Preserve contents width _while resizing down_ until releasing. // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling. - if (table->InstanceNo == 0) + if (table->InstanceCurrent == 0) { if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX) TableSetColumnWidth(table, &table->Columns[table->ResizedColumn], table->ResizedColumnNextWidth); @@ -343,7 +343,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) // Handle reordering request // Note: we don't clear ReorderColumn after handling the request. - if (table->InstanceNo == 0) + if (table->InstanceCurrent == 0) { if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1) table->ReorderColumn = -1; @@ -799,7 +799,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->IsUsingHeaders = false; // Context menu - if (table->IsContextPopupOpen && table->InstanceNo == table->InstanceInteracted) + if (table->IsContextPopupOpen && table->InstanceCurrent == table->InstanceInteracted) { if (BeginPopup("##TableContextMenu")) { @@ -856,7 +856,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) continue; - ImGuiID column_id = table->ID + (table->InstanceNo * table->ColumnsCount) + column_n; + ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent); ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, hit_y2); //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)); KeepAliveID(column_id); @@ -873,7 +873,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) if (held) { table->ResizedColumn = (ImS8)column_n; - table->InstanceInteracted = table->InstanceNo; + table->InstanceInteracted = table->InstanceCurrent; } if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held) { @@ -963,7 +963,7 @@ void ImGui::EndTable() { inner_window->Scroll.x = 0.0f; } - else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceNo) + else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent) { ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn]; if (column->MaxX < table->InnerClipRect.Min.x) @@ -1052,7 +1052,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; const bool is_hovered = (table->HoveredColumnBorder == column_n); - const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceNo); + const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered); if (column->NextActiveColumn == -1 && !is_resizable) @@ -1769,6 +1769,14 @@ const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_n) return &table->ColumnsNames.Buf[column->NameOffset]; } +// Return the resizing ID for the right-side of the given column. +ImGuiID ImGui::TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no) +{ + IM_ASSERT(column_n < table->ColumnsCount); + ImGuiID id = table->ID + (instance_no * table->ColumnsCount) + column_n; + return id; +} + void ImGui::TableSetColumnAutofit(ImGuiTable* table, int column_n) { // Disable clipping then auto-fit, will take 2 frames @@ -1917,7 +1925,7 @@ void ImGui::TableAutoHeaders() //if (g.IO.KeyCtrl) { static char buf[32]; name = buf; ImGuiTableColumn* c = &table->Columns[column_n]; if (c->Flags & ImGuiTableColumnFlags_WidthStretch) ImFormatString(buf, 32, "%.3f>%.1f", c->ResizeWeight, c->WidthGiven); else ImFormatString(buf, 32, "%.1f", c->WidthGiven); } // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them) - PushID(table->InstanceNo * table->ColumnsCount + column_n); + PushID(table->InstanceCurrent * table->ColumnsCount + column_n); TableHeader(name); PopID(); @@ -1964,7 +1972,7 @@ void ImGui::TableAutoHeaders() { table->IsContextPopupOpen = true; table->ContextPopupColumn = (ImS8)open_context_popup; - table->InstanceInteracted = table->InstanceNo; + table->InstanceInteracted = table->InstanceCurrent; OpenPopup("##TableContextMenu"); } } @@ -2011,7 +2019,7 @@ void ImGui::TableHeader(const char* label) //window->DC.CursorPos.x = column->MinX + table->CellPadding.x; // Keep header highlighted when context menu is open. (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) - const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceNo); + const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent); const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld | ImGuiSelectableFlags_DontClosePopups, ImVec2(0.0f, label_height)); const bool held = IsItemActive(); if (held) @@ -2024,7 +2032,7 @@ void ImGui::TableHeader(const char* label) { // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x table->ReorderColumn = (ImS8)column_n; - table->InstanceInteracted = table->InstanceNo; + table->InstanceInteracted = table->InstanceCurrent; // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder. if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x) From 8eb1c925f068098a754e2cbe73824ad59efe80fc Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 15 Apr 2020 11:05:50 +0200 Subject: [PATCH 421/959] Tables: Internals: Added FindTableByID(), removing trailing spaces. # Conflicts: # imgui_internal.h --- imgui.h | 4 ++-- imgui_internal.h | 7 ++++--- imgui_tables.cpp | 8 +++++++- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/imgui.h b/imgui.h index 998909c8..f559da62 100644 --- a/imgui.h +++ b/imgui.h @@ -176,7 +176,7 @@ typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: f typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() -typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() +typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() @@ -672,7 +672,7 @@ namespace ImGui // - If you are using tables as a sort of grid, populating every columns with the same type of contents, // you may prefer using TableNextCell() instead of TableNextRow() + TableSetColumnIndex(). // - See Demo->Tables for details. - // - See ImGuiTableFlags_ enums for a description of available flags. + // - See ImGuiTableFlags_ enums for a description of available flags. #define IMGUI_HAS_TABLE 1 IMGUI_API bool BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! diff --git a/imgui_internal.h b/imgui_internal.h index 12a5f983..1e7e3075 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -547,7 +547,7 @@ struct ImSpanAllocator inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; } inline void* GetSpanPtrBegin(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrSpan == CHUNKS); return (void*)(BasePtr + Offsets[n]); } inline void* GetSpanPtrEnd(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrSpan == CHUNKS); return (n + 1 < CHUNKS) ? BasePtr + Offsets[n + 1] : (void*)(BasePtr + TotalSize); } - template + template inline void GetSpan(int n, ImSpan* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); } }; @@ -1901,7 +1901,7 @@ struct ImGuiTableColumn float WidthRequested; // Master width data when !(Flags & _WidthStretch) float WidthGiven; // == (MaxX - MinX). FIXME-TABLE: Store all persistent width in multiple of FontSize? float StartXRows; // Start position for the frame, currently ~(MinX + CellPaddingX) - float StartXHeaders; + float StartXHeaders; float ContentMaxPosRowsFrozen; // Submitted contents absolute maximum position, from which we can infer width. float ContentMaxPosRowsUnfrozen; // (kept as float because we need to manipulate those between each cell change) float ContentMaxPosHeadersUsed; @@ -2003,7 +2003,7 @@ struct ImGuiTable ImS8 HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). ImS8 ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0. ImS8 LastResizedColumn; // Index of column being resized from previous frame. - ImS8 HeldHeaderColumn; // Index of column header being held. + ImS8 HeldHeaderColumn; // Index of column header being held. ImS8 ReorderColumn; // Index of column being reordered. (not cleared) ImS8 ReorderColumnDir; // -1 or +1 ImS8 RightMostActiveColumn; // Index of right-most non-hidden column. @@ -2246,6 +2246,7 @@ namespace ImGui IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); // Tables + IMGUI_API ImGuiTable* FindTableByID(ImGuiID id); IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void TableBeginUpdateColumns(ImGuiTable* table); IMGUI_API void TableUpdateDrawChannels(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 9d7acc24..0e37a2e1 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -127,6 +127,12 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) return flags; } +ImGuiTable* ImGui::FindTableByID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.Tables.GetByKey(id); +} + // About 'outer_size': // The meaning of outer_size needs to differ slightly depending of if we are using ScrollX/ScrollY flags. // With ScrollX/ScrollY: using a child window for scrolling: @@ -2137,7 +2143,7 @@ void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* click table->IsSortSpecsDirty = true; } -// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set) +// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set) // You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since last call, or the first time. // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() From b7ff85d9ad9872ec3b16ce1f6c2f57c16ef3703f Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 7 May 2020 23:52:17 +0200 Subject: [PATCH 422/959] Tables: Browse settings list in Metrics (outside of Table entry). --- imgui.cpp | 5 +++-- imgui_internal.h | 1 + imgui_tables.cpp | 37 +++++++++++++++++++++---------------- 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index c8023fdb..47c0c4d3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10689,8 +10689,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) #ifdef IMGUI_HAS_TABLE if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) { - //for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) - // DebugNodeTableSettings(settings); + for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) + DebugNodeTableSettings(settings); TreePop(); } #endif // #ifdef IMGUI_HAS_TABLE @@ -11071,6 +11071,7 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow*, const ImDrawLis void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} void ImGui::DebugNodeTable(ImGuiTable*) {} +void ImGui::DebugNodeTableSettings(ImGuiTableSettings*) {} void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {} void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {} void ImGui::DebugNodeWindowsList(ImVector*, const char*) {} diff --git a/imgui_internal.h b/imgui_internal.h index 1e7e3075..62385a77 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2394,6 +2394,7 @@ namespace ImGui 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); + IMGUI_API void DebugNodeTableSettings(ImGuiTableSettings* settings); IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label); IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings); IMGUI_API void DebugNodeWindowsList(ImVector* windows, const char* label); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0e37a2e1..025f144e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2505,25 +2505,30 @@ void ImGui::DebugNodeTable(ImGuiTable* table) (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) ? "WidthAlwaysAutoResize " : "", (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : ""); } - ImGuiTableSettings* settings = TableFindSettings(table); - if (settings && TreeNode("Settings")) - { - BulletText("SaveFlags: 0x%08X", settings->SaveFlags); - BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax); - for (int n = 0; n < settings->ColumnsCount; n++) - { - ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n]; - ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None; - BulletText("Column %d Order %d SortOrder %d %s Visible %d UserID 0x%08X WidthOrWeight %.3f", - n, column_settings->DisplayOrder, column_settings->SortOrder, - (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---", - column_settings->Visible, column_settings->UserID, column_settings->WidthOrWeight); - } - TreePop(); - } + if (ImGuiTableSettings* settings = TableFindSettings(table)) + DebugNodeTableSettings(settings); TreePop(); } } + +void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings) +{ + if (!TreeNode((void*)(intptr_t)settings->ID, "Settings 0x%08X (%d columns)", settings->ID, settings->ColumnsCount)) + return; + BulletText("SaveFlags: 0x%08X", settings->SaveFlags); + BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax); + for (int n = 0; n < settings->ColumnsCount; n++) + { + ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n]; + ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None; + BulletText("Column %d Order %d SortOrder %d %s Visible %d UserID 0x%08X WidthOrWeight %.3f", + n, column_settings->DisplayOrder, column_settings->SortOrder, + (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---", + column_settings->Visible, column_settings->UserID, column_settings->WidthOrWeight); + } + TreePop(); +} + #endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW //------------------------------------------------------------------------- From 9f43aae226c352226abc6c121d96f96dafc946a6 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 12 May 2020 17:23:10 +0200 Subject: [PATCH 423/959] Tables: Calculating ideal total width, some renaming, comments. Clarify that inner_width is unused with ScrollX=0. Clip many comments to 120 columns. --- imgui.cpp | 4 +- imgui_demo.cpp | 12 +- imgui_internal.h | 13 ++- imgui_tables.cpp | 278 +++++++++++++++++++++++++++-------------------- 4 files changed, 171 insertions(+), 136 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 47c0c4d3..55c67bbb 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10515,7 +10515,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); } else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; } else if (rect_type == TRT_ColumnsContentHeadersUsed) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate - else if (rect_type == TRT_ColumnsContentHeadersIdeal) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersDesired, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // " + else if (rect_type == TRT_ColumnsContentHeadersIdeal) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // " else if (rect_type == TRT_ColumnsContentRowsFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthRowsFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // " else if (rect_type == TRT_ColumnsContentRowsUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->MinX + c->ContentWidthRowsUnfrozen, table->InnerClipRect.Max.y); } // " IM_ASSERT(0); @@ -10573,7 +10573,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++) { ImGuiTable* table = g.Tables.GetByIndex(table_n); - if (table->LastFrameActive < g.FrameCount - 1 || table->OuterWindow != g.NavWindow) + if (table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow)) continue; BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name); diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 93168cbd..15876be7 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3680,8 +3680,8 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("_NoSortDescending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_NoSortDescending); ImGui::CheckboxFlags("_PreferSortAscending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_PreferSortAscending); ImGui::CheckboxFlags("_PreferSortDescending", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_PreferSortDescending); - ImGui::CheckboxFlags("_IndentEnable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentEnable); - ImGui::CheckboxFlags("_IndentDisable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentDisable); + ImGui::CheckboxFlags("_IndentEnable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentEnable); ImGui::SameLine(); HelpMarker("Default for column 0"); + ImGui::CheckboxFlags("_IndentDisable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentDisable); ImGui::SameLine(); HelpMarker("Default for column >0"); ImGui::PopID(); ImGui::PopStyleVar(2); } @@ -4089,7 +4089,6 @@ static void ShowDemoWindowTables() static int items_count = IM_ARRAYSIZE(template_items_names); static ImVec2 outer_size_value = ImVec2(0, 250); static float row_min_height = 0.0f; // Auto - static float inner_width_without_scroll = 0.0f; // Fill static float inner_width_with_scroll = 0.0f; // Auto-extend static bool outer_size_enabled = true; static bool lock_first_column_visibility = false; @@ -4171,10 +4170,7 @@ static void ShowDemoWindowTables() // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. // To facilitate experimentation we expose two values and will select the right one depending on active flags. - if (flags & ImGuiTableFlags_ScrollX) - ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX); - else - ImGui::DragFloat("inner_width (when ScrollX inactive)", &inner_width_without_scroll, 1.0f, 0.0f, FLT_MAX); + ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX); ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX); ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); ImGui::DragInt("items_count", &items_count, 0.1f, 0, 5000); @@ -4213,7 +4209,7 @@ static void ShowDemoWindowTables() ImVec2 table_scroll_cur, table_scroll_max; // For debug display const ImDrawList* table_draw_list = NULL; // " - const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : inner_width_without_scroll; + const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : 0.0f; if (ImGui::BeginTable("##table", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use)) { // Declare columns diff --git a/imgui_internal.h b/imgui_internal.h index 62385a77..c77d3081 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1905,11 +1905,11 @@ struct ImGuiTableColumn float ContentMaxPosRowsFrozen; // Submitted contents absolute maximum position, from which we can infer width. float ContentMaxPosRowsUnfrozen; // (kept as float because we need to manipulate those between each cell change) float ContentMaxPosHeadersUsed; - float ContentMaxPosHeadersDesired; + float ContentMaxPosHeadersIdeal; ImS16 ContentWidthRowsFrozen; // Contents width. Because row freezing is not correlated with headers/not-headers we need all 4 variants (ImDrawCmd merging uses different data than alignment code). ImS16 ContentWidthRowsUnfrozen; // (encoded as ImS16 because we actually rarely use those width) ImS16 ContentWidthHeadersUsed; // TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls - ImS16 ContentWidthHeadersDesired; + ImS16 ContentWidthHeadersIdeal; ImS16 NameOffset; // Offset into parent ColumnsNames[] bool IsActive; // Is the column not marked Hidden by the user (regardless of clipping). We're not calling this "Visible" here because visibility also depends on clipping. bool IsActiveNextFrame; @@ -1982,7 +1982,8 @@ struct ImGuiTable float LastOuterHeight; // Outer height from last frame float LastFirstRowHeight; // Height of first row from last frame float ColumnsTotalWidth; - float InnerWidth; + float InnerWidth; // User value passed to BeginTable(), see comments at the top of BeginTable() for details. + float IdealTotalWidth; // Sum of ideal column width for nothing to be clipped float ResizedColumnNextWidth; ImRect OuterRect; // Note: OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). ImRect WorkRect; @@ -2264,14 +2265,14 @@ namespace ImGui IMGUI_API void TableBeginCell(ImGuiTable* table, int column_n); IMGUI_API void TableEndCell(ImGuiTable* table); IMGUI_API ImRect TableGetCellRect(); - IMGUI_API const char* TableGetColumnName(ImGuiTable* table, int column_n); - IMGUI_API ImGuiID TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no = 0); + IMGUI_API const char* TableGetColumnName(const ImGuiTable* table, int column_n); + IMGUI_API ImGuiID TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no = 0); IMGUI_API void TableSetColumnAutofit(ImGuiTable* table, int column_n); IMGUI_API void PushTableBackground(); IMGUI_API void PopTableBackground(); IMGUI_API void TableLoadSettings(ImGuiTable* table); IMGUI_API void TableSaveSettings(ImGuiTable* table); - IMGUI_API ImGuiTableSettings* TableFindSettings(ImGuiTable* table); + IMGUI_API ImGuiTableSettings* TableFindSettings(const ImGuiTable* table); IMGUI_API void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); IMGUI_API void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); IMGUI_API void TableSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 025f144e..ae209ec5 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -109,8 +109,8 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) if (flags & ImGuiTableFlags_Resizable) flags |= ImGuiTableFlags_BordersVInner; - // Adjust flags: disable top rows freezing if there's no scrolling - // In theory we could want to assert if ScrollFreeze was set without the corresponding scroll flag, but that would hinder demos. + // Adjust flags: disable top rows freezing if there's no scrolling. + // We could want to assert if ScrollFreeze was set without the corresponding scroll flag, but that would hinder demos. if ((flags & ImGuiTableFlags_ScrollX) == 0) flags &= ~ImGuiTableFlags_ScrollFreezeColumnsMask_; if ((flags & ImGuiTableFlags_ScrollY) == 0) @@ -120,7 +120,8 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) if ((flags & ImGuiTableFlags_NoHostExtendY) && (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0) flags &= ~ImGuiTableFlags_NoHostExtendY; - // Adjust flags: we don't support NoClipX with (FreezeColumns > 0), we could with some work but it doesn't appear to be worth the effort + // Adjust flags: we don't support NoClipX with (FreezeColumns > 0) + // We could with some work but it doesn't appear to be worth the effort. if (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) flags &= ~ImGuiTableFlags_NoClipX; @@ -133,28 +134,32 @@ ImGuiTable* ImGui::FindTableByID(ImGuiID id) return g.Tables.GetByKey(id); } -// About 'outer_size': -// The meaning of outer_size needs to differ slightly depending of if we are using ScrollX/ScrollY flags. -// With ScrollX/ScrollY: using a child window for scrolling: +// (Read carefully because this is subtle but it does make sense!) +// About 'outer_size', its meaning needs to differ slightly depending of if we are using ScrollX/ScrollY flags: +// X: +// - outer_size.x < 0.0f -> right align from window/work-rect maximum x edge. +// - outer_size.x = 0.0f -> auto enlarge, use all available space. +// - outer_size.x > 0.0f -> fixed width +// Y with ScrollX/ScrollY: using a child window for scrolling: // - outer_size.y < 0.0f -> bottom align -// - outer_size.y = 0.0f -> bottom align: consistent with BeginChild(), best to preserve (0,0) default arg -// - outer_size.y > 0.0f -> fixed child height -// Without scrolling, we output table directly in parent window: +// - outer_size.y = 0.0f -> bottom align, consistent with BeginChild(). not recommended unless table is last item in parent window. +// - outer_size.y > 0.0f -> fixed child height. recommended when using Scrolling on any axis. +// Y without scrolling, we output table directly in parent window: // - outer_size.y < 0.0f -> bottom align (will auto extend, unless NoHostExtendV is set) // - outer_size.y = 0.0f -> zero minimum height (will auto extend, unless NoHostExtendV is set) // - outer_size.y > 0.0f -> minimum height (will auto extend, unless NoHostExtendV is set) -// About: 'inner_width': +// About 'inner_width': // With ScrollX: // - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird -// - inner_width = 0.0f -> auto enlarge: *only* fixed size columns, which will take space they need (proportional columns becomes fixed columns) <-- desired default :( -// - inner_width > 0.0f -> fit in known width: fixed column take space they need if possible (otherwise shrink down), proportional columns share remaining space. +// - inner_width = 0.0f -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns. +// - inner_width > 0.0f -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space! // Without ScrollX: -// - inner_width < 0.0f -> fit in known width (right align from outer_size.x) <-- desired default -// - inner_width = 0.0f -> auto enlarge: will emit contents size in parent window -// - inner_width > 0.0f -> fit in known width (bypass outer_size.x, permitted but not useful, should instead alter outer_width) -// FIXME-TABLE: This is currently not very useful. -// FIXME-TABLE: Replace enlarge vs fixed width by a flag. -// Even if not really useful, we allow 'inner_scroll_width < outer_size.x' for consistency and to facilitate understanding of what the value does. +// - inner_width -> *ignored* +// Details: +// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept +// of "available space" doesn't make sense. +// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding +// of what the value does. bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width) { ImGuiID id = GetID(str_id); @@ -213,15 +218,17 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (use_child_window) { - // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) + // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent + // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) ImVec2 override_content_size(FLT_MAX, FLT_MAX); if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY)) override_content_size.y = FLT_MIN; - // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and never lead to any scrolling) - // We don't handle inner_width < 0.0f, we could potentially use it to right-align based on the right side of the child window work rect, - // which would require knowing ahead if we are going to have decoration taking horizontal spaces (typically a vertical scrollbar). - if (inner_width != 0.0f) + // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and + // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align + // based on the right side of the child window work rect, which would require knowing ahead if we are going to + // have decoration taking horizontal spaces (typically a vertical scrollbar). + if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f) override_content_size.x = inner_width; if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX) @@ -322,7 +329,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG TableLoadSettings(table); // Disable output until user calls TableNextRow() or TableNextCell() leading to the TableUpdateLayout() call.. - // This is not strictly necessary but will reduce cases were misleading "out of table" output will be confusing to the user. + // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. inner_window->SkipItems = true; @@ -373,7 +380,8 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImS8)reorder_dir; IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir); - // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[], rebuild the later from the former. + // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[], + // rebuild the later from the former. for (int column_n = 0; column_n < table->ColumnsCount; column_n++) table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImS8)column_n; table->ReorderColumnDir = 0; @@ -452,10 +460,13 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) void ImGui::TableUpdateDrawChannels(ImGuiTable* table) { // Allocate draw channels. - // - We allocate them following the storage order instead of the display order so reordering columns won't needlessly increase overall dormant memory cost. - // - We isolate headers draw commands in their own channels instead of just altering clip rects. This is in order to facilitate merging of draw commands. - // - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of draw channels. - // - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. + // - We allocate them following storage order instead of display order so reordering columns won't needlessly + // increase overall dormant memory cost. + // - We isolate headers draw commands in their own channels instead of just altering clip rects. + // This is in order to facilitate merging of draw commands. + // - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels. + // - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other + // channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. // Draw channel allocation (before merging): // - NoClip --> 1+1 channels: background + foreground (same clip rect == 1 draw call) // - Clip --> 1+N channels @@ -536,21 +547,24 @@ static float TableGetMinColumnWidth() // Layout columns for the frame // Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first. -// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for WidthAlwaysAutoResize columns, -// increase feedback side-effect with widgets relying on WorkRect.Max.x. Maybe provide a default distribution for WidthAlwaysAutoResize columns? +// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for WidthAlwaysAutoResize +// columns, increase feedback side-effect with widgets relying on WorkRect.Max.x. Maybe provide a default distribution +// for WidthAlwaysAutoResize columns? void ImGui::TableUpdateLayout(ImGuiTable* table) { IM_ASSERT(table->IsLayoutLocked == false); // Compute offset, clip rect for the frame + // (can't make auto padding larger than what WorkRect knows about so right-alignment matches) const ImRect work_rect = table->WorkRect; - const float padding_auto_x = table->CellPaddingX2; // Can't make auto padding larger than what WorkRect knows about so right-alignment matches. + const float padding_auto_x = table->CellPaddingX2; const float min_column_width = TableGetMinColumnWidth(); int count_fixed = 0; float width_fixed = 0.0f; float total_weights = 0.0f; table->LeftMostStretchedColumnDisplayOrder = -1; + table->IdealTotalWidth = 0.0f; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) @@ -569,6 +583,16 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (table->Flags & ImGuiTableFlags_Sortable) TableFixColumnSortDirection(column); + // Calculate "ideal" column width for nothing to be clipped. + // Combine width from regular rows + width from headers unless requested not to. + const float column_content_width_rows = (float)ImMax(column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen); + const float column_content_width_headers = (float)column->ContentWidthHeadersIdeal; + float column_width_ideal = column_content_width_rows; + if (!(table->Flags & ImGuiTableFlags_NoHeadersWidth) && !(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth)) + column_width_ideal = ImMax(column_width_ideal, column_content_width_headers); + column_width_ideal = ImMax(column_width_ideal + padding_auto_x, min_column_width); + table->IdealTotalWidth += column_width_ideal; + if (column->Flags & (ImGuiTableColumnFlags_WidthAlwaysAutoResize | ImGuiTableColumnFlags_WidthFixed)) { // Latch initial size for fixed columns @@ -576,14 +600,11 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) const bool init_size = (column->AutoFitQueue != 0x00) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize); if (init_size) { - // Combine width from regular rows + width from headers unless requested not to - float width_request = (float)ImMax(column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen); - if (!(table->Flags & ImGuiTableFlags_NoHeadersWidth) && !(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth)) - width_request = ImMax(width_request, (float)column->ContentWidthHeadersDesired); - column->WidthRequested = ImMax(width_request + padding_auto_x, min_column_width); - - // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets (e.g. TextWrapped) too much. - // Otherwise what tends to happen is that TextWrapped would output a very large height (= first frame scrollbar display very off + clipper would skip lots of items) + column->WidthRequested = column_width_ideal; + + // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets + // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very + // large height (= first frame scrollbar display very off + clipper would skip lots of items). // This is merely making the side-effect less extreme, but doesn't properly fixes it. if (column->AutoFitQueue > 0x01 && table->IsInitializing) column->WidthRequested = ImMax(column->WidthRequested, min_column_width * 4.0f); @@ -606,7 +627,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible const float width_spacings = table->CellSpacingX * (table->ColumnsActiveCount - 1); float width_avail; - if ((table->Flags & ImGuiTableFlags_ScrollX) && (table->InnerWidth == 0.0f)) + if ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) width_avail = table->InnerClipRect.GetWidth() - width_spacings - 1.0f; else width_avail = work_rect.GetWidth() - width_spacings - 1.0f; @@ -630,15 +651,16 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->WidthRequested = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, min_column_width) + 0.01f); width_remaining_for_stretched_columns -= column->WidthRequested; - // [Resize Rule 2] Resizing from right-side of a weighted column before a fixed column froward sizing to left-side of fixed column - // We also need to copy the NoResize flag.. + // [Resize Rule 2] Resizing from right-side of a weighted column before a fixed column froward sizing + // to left-side of fixed column. We also need to copy the NoResize flag.. if (column->NextActiveColumn != -1) if (ImGuiTableColumn* next_column = &table->Columns[column->NextActiveColumn]) if (next_column->Flags & ImGuiTableColumnFlags_WidthFixed) column->Flags |= (next_column->Flags & ImGuiTableColumnFlags_NoDirectResize_); } - // [Resize Rule 1] The right-most active column is not resizable if there is at least one Stretch column (see comments in TableResizeColumn().) + // [Resize Rule 1] The right-most active column is not resizable if there is at least one Stretch column + // (see comments in TableResizeColumn().) if (column->NextActiveColumn == -1 && table->LeftMostStretchedColumnDisplayOrder != -1) column->Flags |= ImGuiTableColumnFlags_NoDirectResize_; @@ -675,8 +697,9 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) else #endif - // Redistribute remainder width due to rounding (remainder width is < 1.0f * number of Stretch column) - // Using right-to-left distribution (more likely to match resizing cursor), could be adjusted depending where the mouse cursor is and/or relative weights. + // Redistribute remainder width due to rounding (remainder width is < 1.0f * number of Stretch column). + // Using right-to-left distribution (more likely to match resizing cursor), could be adjusted depending where + // the mouse cursor is and/or relative weights. // FIXME-TABLE: May be simpler to store floating width and floor final positions only // FIXME-TABLE: Make it optional? User might prefer to preserve pixel perfect same size? if (width_remaining_for_stretched_columns >= 1.0f) @@ -707,7 +730,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) { // Hidden column: clear a few fields and we are done with it for the remainder of the function. - // We set a zero-width clip rect however we pay attention to set Min.y/Max.y properly to not interfere with the clipper. + // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. column->MinX = column->MaxX = offset_x; column->StartXRows = column->StartXHeaders = offset_x; column->WidthGiven = 0.0f; @@ -729,8 +752,9 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } else { - // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. - // Because of this we also know that all of the columns will always fit in table->WorkRect and therefore in table->InnerRect (because ScrollX is off) + // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make + // sure they are all visible. Because of this we also know that all of the columns will always fit in + // table->WorkRect and therefore in table->InnerRect (because ScrollX is off) if (!(table->Flags & ImGuiTableFlags_NoKeepColumnsVisible)) max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width; } @@ -760,8 +784,9 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1; // Alignment - // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in many cases. - // (To be able to honor this we might be able to store a log of cells width, per row, for visible rows, but nav/programmatic scroll would have visible artifacts.) + // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in + // many cases (to be able to honor this we might be able to store a log of cells width, per row, for + // visible rows, but nav/programmatic scroll would have visible artifacts.) //if (column->Flags & ImGuiTableColumnFlags_AlignRight) // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->ContentWidthRowsUnfrozen); //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) @@ -770,7 +795,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Reset content width variables const float initial_max_pos_x = column->MinX + table->CellPaddingX1; column->ContentMaxPosRowsFrozen = column->ContentMaxPosRowsUnfrozen = initial_max_pos_x; - column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersDesired = initial_max_pos_x; + column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersIdeal = initial_max_pos_x; } // Don't decrement auto-fit counters until container window got a chance to submit its items @@ -787,7 +812,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) active_n++; } - // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either because of using _WidthAlwaysAutoResize/_WidthStretch) + // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, + // either because of using _WidthAlwaysAutoResize/_WidthStretch). // This will hide the resizing option from the context menu. if (count_resizable == 0 && (table->Flags & ImGuiTableFlags_Resizable)) table->Flags &= ~ImGuiTableFlags_Resizable; @@ -828,15 +854,16 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Process interaction on resizing borders. Actual size change will be applied in EndTable() // - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise -// - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets overlapping the same area. +// - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets +// overlapping the same area. void ImGui::TableUpdateBorders(ImGuiTable* table) { ImGuiContext& g = *GImGui; IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable); - // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and use - // the final height from last frame. Because this is only affecting _interaction_ with columns, it is not really problematic. - // (whereas the actual visual will be displayed in EndTable() and using the current frame height) + // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and + // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not + // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). // Actual columns highlight/render will be performed in EndTable() and not be affected. const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersVFullHeight); const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS; @@ -895,8 +922,8 @@ void ImGui::EndTable() ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!"); - // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some cases, - // and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) + // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some + // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?"); // If the user never got to call TableNextRow() or TableNextCell(), we call layout ourselves to ensure all our @@ -942,7 +969,7 @@ void ImGui::EndTable() column->ContentWidthRowsFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsFrozen - ref_x_rows); column->ContentWidthRowsUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsUnfrozen - ref_x_rows); column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers); - column->ContentWidthHeadersDesired = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersDesired - ref_x_headers); + column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x_headers); if (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) max_pos_x = ImMax(max_pos_x, column->MaxX); @@ -1084,9 +1111,9 @@ void ImGui::TableDrawBorders(ImGuiTable* table) if (table->Flags & ImGuiTableFlags_BordersOuter) { // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call - // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their parent. - // In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part of it in inner window, - // and the part that's over scrollbars in the outer window..) + // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + // of it in inner window, and the part that's over scrollbars in the outer window..) // Either solution currently won't allow us to use a larger border size: the border would clipped. ImRect outer_border = table->OuterRect; const ImU32 outer_col = table->BorderColorStrong; @@ -1193,8 +1220,8 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed) { - // [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to - // ensure that our left border won't move, which we can do by making sure column_a/column_b resizes cancels each others. + // [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to ensure + // that our left border won't move, which we can do by making sure column_a/column_b resizes cancels each others. if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed)) if (table->LeftMostStretchedColumnDisplayOrder != -1 && table->LeftMostStretchedColumnDisplayOrder < column_0->DisplayOrder) { @@ -1240,12 +1267,15 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). // When the contents of a column didn't stray off its limit, we move its channels into the corresponding group // based on its position (within frozen rows/columns groups or not). -// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect, and they will be merged by the DrawSplitter.Merge() call. +// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect, and they will be +// merged by the DrawSplitter.Merge() call. // // Column channels will not be merged into one of the 1-4 groups in the following cases: // - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). -// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds matches, by e.g. calling SetCursorScreenPos(). -// - The channel uses more than one draw command itself. We drop all our merging stuff here.. we could do better but it's going to be rare. +// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds +// matches, by e.g. calling SetCursorScreenPos(). +// - The channel uses more than one draw command itself. We drop all our merging stuff here.. we could do better +// but it's going to be rare. // // This function is particularly tricky to understand.. take a breath. void ImGui::TableDrawMergeChannels(ImGuiTable* table) @@ -1308,13 +1338,13 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect); merge_group_mask |= (1 << merge_group_dst_n); - // If we end with a single group and hosted by the outer window, we'll attempt to merge our draw command with - // the existing outer window command. But we can only do so if our columns all fit within the expected clip rect, - // otherwise clipping will be incorrect when ScrollX is disabled. + // If we end with a single group and hosted by the outer window, we'll attempt to merge our draw command + // with the existing outer window command. But we can only do so if our columns all fit within the expected + // clip rect, otherwise clipping will be incorrect when ScrollX is disabled. // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column don't fit within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect - // 2019/10/22: (1) This is breaking table_2_draw_calls but I cannot seem to repro what it is attempting to fix... - // cf git fce2e8dc "Fixed issue with clipping when outerwindow==innerwindow / support ScrollH without ScrollV." + // 2019/10/22: (1) This is breaking table_2_draw_calls but I cannot seem to repro what it is attempting to + // fix... cf git fce2e8dc "Fixed issue with clipping when outerwindow==innerwindow / support ScrollH without ScrollV." // 2019/10/22: (2) Clamping code in TableUpdateLayout() seemingly made this not necessary... #if 0 if (column->MinX < table->InnerClipRect.Min.x || column->MaxX > table->InnerClipRect.Max.x) @@ -1322,7 +1352,8 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) #endif } - // Invalidate current draw channel (we don't clear DrawChannelBeforeRowFreeze/DrawChannelAfterRowFreeze solely to facilitate debugging) + // Invalidate current draw channel + // (we don't clear DrawChannelBeforeRowFreeze/DrawChannelAfterRowFreeze solely to facilitate debugging) column->DrawChannelCurrent = -1; } @@ -1402,8 +1433,9 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; table->DeclColumnsCount++; - // When passing a width automatically enforce WidthFixed policy (vs TableFixColumnFlags would default to WidthAlwaysAutoResize) - // (we write down to FlagsIn which is a little misleading, another solution would be to pass init_width_or_weight to TableFixColumnFlags) + // When passing a width automatically enforce WidthFixed policy + // (vs TableFixColumnFlags would default to WidthAlwaysAutoResize) + // (we write to FlagsIn which is a little misleading, another solution would be to pass init_width_or_weight to TableFixColumnFlags) if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0) if ((table->Flags & ImGuiTableFlags_SizingPolicyFixedX) && (init_width_or_weight > 0.0f)) flags |= ImGuiTableColumnFlags_WidthFixed; @@ -1521,8 +1553,8 @@ void ImGui::TableEndRow(ImGuiTable* table) TableEndCell(table); - // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. - // However it is likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. + // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is + // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. window->DC.CursorPos.y = table->RowPosY2; // Row background fill @@ -1588,7 +1620,8 @@ void ImGui::TableEndRow(ImGuiTable* table) window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong); // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) - // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and get the new cursor position. + // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and + // get the new cursor position. if (unfreeze_rows) { IM_ASSERT(table->IsFreezeRowsPassed == false); @@ -1767,16 +1800,16 @@ ImRect ImGui::TableGetCellRect() return ImRect(column->MinX, table->RowPosY1, column->MaxX, table->RowPosY2); } -const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_n) +const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n) { - ImGuiTableColumn* column = &table->Columns[column_n]; + const ImGuiTableColumn* column = &table->Columns[column_n]; if (column->NameOffset == -1) return NULL; return &table->ColumnsNames.Buf[column->NameOffset]; } // Return the resizing ID for the right-side of the given column. -ImGuiID ImGui::TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no) +ImGuiID ImGui::TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no) { IM_ASSERT(column_n < table->ColumnsCount); ImGuiID id = table->ID + (instance_no * table->ColumnsCount) + column_n; @@ -1880,8 +1913,8 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) } // This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). -// The intent is that advanced users willing to create customized headers would not need to use this helper and may create their own. -// However presently this function uses too many internal structures/calls. +// The intent is that advanced users willing to create customized headers would not need to use this helper and may +// create their own. However presently this function uses too many internal structures/calls. void ImGui::TableAutoHeaders() { ImGuiContext& g = *GImGui; @@ -1964,7 +1997,7 @@ void ImGui::TableAutoHeaders() window->DC.CursorPos.y -= g.Style.ItemSpacing.y; window->DC.CursorMaxPos = backup_cursor_max_pos; // Don't feed back into the width of the Header row - // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden + // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden. if (IsMouseReleased(1) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) open_context_popup = -1; } @@ -2024,7 +2057,8 @@ void ImGui::TableHeader(const char* label) // FIXME-TABLE: Fix when padding are disabled. //window->DC.CursorPos.x = column->MinX + table->CellPadding.x; - // Keep header highlighted when context menu is open. (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) + // Keep header highlighted when context menu is open. + // (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent); const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld | ImGuiSelectableFlags_DontClosePopups, ImVec2(0.0f, label_height)); const bool held = IsItemActive(); @@ -2091,16 +2125,17 @@ void ImGui::TableHeader(const char* label) TableSortSpecsClickColumn(table, column, g.IO.KeyShift); } - // Render clipped label - // Clipping here ensure that in the majority of situations, all our header cells will be merged into a single draw call. + // 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); - // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging. + // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering + // for merging. // FIXME-TABLE: Clarify policies of how label width and potential decorations (arrows) fit into auto-resize of the column float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow; column->ContentMaxPosHeadersUsed = ImMax(column->ContentMaxPosHeadersUsed, work_r.Max.x);// ImMin(max_pos_x, work_r.Max.x)); - column->ContentMaxPosHeadersDesired = ImMax(column->ContentMaxPosHeadersDesired, max_pos_x); + column->ContentMaxPosHeadersIdeal = ImMax(column->ContentMaxPosHeadersIdeal, max_pos_x); PopID(); } @@ -2144,7 +2179,8 @@ void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* click } // Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set) -// You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since last call, or the first time. +// You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since +// last call, or the first time. // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() { @@ -2292,7 +2328,7 @@ static ImGuiTableSettings* FindTableSettingsByID(ImGuiID id) return NULL; } -ImGuiTableSettings* ImGui::TableFindSettings(ImGuiTable* table) +ImGuiTableSettings* ImGui::TableFindSettings(const ImGuiTable* table) { if (table->SettingsOffset == -1) return NULL; @@ -2438,7 +2474,8 @@ void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHan if (settings->ID == 0) // Skip ditched settings continue; - // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped (e.g. Order was unchanged) + // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped + // (e.g. Order was unchanged) const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0; const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0; const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0; @@ -2473,6 +2510,7 @@ void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHan //------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_METRICS_WINDOW + void ImGui::DebugNodeTable(ImGuiTable* table) { char buf[256]; @@ -2482,33 +2520,33 @@ void ImGui::DebugNodeTable(ImGuiTable* table) bool open = TreeNode(table, "%s", buf); if (IsItemHovered()) GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); - if (open) - { - for (int n = 0; n < table->ColumnsCount; n++) - { - ImGuiTableColumn* column = &table->Columns[n]; - const char* name = TableGetColumnName(table, n); - BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" - "Active: %d, Clipped: %d, DrawChannels: %d,%d\n" - "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" - "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Desired %d/%d\n" - "SortOrder: %d, SortDir: %s\n" - "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", - n, column->DisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, - column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, - column->WidthGiven, column->WidthRequested, column->ResizeWeight, - column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersDesired, - column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? "Ascending" : (column->SortDirection == ImGuiSortDirection_Descending) ? "Descending" : "None", - column->UserID, column->Flags, - (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", - (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "", - (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) ? "WidthAlwaysAutoResize " : "", - (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : ""); - } - if (ImGuiTableSettings* settings = TableFindSettings(table)) - DebugNodeTableSettings(settings); - TreePop(); - } + if (!open) + return; + BulletText("OuterWidth: %.1f, InnerWidth: %.1f%s, IdealWidth: %.1f", table->OuterRect.GetWidth(), table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "", table->IdealTotalWidth); + for (int n = 0; n < table->ColumnsCount; n++) + { + ImGuiTableColumn* column = &table->Columns[n]; + const char* name = TableGetColumnName(table, n); + BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" + "Active: %d, Clipped: %d, DrawChannels: %d,%d\n" + "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" + "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Ideal %d/%d\n" + "SortOrder: %d, SortDir: %s\n" + "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", + n, column->DisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, + column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, + column->WidthGiven, column->WidthRequested, column->ResizeWeight, + column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersIdeal, + column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? "Ascending" : (column->SortDirection == ImGuiSortDirection_Descending) ? "Descending" : "None", + column->UserID, column->Flags, + (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "", + (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "", + (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) ? "WidthAlwaysAutoResize " : "", + (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : ""); + } + if (ImGuiTableSettings* settings = TableFindSettings(table)) + DebugNodeTableSettings(settings); + TreePop(); } void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings) From 9b6d0fdb7a04b80436b4749801a002f4c57f811e Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 May 2020 13:30:41 +0200 Subject: [PATCH 424/959] Tables: Fixed ignoring DefaultHide or DefaultSort data from flags when loading settings that don't have them. --- imgui_internal.h | 5 ++--- imgui_tables.cpp | 15 +++++++-------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index c77d3081..03ad431b 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1952,7 +1952,7 @@ struct ImGuiTable ImU64 ActiveMaskByIndex; // Column Index -> IsActive map (Active == not hidden by user/api) in a format adequate for iterating column without touching cold data ImU64 ActiveMaskByDisplayOrder; // Column DisplayOrder -> IsActive map ImU64 VisibleMaskByIndex; // Visible (== Active and not Clipped) - ImGuiTableFlags SettingsSaveFlags; // Pre-compute which data we are going to save into the .ini file (e.g. when order is not altered we won't save order) + ImGuiTableFlags SettingsLoadedFlags; // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order) int SettingsOffset; // Offset in g.SettingsTables int LastFrameActive; int ColumnsCount; // Number of columns declared in BeginTable() @@ -2022,7 +2022,6 @@ struct ImGuiTable 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 IsSettingsRequestLoad; - bool IsSettingsLoaded; 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) bool IsResetDisplayOrderRequest; @@ -2050,7 +2049,7 @@ struct ImGuiTableColumnSettings ImS8 DisplayOrder; ImS8 SortOrder; ImS8 SortDirection : 7; - ImU8 Visible : 1; // This is called Active in ImGuiTableColumn, in .ini file we call it Visible. + ImU8 Visible : 1; // This is called Active in ImGuiTableColumn, but in user-facing code we call this Visible (thus in .ini file) ImGuiTableColumnSettings() { diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ae209ec5..80c1f89b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1466,12 +1466,12 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, column->ResizeWeight = 1.0f; } } - if (table->IsInitializing && !table->IsSettingsLoaded) + if (table->IsInitializing) { // Init default visibility/sort state - if (flags & ImGuiTableColumnFlags_DefaultHide) + if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0) column->IsActive = column->IsActiveNextFrame = false; - if (flags & ImGuiTableColumnFlags_DefaultSort) + if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0) { column->SortOrder = 0; // Multiple columns using _DefaultSort will be reordered when building the sort specs. column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); @@ -2360,7 +2360,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) } settings->ColumnsCount = (ImS8)table->ColumnsCount; - // Serialize ImGuiTableSettings/ImGuiTableColumnSettings --> ImGuiTable/ImGuiTableColumn + // Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings IM_ASSERT(settings->ID == table->ID); IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount); ImGuiTableColumn* column = table->Columns.Data; @@ -2378,7 +2378,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) column_settings->Visible = column->IsActive; // We skip saving some data in the .ini file when they are unnecessary to restore our state - // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet. + // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved. if (column->DisplayOrder != n) settings->SaveFlags |= ImGuiTableFlags_Reorderable; if (column_settings->SortOrder != -1) @@ -2411,10 +2411,9 @@ void ImGui::TableLoadSettings(ImGuiTable* table) { settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); } - table->IsSettingsLoaded = true; - settings->SaveFlags = table->Flags; + table->SettingsLoadedFlags = settings->SaveFlags; - // Serialize ImGuiTable/ImGuiTableColumn --> ImGuiTableSettings/ImGuiTableColumnSettings + // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++) { From 95c273618eb81a5e16a0b726d6b7846460b63ccd Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 May 2020 20:24:37 +0200 Subject: [PATCH 425/959] Tables: Allow hot-reload of settings (merge policy), tidying up settings code --- imgui.cpp | 10 +--- imgui_internal.h | 11 ++--- imgui_tables.cpp | 118 +++++++++++++++++++++++++++++++++-------------- 3 files changed, 90 insertions(+), 49 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 55c67bbb..7ad7a547 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3970,15 +3970,7 @@ void ImGui::Initialize(ImGuiContext* context) #ifdef IMGUI_HAS_TABLE // Add .ini handle for ImGuiTable type - { - ImGuiSettingsHandler ini_handler; - ini_handler.TypeName = "Table"; - ini_handler.TypeHash = ImHashStr("Table"); - ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen; - ini_handler.ReadLineFn = TableSettingsHandler_ReadLine; - ini_handler.WriteAllFn = TableSettingsHandler_WriteAll; - g.SettingsHandlers.push_back(ini_handler); - } + TableInstallSettingsHandler(context); #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK diff --git a/imgui_internal.h b/imgui_internal.h index 03ad431b..bd29e343 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2066,9 +2066,10 @@ struct ImGuiTableColumnSettings struct ImGuiTableSettings { ImGuiID ID; // Set to 0 to invalidate/delete the setting - ImGuiTableFlags SaveFlags; + ImGuiTableFlags SaveFlags; // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..) ImS8 ColumnsCount; - ImS8 ColumnsCountMax; + ImS8 ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher + bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) ImGuiTableSettings() { memset(this, 0, sizeof(*this)); } ImGuiTableColumnSettings* GetColumnSettings() { return (ImGuiTableColumnSettings*)(this + 1); } @@ -2271,10 +2272,8 @@ namespace ImGui IMGUI_API void PopTableBackground(); IMGUI_API void TableLoadSettings(ImGuiTable* table); IMGUI_API void TableSaveSettings(ImGuiTable* table); - IMGUI_API ImGuiTableSettings* TableFindSettings(const ImGuiTable* table); - IMGUI_API void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); - IMGUI_API void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); - IMGUI_API void TableSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); + IMGUI_API ImGuiTableSettings* TableGetBoundSettings(const ImGuiTable* table); + IMGUI_API void TableInstallSettingsHandler(ImGuiContext* context); // Tab Bars IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 80c1f89b..b585f114 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2305,19 +2305,28 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) // [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file. //------------------------------------------------------------------------- -static ImGuiTableSettings* CreateTableSettings(ImGuiID id, int columns_count) +// Clear and initialize empty settings instance +static void InitTableSettings(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max) { - ImGuiContext& g = *GImGui; - ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings)); IM_PLACEMENT_NEW(settings) ImGuiTableSettings(); ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings(); - for (int n = 0; n < columns_count; n++, settings_column++) + for (int n = 0; n < columns_count_max; n++, settings_column++) IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings(); settings->ID = id; - settings->ColumnsCount = settings->ColumnsCountMax = (ImS8)columns_count; + settings->ColumnsCount = (ImS8)columns_count; + settings->ColumnsCountMax = (ImS8)columns_count_max; + settings->WantApply = true; +} + +static ImGuiTableSettings* CreateTableSettings(ImGuiID id, int columns_count) +{ + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings)); + InitTableSettings(settings, id, columns_count, columns_count); return settings; } +// Find existing settings static ImGuiTableSettings* FindTableSettingsByID(ImGuiID id) { // FIXME-OPT: Might want to store a lookup map for this? @@ -2328,20 +2337,19 @@ static ImGuiTableSettings* FindTableSettingsByID(ImGuiID id) return NULL; } -ImGuiTableSettings* ImGui::TableFindSettings(const ImGuiTable* table) +// Get settings for a given table, NULL if none +ImGuiTableSettings* ImGui::TableGetBoundSettings(const ImGuiTable* table) { - if (table->SettingsOffset == -1) - return NULL; - - ImGuiContext& g = *GImGui; - ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); - IM_ASSERT(settings->ID == table->ID); - if (settings->ColumnsCountMax < table->ColumnsCount) + if (table->SettingsOffset != -1) { - settings->ID = 0; // Ditch storage if we won't fit because of a count change - return NULL; + ImGuiContext& g = *GImGui; + ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); + IM_ASSERT(settings->ID == table->ID); + if (settings->ColumnsCountMax >= table->ColumnsCount) + return settings; // OK + settings->ID = 0; // Invalidate storage, we won't fit because of a count change } - return settings; + return NULL; } void ImGui::TableSaveSettings(ImGuiTable* table) @@ -2352,7 +2360,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) // Bind or create settings data ImGuiContext& g = *GImGui; - ImGuiTableSettings* settings = TableFindSettings(table); + ImGuiTableSettings* settings = TableGetBoundSettings(table); if (settings == NULL) { settings = CreateTableSettings(table->ID, table->ColumnsCount); @@ -2370,7 +2378,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) settings->SaveFlags = ImGuiTableFlags_Resizable; for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++) { - //column_settings->WidthOrWeight = column->WidthRequested; // FIXME-WIP + //column_settings->WidthOrWeight = column->WidthRequested; // FIXME-TABLE: Missing column_settings->Index = (ImS8)n; column_settings->DisplayOrder = column->DisplayOrder; column_settings->SortOrder = column->SortOrder; @@ -2378,7 +2386,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) column_settings->Visible = column->IsActive; // We skip saving some data in the .ini file when they are unnecessary to restore our state - // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved. + // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. if (column->DisplayOrder != n) settings->SaveFlags |= ImGuiTableFlags_Reorderable; if (column_settings->SortOrder != -1) @@ -2409,9 +2417,10 @@ void ImGui::TableLoadSettings(ImGuiTable* table) } else { - settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset); + settings = TableGetBoundSettings(table); } table->SettingsLoadedFlags = settings->SaveFlags; + IM_ASSERT(settings->ColumnsCount == table->ColumnsCount); // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); @@ -2422,14 +2431,13 @@ void ImGui::TableLoadSettings(ImGuiTable* table) continue; ImGuiTableColumn* column = &table->Columns[column_n]; //column->WidthRequested = column_settings->WidthOrWeight; // FIXME-WIP - if (column_settings->DisplayOrder != -1) + if (settings->SaveFlags & ImGuiTableFlags_Reorderable) column->DisplayOrder = column_settings->DisplayOrder; - if (column_settings->SortOrder != -1) - { - column->SortOrder = column_settings->SortOrder; - column->SortDirection = column_settings->SortDirection; - } + else + column->DisplayOrder = (ImS8)column_n; column->IsActive = column->IsActiveNextFrame = column_settings->Visible; + column->SortOrder = column_settings->SortOrder; + column->SortDirection = column_settings->SortDirection; } // FIXME-TABLE: Need to validate .ini data @@ -2437,16 +2445,46 @@ void ImGui::TableLoadSettings(ImGuiTable* table) table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImS8)column_n; } -void* ImGui::TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) +static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Tables.GetSize(); i++) + g.Tables.GetByIndex(i)->SettingsOffset = -1; + g.SettingsTables.clear(); +} + +// Apply to existing windows (if any) +static void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) +{ + ImGuiContext& g = *ctx; + for (int i = 0; i != g.Tables.GetSize(); i++) + { + ImGuiTable* table = g.Tables.GetByIndex(i); + table->IsSettingsRequestLoad = true; + table->SettingsOffset = -1; + } +} + +static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { ImGuiID id = 0; int columns_count = 0; if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2) return NULL; + + if (ImGuiTableSettings* settings = FindTableSettingsByID(id)) + { + if (settings->ColumnsCountMax >= columns_count) + { + InitTableSettings(settings, id, columns_count, settings->ColumnsCountMax); // Recycle + return settings; + } + settings->ID = 0; // Invalidate storage if we won't fit because of a count change + } return CreateTableSettings(id, columns_count); } -void ImGui::TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) +static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) { // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" ImGuiTableSettings* settings = (ImGuiTableSettings*)entry; @@ -2465,7 +2503,7 @@ void ImGui::TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImS8)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } } -void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) +static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { ImGuiContext& g = *ctx; for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) @@ -2488,10 +2526,8 @@ void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHan for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++) { // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" - if (column->UserID != 0) - buf->appendf("Column %-2d UserID=%08X", column_n, column->UserID); - else - buf->appendf("Column %-2d", column_n); + buf->appendf("Column %-2d", column_n); + if (column->UserID != 0) buf->appendf(" UserID=%08X", column->UserID); if (save_size) buf->appendf(" Width=%d", 0);// (int)settings_column->WidthOrWeight); // FIXME-TABLE if (save_visible) buf->appendf(" Visible=%d", column->Visible); if (save_order) buf->appendf(" Order=%d", column->DisplayOrder); @@ -2502,6 +2538,20 @@ void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHan } } +void ImGui::TableInstallSettingsHandler(ImGuiContext* context) +{ + ImGuiContext& g = *context; + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "Table"; + ini_handler.TypeHash = ImHashStr("Table"); + ini_handler.ClearAllFn = TableSettingsHandler_ClearAll; + ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen; + ini_handler.ReadLineFn = TableSettingsHandler_ReadLine; + ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll; + ini_handler.WriteAllFn = TableSettingsHandler_WriteAll; + g.SettingsHandlers.push_back(ini_handler); +} + //------------------------------------------------------------------------- // TABLE - Debugging //------------------------------------------------------------------------- @@ -2543,7 +2593,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) ? "WidthAlwaysAutoResize " : "", (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : ""); } - if (ImGuiTableSettings* settings = TableFindSettings(table)) + if (ImGuiTableSettings* settings = TableGetBoundSettings(table)) DebugNodeTableSettings(settings); TreePop(); } From 466b6e619a1a4fe764e84f2c9131a13eaa2e3f0a Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 May 2020 22:24:20 +0200 Subject: [PATCH 426/959] Tables: Fixed incorrect application of CursorMaxPos.x (3162) --- imgui_tables.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b585f114..b6a526e8 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -971,12 +971,12 @@ void ImGui::EndTable() column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers); column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x_headers); + // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. if (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) - max_pos_x = ImMax(max_pos_x, column->MaxX); + max_pos_x = ImMax(max_pos_x, column->MaxX + 1.0f); } - // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. - inner_window->DC.CursorMaxPos.x = max_pos_x + 1; + inner_window->DC.CursorMaxPos.x = max_pos_x; if (!(flags & ImGuiTableFlags_NoClipX)) inner_window->DrawList->PopClipRect(); From dff26191bd8dd7b6f8061b025322bc0e5e76d769 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 13 May 2020 23:42:22 +0200 Subject: [PATCH 427/959] Tables: Try to report contents width to outer window, generally better auto-fit. --- imgui_demo.cpp | 18 ++++++++++++ imgui_internal.h | 4 +-- imgui_tables.cpp | 71 +++++++++++++++++++++++++++++------------------- 3 files changed, 63 insertions(+), 30 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 15876be7..b91ec0ab 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3570,6 +3570,24 @@ static void ShowDemoWindowTables() } ImGui::EndTable(); } + + if (ImGui::BeginTable("##table2", 3, flags | ImGuiTableFlags_SizingPolicyFixedX)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableAutoHeaders(); + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Fixed %d,%d", row, column); + } + } + ImGui::EndTable(); + } ImGui::TreePop(); } diff --git a/imgui_internal.h b/imgui_internal.h index bd29e343..1d5b7020 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1981,9 +1981,9 @@ struct ImGuiTable float CellSpacingX; // Spacing between non-bordered cells float LastOuterHeight; // Outer height from last frame float LastFirstRowHeight; // Height of first row from last frame - float ColumnsTotalWidth; float InnerWidth; // User value passed to BeginTable(), see comments at the top of BeginTable() for details. - float IdealTotalWidth; // Sum of ideal column width for nothing to be clipped + float ColumnsTotalWidth; // Sum of current column width + float ColumnsAutoFitWidth; // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window float ResizedColumnNextWidth; ImRect OuterRect; // Note: OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). ImRect WorkRect; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b6a526e8..29b1c9b1 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -558,13 +558,14 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // (can't make auto padding larger than what WorkRect knows about so right-alignment matches) const ImRect work_rect = table->WorkRect; const float padding_auto_x = table->CellPaddingX2; + const float spacing_auto_x = table->CellSpacingX * (1.0f + 2.0f); // CellSpacingX is >0.0f when there's no vertical border, in which case we add two extra CellSpacingX to make auto-fit look nice instead of cramped. We may want to expose this somehow. const float min_column_width = TableGetMinColumnWidth(); int count_fixed = 0; float width_fixed = 0.0f; float total_weights = 0.0f; table->LeftMostStretchedColumnDisplayOrder = -1; - table->IdealTotalWidth = 0.0f; + table->ColumnsAutoFitWidth = 0.0f; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) @@ -591,7 +592,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (!(table->Flags & ImGuiTableFlags_NoHeadersWidth) && !(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth)) column_width_ideal = ImMax(column_width_ideal, column_content_width_headers); column_width_ideal = ImMax(column_width_ideal + padding_auto_x, min_column_width); - table->IdealTotalWidth += column_width_ideal; + table->ColumnsAutoFitWidth += column_width_ideal; if (column->Flags & (ImGuiTableColumnFlags_WidthAlwaysAutoResize | ImGuiTableColumnFlags_WidthFixed)) { @@ -623,6 +624,10 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } } + // CellSpacingX is >0.0f when there's no vertical border, in which case we add two extra CellSpacingX to make auto-fit look nice instead of cramped. + // We may want to expose this somehow. + table->ColumnsAutoFitWidth += spacing_auto_x * (table->ColumnsActiveCount - 1); + // Layout // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible const float width_spacings = table->CellSpacingX * (table->ColumnsActiveCount - 1); @@ -956,28 +961,6 @@ void ImGui::EndTable() table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y); table->LastOuterHeight = table->OuterRect.GetHeight(); - // Store content width reference for each column - float max_pos_x = inner_window->DC.CursorMaxPos.x; - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - { - ImGuiTableColumn* column = &table->Columns[column_n]; - - // Store content width (for both Headers and Rows) - //float ref_x = column->MinX; - float ref_x_rows = column->StartXRows - table->CellPaddingX1; - float ref_x_headers = column->StartXHeaders - table->CellPaddingX1; - column->ContentWidthRowsFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsFrozen - ref_x_rows); - column->ContentWidthRowsUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsUnfrozen - ref_x_rows); - column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers); - column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x_headers); - - // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. - if (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) - max_pos_x = ImMax(max_pos_x, column->MaxX + 1.0f); - } - - inner_window->DC.CursorMaxPos.x = max_pos_x; - if (!(flags & ImGuiTableFlags_NoClipX)) inner_window->DrawList->PopClipRect(); inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back(); @@ -1015,16 +998,16 @@ void ImGui::EndTable() } // Layout in outer window + const float backup_outer_cursor_pos_x = outer_window->DC.CursorPos.x; + const float backup_outer_max_pos_x = outer_window->DC.CursorMaxPos.x; + const float backup_inner_max_pos_x = inner_window->DC.CursorMaxPos.x; inner_window->WorkRect = table->HostWorkRect; inner_window->SkipItems = table->HostSkipItems; outer_window->DC.CursorPos = table->OuterRect.Min; outer_window->DC.ColumnsOffset.x = 0.0f; if (inner_window != outer_window) { - // Override EndChild's ItemSize with our own to enable auto-resize on the X axis when possible - float backup_outer_cursor_pos_x = outer_window->DC.CursorPos.x; EndChild(); - outer_window->DC.CursorMaxPos.x = backup_outer_cursor_pos_x + table->ColumnsTotalWidth + 1.0f + inner_window->ScrollbarSizes.x; } else { @@ -1034,6 +1017,38 @@ void ImGui::EndTable() ItemSize(item_size); } + // Store content width reference for each column + float max_pos_x = backup_inner_max_pos_x; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Store content width (for both Headers and Rows) + //float ref_x = column->MinX; + float ref_x_rows = column->StartXRows - table->CellPaddingX1; + float ref_x_headers = column->StartXHeaders - table->CellPaddingX1; + column->ContentWidthRowsFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsFrozen - ref_x_rows); + column->ContentWidthRowsUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsUnfrozen - ref_x_rows); + column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers); + column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x_headers); + + // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. + if (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) + max_pos_x = ImMax(max_pos_x, column->MaxX + 1.0f); + } + + // Override EndChild/ItemSize max extent with our own to enable auto-resize on the X axis when possible + // FIXME-TABLE: This can be improved (e.g. for Fixed columns we don't want to auto AutoFitWidth? or propagate window auto-fit to table?) + if (table->Flags & ImGuiTableFlags_ScrollX) + { + inner_window->DC.CursorMaxPos.x = max_pos_x; // Set contents width for scrolling + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos_x, backup_outer_cursor_pos_x + table->ColumnsTotalWidth + 1.0f + inner_window->ScrollbarSizes.x); // For auto-fit + } + else + { + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos_x, table->WorkRect.Min.x + table->ColumnsAutoFitWidth); // For auto-fit + } + // Save settings if (table->IsSettingsDirty) TableSaveSettings(table); @@ -2571,7 +2586,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); if (!open) return; - BulletText("OuterWidth: %.1f, InnerWidth: %.1f%s, IdealWidth: %.1f", table->OuterRect.GetWidth(), table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "", table->IdealTotalWidth); + BulletText("OuterWidth: %.1f, InnerWidth: %.1f%s, ColumnsWidth: %.1f, AutoFitWidth: %.1f", table->OuterRect.GetWidth(), table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "", table->ColumnsTotalWidth, table->ColumnsAutoFitWidth); for (int n = 0; n < table->ColumnsCount; n++) { ImGuiTableColumn* column = &table->Columns[n]; From 23c60b2814da9a4fb2b4b7ff1bcbcd5704256c67 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 14 May 2020 17:57:25 +0200 Subject: [PATCH 428/959] Tables: Renamed internal fields: Active->Visible, Visible->VisibleUnclipped to be less misleading. --- imgui.h | 2 +- imgui_internal.h | 32 ++++----- imgui_tables.cpp | 165 ++++++++++++++++++++++++----------------------- 3 files changed, 100 insertions(+), 99 deletions(-) diff --git a/imgui.h b/imgui.h index f559da62..122facf4 100644 --- a/imgui.h +++ b/imgui.h @@ -687,7 +687,7 @@ namespace ImGui // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. // - The name passed to TableSetupColumn() is used by TableAutoHeaders() and by the context-menu // - Use TableAutoHeaders() to submit the whole header row, otherwise you may treat the header row as a regular row, manually call TableHeader() and other widgets. - // - Headers are required to perform some interactions: reordering, sorting, context menu // FIXME-TABLE: remove context from this list! + // - Headers are required to perform some interactions: reordering, sorting, context menu (FIXME-TABLE: context menu should work without!) IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = -1.0f, ImU32 user_id = 0); IMGUI_API void TableAutoHeaders(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu IMGUI_API void TableHeader(const char* label); // submit one header cell manually. diff --git a/imgui_internal.h b/imgui_internal.h index 1d5b7020..d8d05245 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1888,7 +1888,7 @@ struct ImGuiTabBar #define IMGUI_TABLE_MAX_DRAW_CHANNELS (2 + 64 * 2) // See TableUpdateDrawChannels() // [Internal] sizeof() ~ 100 -// We use the terminology "Active" to refer to a column that is not Hidden by user or programmatically. We don't use the term "Visible" because it is ambiguous since an Active column can be non-visible because of scrolling. +// We use the terminology "Visible" to refer to a column that is not Hidden by user or settings. However it may still be out of view and clipped (see IsClipped). struct ImGuiTableColumn { ImRect ClipRect; // Clipping rectangle for the column @@ -1911,17 +1911,17 @@ struct ImGuiTableColumn ImS16 ContentWidthHeadersUsed; // TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls ImS16 ContentWidthHeadersIdeal; ImS16 NameOffset; // Offset into parent ColumnsNames[] - bool IsActive; // Is the column not marked Hidden by the user (regardless of clipping). We're not calling this "Visible" here because visibility also depends on clipping. - bool IsActiveNextFrame; - bool IsClipped; // Set when not overlapping the host window clipping rectangle. We don't use the opposite "!Visible" name because Clipped can be altered by events. + bool IsVisible; // Is the column not marked Hidden by the user? (could be clipped by scrolling, etc). + bool IsVisibleNextFrame; + bool IsClipped; // Set when not overlapping the host window clipping rectangle. bool SkipItems; ImS8 DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) - ImS8 IndexWithinActiveSet; // Index within active/visible set (<= IndexToDisplayOrder) + ImS8 IndexWithinVisibleSet; // Index within visible set (<= IndexToDisplayOrder) ImS8 DrawChannelCurrent; // Index within DrawSplitter.Channels[] ImS8 DrawChannelRowsBeforeFreeze; ImS8 DrawChannelRowsAfterFreeze; - ImS8 PrevActiveColumn; // Index of prev active column within Columns[], -1 if first active column - ImS8 NextActiveColumn; // Index of next active column within Columns[], -1 if last active column + ImS8 PrevVisibleColumn; // Index of prev visible column within Columns[], -1 if first visible column + ImS8 NextVisibleColumn; // Index of next visible column within Columns[], -1 if last visible column ImS8 AutoFitQueue; // Queue of 8 values for the next 8 frames to request auto-fit ImS8 CannotSkipItemsQueue; // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem ImS8 SortOrder; // -1: Not sorting on this column @@ -1932,10 +1932,10 @@ struct ImGuiTableColumn memset(this, 0, sizeof(*this)); ResizeWeight = WidthRequested = WidthGiven = -1.0f; NameOffset = -1; - IsActive = IsActiveNextFrame = true; - DisplayOrder = IndexWithinActiveSet = -1; + IsVisible = IsVisibleNextFrame = true; + DisplayOrder = IndexWithinVisibleSet = -1; DrawChannelCurrent = DrawChannelRowsBeforeFreeze = DrawChannelRowsAfterFreeze = -1; - PrevActiveColumn = NextActiveColumn = -1; + PrevVisibleColumn = NextVisibleColumn = -1; AutoFitQueue = CannotSkipItemsQueue = (1 << 3) - 1; // Skip for three frames SortOrder = -1; SortDirection = ImGuiSortDirection_Ascending; @@ -1949,14 +1949,14 @@ struct ImGuiTable ImVector RawData; ImSpan Columns; // Point within RawData[] ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) - ImU64 ActiveMaskByIndex; // Column Index -> IsActive map (Active == not hidden by user/api) in a format adequate for iterating column without touching cold data - ImU64 ActiveMaskByDisplayOrder; // Column DisplayOrder -> IsActive map - ImU64 VisibleMaskByIndex; // Visible (== Active and not Clipped) + ImU64 VisibleMaskByIndex; // Column Index -> IsVisible map (== not hidden by user/api) in a format adequate for iterating column without touching cold data + ImU64 VisibleMaskByDisplayOrder; // Column DisplayOrder -> IsVisible map + ImU64 VisibleUnclippedMaskByIndex;// Visible and not Clipped, aka "actually visible" "not hidden by some scrolling" ImGuiTableFlags SettingsLoadedFlags; // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order) int SettingsOffset; // Offset in g.SettingsTables int LastFrameActive; int ColumnsCount; // Number of columns declared in BeginTable() - int ColumnsActiveCount; // Number of non-hidden columns (<= ColumnsCount) + int ColumnsVisibleCount; // Number of non-hidden columns (<= ColumnsCount) int CurrentColumn; int CurrentRow; ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple table with same ID look are multiple tables, they are just synched. @@ -2007,7 +2007,7 @@ struct ImGuiTable ImS8 HeldHeaderColumn; // Index of column header being held. ImS8 ReorderColumn; // Index of column being reordered. (not cleared) ImS8 ReorderColumnDir; // -1 or +1 - ImS8 RightMostActiveColumn; // Index of right-most non-hidden column. + ImS8 RightMostVisibleColumn; // Index of right-most non-hidden column. ImS8 LeftMostStretchedColumnDisplayOrder; // Display order of left-most stretched column. ImS8 ContextPopupColumn; // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot ImS8 DummyDrawChannel; // Redirect non-visible columns here. @@ -2049,7 +2049,7 @@ struct ImGuiTableColumnSettings ImS8 DisplayOrder; ImS8 SortOrder; ImS8 SortDirection : 7; - ImU8 Visible : 1; // This is called Active in ImGuiTableColumn, but in user-facing code we call this Visible (thus in .ini file) + ImU8 Visible : 1; ImGuiTableColumnSettings() { diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 29b1c9b1..cec4ebb0 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -286,7 +286,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->DeclColumnsCount = 0; table->HoveredColumnBody = -1; table->HoveredColumnBorder = -1; - table->RightMostActiveColumn = -1; + table->RightMostVisibleColumn = -1; // Using opaque colors facilitate overlapping elements of the grid table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong); @@ -333,7 +333,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. inner_window->SkipItems = true; - // Update/lock which columns will be Active for the frame + // Update/lock which columns will be Visible for the frame TableBeginUpdateColumns(table); return true; @@ -371,7 +371,7 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) IM_ASSERT(reorder_dir == -1 || reorder_dir == +1); IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable); ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn]; - ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevActiveColumn : src_column->NextActiveColumn]; + ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevVisibleColumn : src_column->NextVisibleColumn]; IM_UNUSED(dst_column); const int src_order = src_column->DisplayOrder; const int dst_order = dst_column->DisplayOrder; @@ -398,10 +398,10 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) table->IsSettingsDirty = true; } - // Setup and lock Active state and order - table->ColumnsActiveCount = 0; + // Setup and lock Visible state and order + table->ColumnsVisibleCount = 0; table->IsDefaultDisplayOrder = true; - ImGuiTableColumn* last_active_column = NULL; + ImGuiTableColumn* last_visible_column = NULL; bool want_column_auto_fit = false; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { @@ -411,12 +411,12 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; column->NameOffset = -1; if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide)) - column->IsActiveNextFrame = true; - if (column->IsActive != column->IsActiveNextFrame) + column->IsVisibleNextFrame = true; + if (column->IsVisible != column->IsVisibleNextFrame) { - column->IsActive = column->IsActiveNextFrame; + column->IsVisible = column->IsVisibleNextFrame; table->IsSettingsDirty = true; - if (!column->IsActive && column->SortOrder != -1) + if (!column->IsVisible && column->SortOrder != -1) table->IsSortSpecsDirty = true; } if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_MultiSortable)) @@ -426,30 +426,30 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) ImU64 index_mask = (ImU64)1 << column_n; ImU64 display_order_mask = (ImU64)1 << column->DisplayOrder; - if (column->IsActive) + if (column->IsVisible) { - column->PrevActiveColumn = column->NextActiveColumn = -1; - if (last_active_column) + column->PrevVisibleColumn = column->NextVisibleColumn = -1; + if (last_visible_column) { - last_active_column->NextActiveColumn = (ImS8)column_n; - column->PrevActiveColumn = (ImS8)table->Columns.index_from_ptr(last_active_column); + last_visible_column->NextVisibleColumn = (ImS8)column_n; + column->PrevVisibleColumn = (ImS8)table->Columns.index_from_ptr(last_visible_column); } - column->IndexWithinActiveSet = (ImS8)table->ColumnsActiveCount; - table->ColumnsActiveCount++; - table->ActiveMaskByIndex |= index_mask; - table->ActiveMaskByDisplayOrder |= display_order_mask; - last_active_column = column; + column->IndexWithinVisibleSet = (ImS8)table->ColumnsVisibleCount; + table->ColumnsVisibleCount++; + table->VisibleMaskByIndex |= index_mask; + table->VisibleMaskByDisplayOrder |= display_order_mask; + last_visible_column = column; } else { - column->IndexWithinActiveSet = -1; - table->ActiveMaskByIndex &= ~index_mask; - table->ActiveMaskByDisplayOrder &= ~display_order_mask; + column->IndexWithinVisibleSet = -1; + table->VisibleMaskByIndex &= ~index_mask; + table->VisibleMaskByDisplayOrder &= ~display_order_mask; } - IM_ASSERT(column->IndexWithinActiveSet <= column->DisplayOrder); + IM_ASSERT(column->IndexWithinVisibleSet <= column->DisplayOrder); } - table->VisibleMaskByIndex = table->ActiveMaskByIndex; // Columns will be masked out by TableUpdateLayout() when Clipped - table->RightMostActiveColumn = (ImS8)(last_active_column ? table->Columns.index_from_ptr(last_active_column) : -1); + table->VisibleUnclippedMaskByIndex = table->VisibleMaskByIndex; // Columns will be masked out by TableUpdateLayout() when Clipped + table->RightMostVisibleColumn = (ImS8)(last_visible_column ? table->Columns.index_from_ptr(last_visible_column) : -1); // Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid // the column fitting to wait until the first visible frame of the child container (may or not be a good thing). @@ -473,9 +473,9 @@ void ImGui::TableUpdateDrawChannels(ImGuiTable* table) // - FreezeRows || FreezeColumns --> 1+N*2 (unless scrolling value is zero) // - FreezeRows && FreezeColunns --> 2+N*2 (unless scrolling value is zero) const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1; - const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClipX) ? 1 : table->ColumnsActiveCount; + const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClipX) ? 1 : table->ColumnsVisibleCount; const int channels_for_background = 1; - const int channels_for_dummy = (table->ColumnsActiveCount < table->ColumnsCount || table->VisibleMaskByIndex != table->ActiveMaskByIndex) ? +1 : 0; + const int channels_for_dummy = (table->ColumnsVisibleCount < table->ColumnsCount || table->VisibleUnclippedMaskByIndex != table->VisibleMaskByIndex) ? +1 : 0; const int channels_total = channels_for_background + (channels_for_row * freeze_row_multiplier) + channels_for_dummy; table->DrawSplitter.Split(table->InnerWindow->DrawList, channels_total); table->DummyDrawChannel = channels_for_dummy ? (ImS8)(channels_total - 1) : -1; @@ -568,7 +568,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->ColumnsAutoFitWidth = 0.0f; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; @@ -626,11 +626,11 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // CellSpacingX is >0.0f when there's no vertical border, in which case we add two extra CellSpacingX to make auto-fit look nice instead of cramped. // We may want to expose this somehow. - table->ColumnsAutoFitWidth += spacing_auto_x * (table->ColumnsActiveCount - 1); + table->ColumnsAutoFitWidth += spacing_auto_x * (table->ColumnsVisibleCount - 1); // Layout // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible - const float width_spacings = table->CellSpacingX * (table->ColumnsActiveCount - 1); + const float width_spacings = table->CellSpacingX * (table->ColumnsVisibleCount - 1); float width_avail; if ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) width_avail = table->InnerClipRect.GetWidth() - width_spacings - 1.0f; @@ -645,7 +645,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->ColumnsTotalWidth = width_spacings; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]]; @@ -658,15 +658,15 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // [Resize Rule 2] Resizing from right-side of a weighted column before a fixed column froward sizing // to left-side of fixed column. We also need to copy the NoResize flag.. - if (column->NextActiveColumn != -1) - if (ImGuiTableColumn* next_column = &table->Columns[column->NextActiveColumn]) + if (column->NextVisibleColumn != -1) + if (ImGuiTableColumn* next_column = &table->Columns[column->NextVisibleColumn]) if (next_column->Flags & ImGuiTableColumnFlags_WidthFixed) column->Flags |= (next_column->Flags & ImGuiTableColumnFlags_NoDirectResize_); } - // [Resize Rule 1] The right-most active column is not resizable if there is at least one Stretch column - // (see comments in TableResizeColumn().) - if (column->NextActiveColumn == -1 && table->LeftMostStretchedColumnDisplayOrder != -1) + // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column + // (see comments in TableResizeColumn()) + if (column->NextVisibleColumn == -1 && table->LeftMostStretchedColumnDisplayOrder != -1) column->Flags |= ImGuiTableColumnFlags_NoDirectResize_; if (!(column->Flags & ImGuiTableColumnFlags_NoResize)) @@ -684,15 +684,15 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Shrink widths when the total does not fit // FIXME-TABLE: This is working but confuses/conflicts with manual resizing. // FIXME-TABLE: Policy to shrink down below below ideal/requested width if there's no room? - g.ShrinkWidthBuffer.resize(table->ColumnsActiveCount); - for (int order_n = 0, active_n = 0; order_n < table->ColumnsCount; order_n++) + g.ShrinkWidthBuffer.resize(table->ColumnsVisibleCount); + for (int order_n = 0, visible_n = 0; order_n < table->ColumnsCount; order_n++) { - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; const int column_n = table->DisplayOrder[order_n]; - g.ShrinkWidthBuffer[active_n].Index = column_n; - g.ShrinkWidthBuffer[active_n].Width = table->Columns[column_n].WidthGiven; - active_n++; + g.ShrinkWidthBuffer[visible_n].Index = column_n; + g.ShrinkWidthBuffer[visible_n].Width = table->Columns[column_n].WidthGiven; + visible_n++; } ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess); for (int n = 0; n < g.ShrinkWidthBuffer.Size; n++) @@ -710,7 +710,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (width_remaining_for_stretched_columns >= 1.0f) for (int order_n = table->ColumnsCount - 1; total_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--) { - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]]; if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch)) @@ -721,7 +721,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } // Setup final position, offset and clipping rectangles - int active_n = 0; + int visible_n = 0; float offset_x = (table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x; ImRect host_clip_rect = table->InnerClipRect; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) @@ -729,10 +729,10 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; - if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == active_n) + if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == visible_n) offset_x += work_rect.Min.x - table->OuterRect.Min.x; - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) { // Hidden column: clear a few fields and we are done with it for the remainder of the function. // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. @@ -761,7 +761,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // sure they are all visible. Because of this we also know that all of the columns will always fit in // table->WorkRect and therefore in table->InnerRect (because ScrollX is off) if (!(table->Flags & ImGuiTableFlags_NoKeepColumnsVisible)) - max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width; + max_x = table->WorkRect.Max.x - (table->ColumnsVisibleCount - (column->IndexWithinVisibleSet + 1)) * min_column_width; } if (offset_x + column->WidthGiven > max_x) column->WidthGiven = ImMax(max_x - offset_x, min_column_width); @@ -781,7 +781,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (column->IsClipped) { // Columns with the _WidthAlwaysAutoResize sizing policy will never be updated then. - table->VisibleMaskByIndex &= ~((ImU64)1 << column_n); + table->VisibleUnclippedMaskByIndex &= ~((ImU64)1 << column_n); } else { @@ -810,11 +810,11 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->CannotSkipItemsQueue >>= 1; } - if (active_n < table->FreezeColumnsCount) + if (visible_n < table->FreezeColumnsCount) host_clip_rect.Min.x = ImMax(host_clip_rect.Min.x, column->MaxX + 2.0f); offset_x += column->WidthGiven + table->CellSpacingX; - active_n++; + visible_n++; } // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, @@ -879,7 +879,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; const int column_n = table->DisplayOrderToIndex[order_n]; @@ -1033,7 +1033,7 @@ void ImGui::EndTable() column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x_headers); // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. - if (table->ActiveMaskByIndex & ((ImU64)1 << column_n)) + if (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) max_pos_x = ImMax(max_pos_x, column->MaxX + 1.0f); } @@ -1094,7 +1094,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) { for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; const int column_n = table->DisplayOrderToIndex[order_n]; @@ -1103,7 +1103,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered); - if (column->NextActiveColumn == -1 && !is_resizable) + if (column->NextVisibleColumn == -1 && !is_resizable) draw_right_border = false; if (draw_right_border && column->MaxX > column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. { @@ -1166,7 +1166,7 @@ static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - if (!column->IsActive || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + if (!column->IsVisible || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) continue; visible_weight += column->ResizeWeight; visible_width += column->WidthRequested; @@ -1177,7 +1177,7 @@ static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - if (!column->IsActive || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) + if (!column->IsVisible || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) continue; column->ResizeWeight = (column->WidthRequested + 0.0f) / visible_width; } @@ -1201,14 +1201,14 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f float min_width = TableGetMinColumnWidth(); float max_width_0 = FLT_MAX; if (!(table->Flags & ImGuiTableFlags_ScrollX)) - max_width_0 = (table->WorkRect.Max.x - column_0->MinX) - (table->ColumnsActiveCount - (column_0->IndexWithinActiveSet + 1)) * min_width; + max_width_0 = (table->WorkRect.Max.x - column_0->MinX) - (table->ColumnsVisibleCount - (column_0->IndexWithinVisibleSet + 1)) * min_width; column_0_width = ImClamp(column_0_width, min_width, max_width_0); // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) if (column_0->WidthGiven == column_0_width || column_0->WidthRequested == column_0_width) return; - ImGuiTableColumn* column_1 = (column_0->NextActiveColumn != -1) ? &table->Columns[column_0->NextActiveColumn] : NULL; + ImGuiTableColumn* column_1 = (column_0->NextVisibleColumn != -1) ? &table->Columns[column_0->NextVisibleColumn] : NULL; // In this surprisingly not simple because of how we support mixing Fixed and Stretch columns. // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. @@ -1315,7 +1315,7 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) // 1. Scan channels and take note of those which can be merged for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { - if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; @@ -1485,7 +1485,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, { // Init default visibility/sort state if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0) - column->IsActive = column->IsActiveNextFrame = false; + column->IsVisible = column->IsVisibleNextFrame = false; if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0) { column->SortOrder = 0; // Multiple columns using _DefaultSort will be reordered when building the sort specs. @@ -1692,7 +1692,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n) window->WorkRect.Max.x = column->MaxX - table->CellPaddingX2; // To allow ImGuiListClipper to function we propagate our row height - if (!column->IsActive) + if (!column->IsVisible) window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2); window->SkipItems = column->SkipItems; @@ -1752,7 +1752,7 @@ bool ImGui::TableNextCell() } int column_n = table->CurrentColumn; - return (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) != 0; + return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; } const char* ImGui::TableGetColumnName(int column_n) @@ -1766,6 +1766,7 @@ const char* ImGui::TableGetColumnName(int column_n) return TableGetColumnName(table, column_n); } +// We expose "Visible and Unclipped" to the user, vs our internal "Visible" state which is !Hidden bool ImGui::TableGetColumnIsVisible(int column_n) { ImGuiContext& g = *GImGui; @@ -1774,7 +1775,7 @@ bool ImGui::TableGetColumnIsVisible(int column_n) return false; if (column_n < 0) column_n = table->CurrentColumn; - return (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) != 0; + return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; } int ImGui::TableGetColumnIndex() @@ -1801,7 +1802,7 @@ bool ImGui::TableSetColumnIndex(int column_idx) TableBeginCell(table, column_idx); } - return (table->VisibleMaskByIndex & ((ImU64)1 << column_idx)) != 0; + return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_idx)) != 0; } // Return the cell rectangle based on currently known height. @@ -1876,7 +1877,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) { if (ImGuiTableColumn* selected_column = (selected_column_n != -1) ? &table->Columns[selected_column_n] : NULL) { - const bool can_resize = !(selected_column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && selected_column->IsActive; + const bool can_resize = !(selected_column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && selected_column->IsVisible; if (MenuItem("Size column to fit", NULL, false, can_resize)) TableSetColumnAutofit(table, selected_column_n); } @@ -1886,7 +1887,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - if (column->IsActive) + if (column->IsVisible) TableSetColumnAutofit(table, column_n); } } @@ -1918,10 +1919,10 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) // Make sure we can't hide the last active column bool menu_item_active = (column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true; - if (column->IsActive && table->ColumnsActiveCount <= 1) + if (column->IsVisible && table->ColumnsVisibleCount <= 1) menu_item_active = false; - if (MenuItem(name, NULL, column->IsActive, menu_item_active)) - column->IsActiveNextFrame = !column->IsActive; + if (MenuItem(name, NULL, column->IsVisible, menu_item_active)) + column->IsVisibleNextFrame = !column->IsVisible; } PopItemFlag(); } @@ -1995,8 +1996,8 @@ void ImGui::TableAutoHeaders() // FIXME-TABLE: This is not user-land code any more... perhaps instead we should expose hovered column. // and allow some sort of row-centric IsItemHovered() for full flexibility? float unused_x1 = table->WorkRect.Min.x; - if (table->RightMostActiveColumn != -1) - unused_x1 = ImMax(unused_x1, table->Columns[table->RightMostActiveColumn].MaxX); + if (table->RightMostVisibleColumn != -1) + unused_x1 = ImMax(unused_x1, table->Columns[table->RightMostVisibleColumn].MaxX); if (unused_x1 < table->WorkRect.Max.x) { // FIXME: We inherit ClipRect/SkipItem from last submitted column (active or not), let's temporarily override it. @@ -2091,14 +2092,14 @@ void ImGui::TableHeader(const char* label) // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder. if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x) - if (ImGuiTableColumn* prev_column = (column->PrevActiveColumn != -1) ? &table->Columns[column->PrevActiveColumn] : NULL) + if (ImGuiTableColumn* prev_column = (column->PrevVisibleColumn != -1) ? &table->Columns[column->PrevVisibleColumn] : NULL) if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder)) - if ((column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinActiveSet < table->FreezeColumnsRequest)) + if ((column->IndexWithinVisibleSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinVisibleSet < table->FreezeColumnsRequest)) table->ReorderColumnDir = -1; if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x) - if (ImGuiTableColumn* next_column = (column->NextActiveColumn != -1) ? &table->Columns[column->NextActiveColumn] : NULL) + if (ImGuiTableColumn* next_column = (column->NextVisibleColumn != -1) ? &table->Columns[column->NextVisibleColumn] : NULL) if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder)) - if ((column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (next_column->IndexWithinActiveSet < table->FreezeColumnsRequest)) + if ((column->IndexWithinVisibleSet < table->FreezeColumnsRequest) == (next_column->IndexWithinVisibleSet < table->FreezeColumnsRequest)) table->ReorderColumnDir = +1; } @@ -2257,7 +2258,7 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - if (column->SortOrder != -1 && !column->IsActive) + if (column->SortOrder != -1 && !column->IsVisible) column->SortOrder = -1; if (column->SortOrder == -1) continue; @@ -2300,7 +2301,7 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - if (!(column->Flags & ImGuiTableColumnFlags_NoSort) && column->IsActive) + if (!(column->Flags & ImGuiTableColumnFlags_NoSort) && column->IsVisible) { sort_order_count = 1; column->SortOrder = 0; @@ -2398,7 +2399,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) column_settings->DisplayOrder = column->DisplayOrder; column_settings->SortOrder = column->SortOrder; column_settings->SortDirection = column->SortDirection; - column_settings->Visible = column->IsActive; + column_settings->Visible = column->IsVisible; // We skip saving some data in the .ini file when they are unnecessary to restore our state // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. @@ -2450,7 +2451,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) column->DisplayOrder = column_settings->DisplayOrder; else column->DisplayOrder = (ImS8)column_n; - column->IsActive = column->IsActiveNextFrame = column_settings->Visible; + column->IsVisible = column->IsVisibleNextFrame = column_settings->Visible; column->SortOrder = column_settings->SortOrder; column->SortDirection = column_settings->SortDirection; } @@ -2592,13 +2593,13 @@ void ImGui::DebugNodeTable(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[n]; const char* name = TableGetColumnName(table, n); BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" - "Active: %d, Clipped: %d, DrawChannels: %d,%d\n" + "Visible: %d, Clipped: %d, DrawChannels: %d,%d\n" "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Ideal %d/%d\n" "SortOrder: %d, SortDir: %s\n" "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", n, column->DisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, - column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, + column->IsVisible, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, column->WidthGiven, column->WidthRequested, column->ResizeWeight, column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersIdeal, column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? "Ascending" : (column->SortDirection == ImGuiSortDirection_Descending) ? "Descending" : "None", From bc170e73257e2be2713f63e0b386e81abca65f64 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 22 May 2020 15:27:53 +0200 Subject: [PATCH 429/959] Tables: Renamed ResizeWeight->WidthStretchWeight, WidthRequested->WidthFixedRequest, clarififications, comments. --- imgui_demo.cpp | 32 +++++++------- imgui_internal.h | 8 ++-- imgui_tables.cpp | 111 ++++++++++++++++++++++++----------------------- 3 files changed, 76 insertions(+), 75 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b91ec0ab..b55d5492 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3246,7 +3246,7 @@ struct MyItem int Quantity; // We have a problem which is affecting _only this demo_ and should not affect your code: - // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(), + // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(), // however qsort doesn't allow passing user data to comparing function. // As a workaround, we are storing the sort specs in a static/global for the comparing function to access. // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global. @@ -3326,9 +3326,9 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Basic")) { // Here we will showcase 4 different ways to output a table. They are very simple variations of a same thing! - + // Basic use of tables using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. - // In many situations, this is the most flexible and easy to use pattern. + // In many situations, this is the most flexible and easy to use pattern. HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop."); if (ImGui::BeginTable("##table1", 3)) { @@ -3363,7 +3363,7 @@ static void ShowDemoWindowTables() } // Another subtle variant, we call TableNextCell() _before_ each cell. At the end of a row, TableNextCell() will create a new row. - // Note that we don't call TableNextRow() here! + // Note that we don't call TableNextRow() here! // If we want to call TableNextRow(), then we don't need to call TableNextCell() for the first cell. HelpMarker("Only using TableNextCell(), which tends to be convenient for tables where every cells contains the same type of contents.\nThis is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition."); if (ImGui::BeginTable("##table4", 3)) @@ -3449,7 +3449,7 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); ImGui::SameLine(); HelpMarker("Using the _Resizable flag automatically enables the _BordersV flag as well."); - + if (ImGui::BeginTable("##table1", 3, flags)) { for (int row = 0; row < 5; row++) @@ -3550,7 +3550,7 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", (unsigned int*)&flags, ImGuiTableFlags_Reorderable); ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", (unsigned int*)&flags, ImGuiTableFlags_Hideable); - + if (ImGui::BeginTable("##table1", 3, flags)) { // Submit columns name with TableSetupColumn() and call TableAutoHeaders() to create a row with a header in each column. @@ -3600,7 +3600,7 @@ static void ShowDemoWindowTables() static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); - + if (ImGui::BeginTable("##table1", 3, flags, size)) { ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); @@ -3735,7 +3735,7 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Recursive")) { HelpMarker("This demonstrate embedding a table into another table cell."); - + if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersVFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("A0"); @@ -3904,13 +3904,13 @@ static void ShowDemoWindowTables() ImGui::TableAutoHeaders(); // Simple storage to output a dummy file-system. - struct MyTreeNode - { - const char* Name; - const char* Type; - int Size; - int ChildIdx; - int ChildCount; + struct MyTreeNode + { + const char* Name; + const char* Type; + int Size; + int ChildIdx; + int ChildCount; static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes) { ImGui::TableNextRow(); @@ -3960,7 +3960,7 @@ static void ShowDemoWindowTables() } // Demonstrate using TableHeader() calls instead of TableAutoHeaders() - // FIXME-TABLE: Currently this doesn't get us feature-parity with TableAutoHeaders(), e.g. missing context menu. Tables API needs some work! + // FIXME-TABLE: Currently this doesn't get us feature-parity with TableAutoHeaders(), e.g. missing context menu. Tables API needs some work! if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Custom headers")) diff --git a/imgui_internal.h b/imgui_internal.h index d8d05245..362390a9 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1897,9 +1897,9 @@ struct ImGuiTableColumn ImGuiTableColumnFlags Flags; // Effective flags. See ImGuiTableColumnFlags_ float MinX; // Absolute positions float MaxX; - float ResizeWeight; // ~1.0f. Master width data when (Flags & _WidthStretch) - float WidthRequested; // Master width data when !(Flags & _WidthStretch) - float WidthGiven; // == (MaxX - MinX). FIXME-TABLE: Store all persistent width in multiple of FontSize? + float WidthStretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. + float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from WidthStretchWeight in TableUpdateLayout() + float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be >WidthRequest to honor minimum width, may be LeftMostStretchedColumnDisplayOrder = -1; table->ColumnsAutoFitWidth = 0.0f; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) @@ -598,27 +598,27 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) { // Latch initial size for fixed columns count_fixed += 1; - const bool init_size = (column->AutoFitQueue != 0x00) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize); - if (init_size) + const bool auto_fit = (column->AutoFitQueue != 0x00) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize); + if (auto_fit) { - column->WidthRequested = column_width_ideal; + column->WidthRequest = column_width_ideal; // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very // large height (= first frame scrollbar display very off + clipper would skip lots of items). // This is merely making the side-effect less extreme, but doesn't properly fixes it. if (column->AutoFitQueue > 0x01 && table->IsInitializing) - column->WidthRequested = ImMax(column->WidthRequested, min_column_width * 4.0f); + column->WidthRequest = ImMax(column->WidthRequest, min_column_width * 4.0f); } - width_fixed += column->WidthRequested; + sum_width_fixed_requests += column->WidthRequest; } else { IM_ASSERT(column->Flags & ImGuiTableColumnFlags_WidthStretch); - const int init_size = (column->ResizeWeight < 0.0f); + const int init_size = (column->WidthStretchWeight < 0.0f); if (init_size) - column->ResizeWeight = 1.0f; - total_weights += column->ResizeWeight; + column->WidthStretchWeight = 1.0f; + sum_weights_stretched += column->WidthStretchWeight; if (table->LeftMostStretchedColumnDisplayOrder == -1) table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->DisplayOrder; } @@ -636,7 +636,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) width_avail = table->InnerClipRect.GetWidth() - width_spacings - 1.0f; else width_avail = work_rect.GetWidth() - width_spacings - 1.0f; - const float width_avail_for_stretched_columns = width_avail - width_fixed; + const float width_avail_for_stretched_columns = width_avail - sum_width_fixed_requests; float width_remaining_for_stretched_columns = width_avail_for_stretched_columns; // Apply final width based on requested widths @@ -652,12 +652,13 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Allocate width for stretched/weighted columns if (column->Flags & ImGuiTableColumnFlags_WidthStretch) { - float weight_ratio = column->ResizeWeight / total_weights; - column->WidthRequested = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, min_column_width) + 0.01f); - width_remaining_for_stretched_columns -= column->WidthRequested; + // WidthStretchWeight gets converted into WidthRequest + float weight_ratio = column->WidthStretchWeight / sum_weights_stretched; + column->WidthRequest = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, min_column_width) + 0.01f); + width_remaining_for_stretched_columns -= column->WidthRequest; - // [Resize Rule 2] Resizing from right-side of a weighted column before a fixed column froward sizing - // to left-side of fixed column. We also need to copy the NoResize flag.. + // [Resize Rule 2] Resizing from right-side of a weighted column preceding a fixed column + // needs to forward resizing to left-side of fixed column. We also need to copy the NoResize flag.. if (column->NextVisibleColumn != -1) if (ImGuiTableColumn* next_column = &table->Columns[column->NextVisibleColumn]) if (next_column->Flags & ImGuiTableColumnFlags_WidthFixed) @@ -673,7 +674,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) count_resizable++; // Assign final width, record width in case we will need to shrink - column->WidthGiven = ImFloor(ImMax(column->WidthRequested, min_column_width)); + column->WidthGiven = ImFloor(ImMax(column->WidthRequest, min_column_width)); table->ColumnsTotalWidth += column->WidthGiven; } @@ -703,19 +704,19 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) #endif // Redistribute remainder width due to rounding (remainder width is < 1.0f * number of Stretch column). - // Using right-to-left distribution (more likely to match resizing cursor), could be adjusted depending where - // the mouse cursor is and/or relative weights. + // Using right-to-left distribution (more likely to match resizing cursor), could be adjusted depending + // on where the mouse cursor is and/or relative weights. // FIXME-TABLE: May be simpler to store floating width and floor final positions only // FIXME-TABLE: Make it optional? User might prefer to preserve pixel perfect same size? if (width_remaining_for_stretched_columns >= 1.0f) - for (int order_n = table->ColumnsCount - 1; total_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--) + for (int order_n = table->ColumnsCount - 1; sum_weights_stretched > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--) { if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) continue; ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]]; if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch)) continue; - column->WidthRequested += 1.0f; + column->WidthRequest += 1.0f; column->WidthGiven += 1.0f; width_remaining_for_stretched_columns -= 1.0f; } @@ -1168,8 +1169,8 @@ static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; if (!column->IsVisible || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) continue; - visible_weight += column->ResizeWeight; - visible_width += column->WidthRequested; + visible_weight += column->WidthStretchWeight; + visible_width += column->WidthRequest; } IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f); @@ -1179,7 +1180,7 @@ static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; if (!column->IsVisible || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) continue; - column->ResizeWeight = (column->WidthRequested + 0.0f) / visible_width; + column->WidthStretchWeight = (column->WidthRequest + 0.0f) / visible_width; } } @@ -1205,7 +1206,7 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f column_0_width = ImClamp(column_0_width, min_width, max_width_0); // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) - if (column_0->WidthGiven == column_0_width || column_0->WidthRequested == column_0_width) + if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width) return; ImGuiTableColumn* column_1 = (column_0->NextVisibleColumn != -1) ? &table->Columns[column_0->NextVisibleColumn] : NULL; @@ -1241,14 +1242,14 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f if (table->LeftMostStretchedColumnDisplayOrder != -1 && table->LeftMostStretchedColumnDisplayOrder < column_0->DisplayOrder) { // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) - float column_1_width = ImMax(column_1->WidthRequested - (column_0_width - column_0->WidthRequested), min_width); - column_0_width = column_0->WidthRequested + column_1->WidthRequested - column_1_width; - column_1->WidthRequested = column_1_width; + float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width); + column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width; + column_1->WidthRequest = column_1_width; } // Apply //IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthRequested, column_0_width); - column_0->WidthRequested = column_0_width; + column_0->WidthRequest = column_0_width; } else if (column_0->Flags & ImGuiTableColumnFlags_WidthStretch) { @@ -1257,15 +1258,15 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f { float off = (column_0->WidthGiven - column_0_width); float column_1_width = column_1->WidthGiven + off; - column_1->WidthRequested = ImMax(min_width, column_1_width); + column_1->WidthRequest = ImMax(min_width, column_1_width); return; } // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b) - float column_1_width = ImMax(column_1->WidthRequested - (column_0_width - column_0->WidthRequested), min_width); - column_0_width = column_0->WidthRequested + column_1->WidthRequested - column_1_width; - column_1->WidthRequested = column_1_width; - column_0->WidthRequested = column_0_width; + float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width); + column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width; + column_1->WidthRequest = column_1_width; + column_0->WidthRequest = column_0_width; TableUpdateColumnsWeightFromWidth(table); } table->IsSettingsDirty = true; @@ -1462,23 +1463,23 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, // Initialize defaults // FIXME-TABLE: We don't restore widths/weight so let's avoid using IsSettingsLoaded for now - if (table->IsInitializing && column->WidthRequested < 0.0f && column->ResizeWeight < 0.0f)// && !table->IsSettingsLoaded) + if (table->IsInitializing && column->WidthRequest < 0.0f && column->WidthStretchWeight < 0.0f)// && !table->IsSettingsLoaded) { // Init width or weight // Disable auto-fit if a default fixed width has been specified if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) { - column->WidthRequested = init_width_or_weight; + column->WidthRequest = init_width_or_weight; column->AutoFitQueue = 0x00; } if (flags & ImGuiTableColumnFlags_WidthStretch) { IM_ASSERT(init_width_or_weight < 0.0f || init_width_or_weight > 0.0f); - column->ResizeWeight = (init_width_or_weight < 0.0f ? 1.0f : init_width_or_weight); + column->WidthStretchWeight = (init_width_or_weight < 0.0f ? 1.0f : init_width_or_weight); } else { - column->ResizeWeight = 1.0f; + column->WidthStretchWeight = 1.0f; } } if (table->IsInitializing) @@ -2594,13 +2595,13 @@ void ImGui::DebugNodeTable(ImGuiTable* table) const char* name = TableGetColumnName(table, n); BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" "Visible: %d, Clipped: %d, DrawChannels: %d,%d\n" - "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n" + "WidthGiven/Request: %.1f/%.1f, WidthWeight: %.3f\n" "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Ideal %d/%d\n" "SortOrder: %d, SortDir: %s\n" "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", n, column->DisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, column->IsVisible, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze, - column->WidthGiven, column->WidthRequested, column->ResizeWeight, + column->WidthGiven, column->WidthRequest, column->WidthStretchWeight, column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersIdeal, column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? "Ascending" : (column->SortDirection == ImGuiSortDirection_Descending) ? "Descending" : "None", column->UserID, column->Flags, From af52a0cea203c43385252adb94a44b42c7cd2ff8 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 22 May 2020 16:48:13 +0200 Subject: [PATCH 430/959] Tables: Resizing weighted column preserve sum of weights. Fix ResizedColumn init leading to undesirable TableSetColumnWidth() on first run. Rework TableSettingsHandler_ReadLine() structure to allow other types of line. --- imgui_internal.h | 3 ++- imgui_tables.cpp | 27 +++++++++++++++------------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 362390a9..2acc1d74 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2037,6 +2037,7 @@ struct ImGuiTable LastResizedColumn = -1; ContextPopupColumn = -1; ReorderColumn = -1; + ResizedColumn = -1; } }; @@ -2048,7 +2049,7 @@ struct ImGuiTableColumnSettings ImS8 Index; ImS8 DisplayOrder; ImS8 SortOrder; - ImS8 SortDirection : 7; + ImU8 SortDirection : 2; ImU8 Visible : 1; ImGuiTableColumnSettings() diff --git a/imgui_tables.cpp b/imgui_tables.cpp index aa133d97..9fd8c3d1 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1180,7 +1180,7 @@ static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; if (!column->IsVisible || !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) continue; - column->WidthStretchWeight = (column->WidthRequest + 0.0f) / visible_width; + column->WidthStretchWeight = ((column->WidthRequest + 0.0f) / visible_width) * visible_weight; } } @@ -2506,18 +2506,21 @@ static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" ImGuiTableSettings* settings = (ImGuiTableSettings*)entry; int column_n = 0, r = 0, n = 0; - if (sscanf(line, "Column %d%n", &column_n, &r) == 1) { line = ImStrSkipBlank(line + r); } else { return; } - if (column_n < 0 || column_n >= settings->ColumnsCount) - return; - char c = 0; - ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n; - column->Index = (ImS8)column_n; - if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r) == 1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; } - if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); /* .. */ settings->SaveFlags |= ImGuiTableFlags_Resizable; } - if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->Visible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } - if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImS8)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; } - if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImS8)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } + if (sscanf(line, "Column %d%n", &column_n, &r) == 1) + { + if (column_n < 0 || column_n >= settings->ColumnsCount) + return; + line = ImStrSkipBlank(line + r); + char c = 0; + ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n; + column->Index = (ImS8)column_n; + if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; } + if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); /* .. */ settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->Visible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } + if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImS8)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; } + if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImS8)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } + } } static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) From 6bc0bbccf3296d7c31be281db9bf9778ac8ffa67 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 22 May 2020 18:00:23 +0200 Subject: [PATCH 431/959] Tables: Restore width/weight saving/loading code. Non-weighted width currently not font/DPI change friendly. --- imgui_internal.h | 6 ++++-- imgui_tables.cpp | 36 ++++++++++++++++++++++++------------ 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 2acc1d74..6deb8f9a 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2050,7 +2050,8 @@ struct ImGuiTableColumnSettings ImS8 DisplayOrder; ImS8 SortOrder; ImU8 SortDirection : 2; - ImU8 Visible : 1; + ImU8 IsVisible : 1; + ImU8 IsWeighted : 1; ImGuiTableColumnSettings() { @@ -2059,7 +2060,8 @@ struct ImGuiTableColumnSettings Index = -1; DisplayOrder = SortOrder = -1; SortDirection = ImGuiSortDirection_None; - Visible = 1; + IsVisible = 1; + IsWeighted = 0; } }; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 9fd8c3d1..726a9312 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -73,7 +73,7 @@ // | TableSortSpecsClickColumn() - when clicked: alter sort order and sort direction // - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) // - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders() -// | TableUpdateLayout() - called by the FIRST call to TableNextRow()! lock all widths and columns positions. +// | TableUpdateLayout() - lock all widths and columns positions! called by the FIRST call to TableNextRow()! // | - TableUpdateDrawChannels() - setup ImDrawList channels // | - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission // | - TableDrawContextMenu() - draw right-click context menu @@ -2395,20 +2395,21 @@ void ImGui::TableSaveSettings(ImGuiTable* table) settings->SaveFlags = ImGuiTableFlags_Resizable; for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++) { - //column_settings->WidthOrWeight = column->WidthRequested; // FIXME-TABLE: Missing + column_settings->WidthOrWeight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->WidthStretchWeight : column->WidthRequest; column_settings->Index = (ImS8)n; column_settings->DisplayOrder = column->DisplayOrder; column_settings->SortOrder = column->SortOrder; column_settings->SortDirection = column->SortDirection; - column_settings->Visible = column->IsVisible; + column_settings->IsVisible = column->IsVisible; + column_settings->IsWeighted = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0; // We skip saving some data in the .ini file when they are unnecessary to restore our state // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. if (column->DisplayOrder != n) settings->SaveFlags |= ImGuiTableFlags_Reorderable; - if (column_settings->SortOrder != -1) + if (column->SortOrder != -1) settings->SaveFlags |= ImGuiTableFlags_Sortable; - if (column_settings->Visible != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) + if (column->IsVisible != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) settings->SaveFlags |= ImGuiTableFlags_Hideable; } settings->SaveFlags &= table->Flags; @@ -2446,13 +2447,21 @@ void ImGui::TableLoadSettings(ImGuiTable* table) int column_n = column_settings->Index; if (column_n < 0 || column_n >= table->ColumnsCount) continue; + ImGuiTableColumn* column = &table->Columns[column_n]; - //column->WidthRequested = column_settings->WidthOrWeight; // FIXME-WIP + if (settings->SaveFlags & ImGuiTableFlags_Resizable) + { + if (column_settings->IsWeighted) + column->WidthStretchWeight = column_settings->WidthOrWeight; + else + column->WidthRequest = column_settings->WidthOrWeight; + column->AutoFitQueue = 0x00; + } if (settings->SaveFlags & ImGuiTableFlags_Reorderable) column->DisplayOrder = column_settings->DisplayOrder; else column->DisplayOrder = (ImS8)column_n; - column->IsVisible = column->IsVisibleNextFrame = column_settings->Visible; + column->IsVisible = column->IsVisibleNextFrame = column_settings->IsVisible; column->SortOrder = column_settings->SortOrder; column->SortDirection = column_settings->SortDirection; } @@ -2505,6 +2514,7 @@ static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, { // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" ImGuiTableSettings* settings = (ImGuiTableSettings*)entry; + float f = 0.0f; int column_n = 0, r = 0, n = 0; if (sscanf(line, "Column %d%n", &column_n, &r) == 1) @@ -2516,8 +2526,9 @@ static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n; column->Index = (ImS8)column_n; if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; } - if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); /* .. */ settings->SaveFlags |= ImGuiTableFlags_Resizable; } - if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->Visible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } + if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsWeighted = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsWeighted = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsVisible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImS8)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; } if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImS8)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } } @@ -2548,8 +2559,9 @@ static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandle // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" buf->appendf("Column %-2d", column_n); if (column->UserID != 0) buf->appendf(" UserID=%08X", column->UserID); - if (save_size) buf->appendf(" Width=%d", 0);// (int)settings_column->WidthOrWeight); // FIXME-TABLE - if (save_visible) buf->appendf(" Visible=%d", column->Visible); + if (save_size && column->IsWeighted) buf->appendf(" Weight=%.4f", column->WidthOrWeight); + if (save_size && !column->IsWeighted) buf->appendf(" Width=%d", (int)column->WidthOrWeight); + if (save_visible) buf->appendf(" Visible=%d", column->IsVisible); if (save_order) buf->appendf(" Order=%d", column->DisplayOrder); if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^'); buf->append("\n"); @@ -2631,7 +2643,7 @@ void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings) BulletText("Column %d Order %d SortOrder %d %s Visible %d UserID 0x%08X WidthOrWeight %.3f", n, column_settings->DisplayOrder, column_settings->SortOrder, (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---", - column_settings->Visible, column_settings->UserID, column_settings->WidthOrWeight); + column_settings->IsVisible, column_settings->UserID, column_settings->WidthOrWeight); } TreePop(); } From fec9d7d2260abeb6ced684cabb0e70599101c87b Mon Sep 17 00:00:00 2001 From: omar Date: Sun, 24 May 2020 20:07:21 +0200 Subject: [PATCH 432/959] Tables: Rescale fixed widths when font size change to support varying dpi scale at runtime and on .ini reload. --- imgui_internal.h | 2 ++ imgui_tables.cpp | 27 ++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/imgui_internal.h b/imgui_internal.h index 6deb8f9a..780bc33c 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1985,6 +1985,7 @@ struct ImGuiTable float ColumnsTotalWidth; // Sum of current column width float ColumnsAutoFitWidth; // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window float ResizedColumnNextWidth; + float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. ImRect OuterRect; // Note: OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). ImRect WorkRect; ImRect InnerClipRect; @@ -2070,6 +2071,7 @@ struct ImGuiTableSettings { ImGuiID ID; // Set to 0 to invalidate/delete the setting ImGuiTableFlags SaveFlags; // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..) + float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. ImS8 ColumnsCount; ImS8 ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 726a9312..87bffa86 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -328,6 +328,21 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (table->IsSettingsRequestLoad) TableLoadSettings(table); + // Handle DPI/font resize + // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well. + // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition. + // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory. + // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path. + const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ? + if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit) + { + const float scale_factor = new_ref_scale_unit / table->RefScale; + //IMGUI_DEBUG_LOG("[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor); + for (int n = 0; n < columns_count; n++) + table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor; + } + table->RefScale = new_ref_scale_unit; + // Disable output until user calls TableNextRow() or TableNextCell() leading to the TableUpdateLayout() call.. // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. @@ -607,6 +622,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very // large height (= first frame scrollbar display very off + clipper would skip lots of items). // This is merely making the side-effect less extreme, but doesn't properly fixes it. + // FIXME: Move this to ->WidthGiven to avoid temporary lossyless? if (column->AutoFitQueue > 0x01 && table->IsInitializing) column->WidthRequest = ImMax(column->WidthRequest, min_column_width * 4.0f); } @@ -2392,6 +2408,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); // FIXME-TABLE: Logic to avoid saving default widths? + bool save_ref_scale = false; settings->SaveFlags = ImGuiTableFlags_Resizable; for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++) { @@ -2402,6 +2419,8 @@ void ImGui::TableSaveSettings(ImGuiTable* table) column_settings->SortDirection = column->SortDirection; column_settings->IsVisible = column->IsVisible; column_settings->IsWeighted = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0; + if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0) + save_ref_scale = true; // We skip saving some data in the .ini file when they are unnecessary to restore our state // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. @@ -2413,6 +2432,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) settings->SaveFlags |= ImGuiTableFlags_Hideable; } settings->SaveFlags &= table->Flags; + settings->RefScale = save_ref_scale ? table->RefScale : 0.0f; MarkIniSettingsDirty(); } @@ -2438,6 +2458,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) settings = TableGetBoundSettings(table); } table->SettingsLoadedFlags = settings->SaveFlags; + table->RefScale = settings->RefScale; IM_ASSERT(settings->ColumnsCount == table->ColumnsCount); // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn @@ -2517,6 +2538,8 @@ static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, float f = 0.0f; int column_n = 0, r = 0, n = 0; + if (sscanf(line, "RefScale=%f", &f) == 1) { settings->RefScale = f; return; } + if (sscanf(line, "Column %d%n", &column_n, &r) == 1) { if (column_n < 0 || column_n >= settings->ColumnsCount) @@ -2553,6 +2576,8 @@ static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandle buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount); + if (settings->RefScale != 0.0f) + buf->appendf("RefScale=%g\n", settings->RefScale); ImGuiTableColumnSettings* column = settings->GetColumnSettings(); for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++) { @@ -2610,7 +2635,7 @@ void ImGui::DebugNodeTable(ImGuiTable* table) const char* name = TableGetColumnName(table, n); BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n" "Visible: %d, Clipped: %d, DrawChannels: %d,%d\n" - "WidthGiven/Request: %.1f/%.1f, WidthWeight: %.3f\n" + "WidthGiven/Request: %.2f/%.2f, WidthWeight: %.3f\n" "ContentWidth: RowsFrozen %d, RowsUnfrozen %d, HeadersUsed/Ideal %d/%d\n" "SortOrder: %d, SortDir: %s\n" "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..", From e41fc7b5b03e6efccad996552b06b6bb1c467890 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 29 May 2020 18:32:04 +0200 Subject: [PATCH 433/959] Tables: Fix TableDrawMergeChannels() mistakenly merging unfrozen columns cliprect with host cliprect. Comments, debug. --- imgui_tables.cpp | 62 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 18 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 87bffa86..2c3deeea 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1290,11 +1290,11 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // Columns where the contents didn't stray off their local clip rectangle can be merged into a same draw command. // To achieve this we merge their clip rect and make them contiguous in the channel list so they can be merged. -// So here we'll reorder the draw cmd which can be merged, by arranging them into a maximum of 4 distinct groups: +// This function first reorder the draw cmd which can be merged, by arranging them into a maximum of 4 distinct groups: // // 1 group: 2 groups: 2 groups: 4 groups: -// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze -// [ .. ] or no scroll [ 1. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll +// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 02 ] row+col freeze +// [ .. ] or no scroll [ 1. ] and v-scroll [ .. ] and h-scroll [ 13 ] and v+h-scroll // // Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). // When the contents of a column didn't stray off its limit, we move its channels into the corresponding group @@ -1306,8 +1306,9 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). // Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds // matches, by e.g. calling SetCursorScreenPos(). -// - The channel uses more than one draw command itself. We drop all our merging stuff here.. we could do better -// but it's going to be rare. +// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here.. +// we could do better but it's going to be rare and probably not worth the hassle. +// Columns for which the draw chnanel(s) haven't been merged with other will use their own ImDrawCmd. // // This function is particularly tricky to understand.. take a breath. void ImGui::TableDrawMergeChannels(ImGuiTable* table) @@ -1350,15 +1351,18 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) continue; // Find out the width of this merge group and check if it will fit in our column. - float width_contents; - if (merge_group_sub_count == 1) // No row freeze (same as testing !is_frozen_v) - width_contents = ImMax(column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed); - else if (merge_group_sub_n == 0) // Row freeze: use width before freeze - width_contents = ImMax(column->ContentWidthRowsFrozen, column->ContentWidthHeadersUsed); - else // Row freeze: use width after freeze - width_contents = column->ContentWidthRowsUnfrozen; - if (width_contents > column->WidthGiven && !(column->Flags & ImGuiTableColumnFlags_NoClipX)) - continue; + if (!(column->Flags & ImGuiTableColumnFlags_NoClipX)) + { + float width_contents; + if (merge_group_sub_count == 1) // No row freeze (same as testing !is_frozen_v) + width_contents = ImMax(column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed); + else if (merge_group_sub_n == 0) // Row freeze: use width before freeze + width_contents = ImMax(column->ContentWidthRowsFrozen, column->ContentWidthHeadersUsed); + else // Row freeze: use width after freeze + width_contents = column->ContentWidthRowsUnfrozen; + if (width_contents > column->WidthGiven) + continue; + } const int merge_group_dst_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1); IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS); @@ -1385,28 +1389,50 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) } // Invalidate current draw channel - // (we don't clear DrawChannelBeforeRowFreeze/DrawChannelAfterRowFreeze solely to facilitate debugging) + // (we don't clear DrawChannelBeforeRowFreeze/DrawChannelAfterRowFreeze solely to facilitate debugging/later inspection of data) column->DrawChannelCurrent = -1; } + // [DEBUG] Display merge groups +#if 0 + if (g.IO.KeyShift) + for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++) + { + MergeGroup* merge_group = &merge_groups[merge_group_n]; + if (merge_group->ChannelsCount == 0) + continue; + char buf[32]; + ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount); + ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4); + ImVec2 text_size = CalcTextSize(buf, NULL); + GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255)); + GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL); + GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255)); + } +#endif + // 2. Rewrite channel list in our preferred order if (merge_group_mask != 0) { + // Conceptually we want to test if only 1 bit of merge_group_mask is set, but with no freezing we know it's always going to be group 3. + // We need to test for !is_frozen because any unfitting column will not be part of a merge group, so testing for merge_group_mask isn't enough. + const bool may_extend_clip_rect_to_host_rect = (merge_group_mask == (1 << 3)) && !is_frozen_v && !is_frozen_h; + // Use shared temporary storage so the allocation gets amortized g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - 1); ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data; - ImBitArray remaining_mask; + ImBitArray remaining_mask; // We need 130-bit of storage remaining_mask.ClearBits(); remaining_mask.SetBitRange(1, splitter->_Count - 1); // Background channel 0 not part of the merge (see channel allocation in TableUpdateDrawChannels) int remaining_count = splitter->_Count - 1; - const bool may_extend_clip_rect_to_host_rect = ImIsPowerOfTwo(merge_group_mask); - for (int merge_group_n = 0; merge_group_n < 4; merge_group_n++) + for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++) if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount) { MergeGroup* merge_group = &merge_groups[merge_group_n]; ImRect merge_clip_rect = merge_groups[merge_group_n].ClipRect; if (may_extend_clip_rect_to_host_rect) { + IM_ASSERT(merge_group_n == 3); //GetOverlayDrawList()->AddRect(table->HostClipRect.Min, table->HostClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 3.0f); //GetOverlayDrawList()->AddRect(table->InnerClipRect.Min, table->InnerClipRect.Max, IM_COL32(0, 255, 0, 200), 0.0f, ~0, 1.0f); //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 2.0f); From 7513842284e513f19d87da7aeb5945d619020ad5 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 29 May 2020 19:31:47 +0200 Subject: [PATCH 434/959] Tables: Fix assert/crash when a visible column is clipped in a multi clip group situation. --- imgui_tables.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2c3deeea..efeed39f 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1331,11 +1331,10 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) bool merge_groups_all_fit_within_inner_rect = (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0; // 1. Scan channels and take note of those which can be merged - for (int order_n = 0; order_n < table->ColumnsCount; order_n++) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { - if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) + if (!(table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n))) continue; - const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; const int merge_group_sub_count = is_frozen_v ? 2 : 1; From af992d1321b2f2c9ea5dbfdeddad8ad68e9b0306 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jun 2020 16:03:50 +0200 Subject: [PATCH 435/959] Tables: Tweak settings functions to more prominently clarify the two levels of function. --- imgui.cpp | 2 +- imgui_internal.h | 11 +++++++---- imgui_tables.cpp | 22 ++++++++++++++-------- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 7ad7a547..bc1ac4b7 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -3970,7 +3970,7 @@ void ImGui::Initialize(ImGuiContext* context) #ifdef IMGUI_HAS_TABLE // Add .ini handle for ImGuiTable type - TableInstallSettingsHandler(context); + TableSettingsInstallHandler(context); #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK diff --git a/imgui_internal.h b/imgui_internal.h index 780bc33c..b9e1d889 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2275,10 +2275,13 @@ namespace ImGui IMGUI_API void TableSetColumnAutofit(ImGuiTable* table, int column_n); IMGUI_API void PushTableBackground(); IMGUI_API void PopTableBackground(); - IMGUI_API void TableLoadSettings(ImGuiTable* table); - IMGUI_API void TableSaveSettings(ImGuiTable* table); - IMGUI_API ImGuiTableSettings* TableGetBoundSettings(const ImGuiTable* table); - IMGUI_API void TableInstallSettingsHandler(ImGuiContext* context); + IMGUI_API void TableSettingsInstallHandler(ImGuiContext* context); + IMGUI_API ImGuiTableSettings* TableSettingsCreate(ImGuiID id, int columns_count); + IMGUI_API ImGuiTableSettings* TableSettingsFindByID(ImGuiID id); + IMGUI_API void TableSettingsClearByID(ImGuiID id); + IMGUI_API void TableLoadSettings(ImGuiTable* table); + IMGUI_API void TableSaveSettings(ImGuiTable* table); + IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table); // Tab Bars IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index efeed39f..48ef06a7 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2376,7 +2376,7 @@ static void InitTableSettings(ImGuiTableSettings* settings, ImGuiID id, int colu settings->WantApply = true; } -static ImGuiTableSettings* CreateTableSettings(ImGuiID id, int columns_count) +ImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count) { ImGuiContext& g = *GImGui; ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings)); @@ -2385,7 +2385,7 @@ static ImGuiTableSettings* CreateTableSettings(ImGuiID id, int columns_count) } // Find existing settings -static ImGuiTableSettings* FindTableSettingsByID(ImGuiID id) +ImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id) { // FIXME-OPT: Might want to store a lookup map for this? ImGuiContext& g = *GImGui; @@ -2395,8 +2395,14 @@ static ImGuiTableSettings* FindTableSettingsByID(ImGuiID id) return NULL; } +void ImGui::TableSettingsClearByID(ImGuiID id) +{ + if (ImGuiTableSettings* settings = TableSettingsFindByID(id)) + settings->ID = 0; +} + // Get settings for a given table, NULL if none -ImGuiTableSettings* ImGui::TableGetBoundSettings(const ImGuiTable* table) +ImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table) { if (table->SettingsOffset != -1) { @@ -2421,7 +2427,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) ImGuiTableSettings* settings = TableGetBoundSettings(table); if (settings == NULL) { - settings = CreateTableSettings(table->ID, table->ColumnsCount); + settings = TableSettingsCreate(table->ID, table->ColumnsCount); table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); } settings->ColumnsCount = (ImS8)table->ColumnsCount; @@ -2473,7 +2479,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) ImGuiTableSettings* settings; if (table->SettingsOffset == -1) { - settings = FindTableSettingsByID(table->ID); + settings = TableSettingsFindByID(table->ID); if (settings == NULL) return; table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); @@ -2544,7 +2550,7 @@ static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2) return NULL; - if (ImGuiTableSettings* settings = FindTableSettingsByID(id)) + if (ImGuiTableSettings* settings = ImGui::TableSettingsFindByID(id)) { if (settings->ColumnsCountMax >= columns_count) { @@ -2553,7 +2559,7 @@ static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, } settings->ID = 0; // Invalidate storage if we won't fit because of a count change } - return CreateTableSettings(id, columns_count); + return ImGui::TableSettingsCreate(id, columns_count); } static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) @@ -2620,7 +2626,7 @@ static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandle } } -void ImGui::TableInstallSettingsHandler(ImGuiContext* context) +void ImGui::TableSettingsInstallHandler(ImGuiContext* context) { ImGuiContext& g = *context; ImGuiSettingsHandler ini_handler; From 8690d1f9cec767878a97d01dd8d723b26a00bc36 Mon Sep 17 00:00:00 2001 From: Rokas Kupstys Date: Mon, 1 Jun 2020 12:25:08 +0300 Subject: [PATCH 436/959] Tables: Fix sort specs sometimes incorrectly reporting sort spec count when table loses _MultiSortable flag during runtime. --- imgui_tables.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 48ef06a7..3fec1061 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2330,6 +2330,7 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set. if (need_fix_single_sort_order) { + sort_order_count = 1; for (int column_n = 0; column_n < table->ColumnsCount; column_n++) if (column_n != column_with_smallest_sort_order) table->Columns[column_n].SortOrder = -1; From dc915c86ca8172c2836db676088f2da80b802866 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 2 Jun 2020 16:33:06 +0200 Subject: [PATCH 437/959] Tables: Fixed a manual resize path not marking settings as dirty, TableSortSpecsSanitize() doesn't need to test table->IsInitializing --- imgui_tables.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3fec1061..15287cd2 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1247,9 +1247,9 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // Rules: // - [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). - // - [Resize Rule 2] Resizing from right-side of a Stretch column before a fixed column froward sizing to left-side of fixed column. + // - [Resize Rule 2] Resizing from right-side of a Stretch column before a fixed column forward sizing to left-side of fixed column. // - [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to ensure that our left border won't move. - + table->IsSettingsDirty = true; if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed) { // [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to ensure @@ -1285,7 +1285,6 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f column_0->WidthRequest = column_0_width; TableUpdateColumnsWeightFromWidth(table); } - table->IsSettingsDirty = true; } // Columns where the contents didn't stray off their local clip rectangle can be merged into a same draw command. @@ -2294,6 +2293,8 @@ bool ImGui::TableGetColumnIsSorted(int column_n) void ImGui::TableSortSpecsSanitize(ImGuiTable* table) { + IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable); + // Clear SortOrder from hidden column and verify that there's no gap or duplicate. int sort_order_count = 0; ImU64 sort_order_mask = 0x00; @@ -2339,8 +2340,8 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) } } - // Fallback default sort order (if no column has the ImGuiTableColumnFlags_DefaultSort flag) - if (sort_order_count == 0 && table->IsInitializing) + // Fallback default sort order (if no column had the ImGuiTableColumnFlags_DefaultSort flag) + if (sort_order_count == 0) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; From 58411f27cba505d1f4959ff3cde857f118a09911 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 3 Jun 2020 19:42:43 +0200 Subject: [PATCH 438/959] Tables: Avoid TableGetSortSpecs() having a side-effect on sort specs sanitization. --- imgui_internal.h | 4 ++- imgui_tables.cpp | 75 ++++++++++++++++++++++++++++-------------------- 2 files changed, 47 insertions(+), 32 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index b9e1d889..0112685d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1938,7 +1938,7 @@ struct ImGuiTableColumn PrevVisibleColumn = NextVisibleColumn = -1; AutoFitQueue = CannotSkipItemsQueue = (1 << 3) - 1; // Skip for three frames SortOrder = -1; - SortDirection = ImGuiSortDirection_Ascending; + SortDirection = ImGuiSortDirection_None; } }; @@ -2020,6 +2020,7 @@ struct ImGuiTable bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). bool IsInitializing; bool IsSortSpecsDirty; + bool IsSortSpecsChangedForUser; // Reported to end-user via TableGetSortSpecs()->SpecsChanged and then clear. 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 IsSettingsRequestLoad; @@ -2265,6 +2266,7 @@ namespace ImGui IMGUI_API void TableDrawContextMenu(ImGuiTable* table, int column_n); IMGUI_API void TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* column, bool add_to_existing_sort_orders); IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); + IMGUI_API void TableSortSpecsBuild(ImGuiTable* table); IMGUI_API void TableBeginRow(ImGuiTable* table); IMGUI_API void TableEndRow(ImGuiTable* table); IMGUI_API void TableBeginCell(ImGuiTable* table, int column_n); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 15287cd2..a34ba34e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -546,6 +546,10 @@ static ImGuiTableColumnFlags TableFixColumnFlags(ImGuiTable* table, ImGuiTableCo static void TableFixColumnSortDirection(ImGuiTableColumn* column) { + // Initial sort state + if (column->SortDirection == ImGuiSortDirection_None) + column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); + // Handle NoSortAscending/NoSortDescending if (column->SortDirection == ImGuiSortDirection_Ascending && (column->Flags & ImGuiTableColumnFlags_NoSortAscending)) column->SortDirection = ImGuiSortDirection_Descending; @@ -872,6 +876,11 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 1); else inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false); + + // Sanitize and build sort specs before we have a change to use them for display. + // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change) + if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable)) + TableSortSpecsBuild(table); } // Process interaction on resizing borders. Actual size change will be applied in EndTable() @@ -2224,10 +2233,9 @@ void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* click if (column->SortOrder == -1 || !add_to_existing_sort_orders) column->SortOrder = add_to_existing_sort_orders ? sort_order_max + 1 : 0; } - else + else if (!add_to_existing_sort_orders) { - if (!add_to_existing_sort_orders) - column->SortOrder = -1; + column->SortOrder = -1; } TableFixColumnSortDirection(column); } @@ -2248,34 +2256,11 @@ const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() if (!(table->Flags & ImGuiTableFlags_Sortable)) return NULL; - // Flatten sort specs into user facing data - const bool was_dirty = table->IsSortSpecsDirty; - if (was_dirty) - { - TableSortSpecsSanitize(table); + if (table->IsSortSpecsDirty) + TableSortSpecsBuild(table); - // Write output - table->SortSpecsData.resize(table->SortSpecsCount); - table->SortSpecs.ColumnsMask = 0x00; - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - { - ImGuiTableColumn* column = &table->Columns[column_n]; - if (column->SortOrder == -1) - continue; - ImGuiTableSortSpecsColumn* sort_spec = &table->SortSpecsData[column->SortOrder]; - sort_spec->ColumnUserID = column->UserID; - sort_spec->ColumnIndex = (ImU8)column_n; - sort_spec->SortOrder = (ImU8)column->SortOrder; - sort_spec->SortDirection = column->SortDirection; - table->SortSpecs.ColumnsMask |= (ImU64)1 << column_n; - } - } - - // User facing data - table->SortSpecs.Specs = table->SortSpecsData.Data; - table->SortSpecs.SpecsCount = table->SortSpecsData.Size; - table->SortSpecs.SpecsChanged = was_dirty; - table->IsSortSpecsDirty = false; + table->SortSpecs.SpecsChanged = table->IsSortSpecsChangedForUser; + table->IsSortSpecsChangedForUser = false; return table->SortSpecs.SpecsCount ? &table->SortSpecs : NULL; } @@ -2345,10 +2330,11 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) for (int column_n = 0; column_n < table->ColumnsCount; column_n++) { ImGuiTableColumn* column = &table->Columns[column_n]; - if (!(column->Flags & ImGuiTableColumnFlags_NoSort) && column->IsVisible) + if (column->IsVisible && !(column->Flags & ImGuiTableColumnFlags_NoSort)) { sort_order_count = 1; column->SortOrder = 0; + TableFixColumnSortDirection(column); break; } } @@ -2356,6 +2342,33 @@ void ImGui::TableSortSpecsSanitize(ImGuiTable* table) table->SortSpecsCount = (ImS8)sort_order_count; } +void ImGui::TableSortSpecsBuild(ImGuiTable* table) +{ + IM_ASSERT(table->IsSortSpecsDirty); + TableSortSpecsSanitize(table); + + // Write output + table->SortSpecsData.resize(table->SortSpecsCount); + table->SortSpecs.ColumnsMask = 0x00; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + if (column->SortOrder == -1) + continue; + ImGuiTableSortSpecsColumn* sort_spec = &table->SortSpecsData[column->SortOrder]; + sort_spec->ColumnUserID = column->UserID; + sort_spec->ColumnIndex = (ImU8)column_n; + sort_spec->SortOrder = (ImU8)column->SortOrder; + sort_spec->SortDirection = column->SortDirection; + table->SortSpecs.ColumnsMask |= (ImU64)1 << column_n; + } + table->SortSpecs.Specs = table->SortSpecsData.Data; + table->SortSpecs.SpecsCount = table->SortSpecsData.Size; + + table->IsSortSpecsDirty = false; + table->IsSortSpecsChangedForUser = true; +} + //------------------------------------------------------------------------- // TABLE - .ini settings //------------------------------------------------------------------------- From b7416394684572b267ea53ba9c82ac120e17db78 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 10 Jun 2020 11:15:44 +0200 Subject: [PATCH 439/959] Tables: Fix rendering of row bg and line separators (#3293, broken by fixes #3163, code was accidently relying on SetCurrentChannel not updating rectangle) + Used shortcut in PushTableBackground/PopTableBackground --- imgui_tables.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index a34ba34e..ba9fcabb 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1316,7 +1316,7 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // matches, by e.g. calling SetCursorScreenPos(). // - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here.. // we could do better but it's going to be rare and probably not worth the hassle. -// Columns for which the draw chnanel(s) haven't been merged with other will use their own ImDrawCmd. +// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. // // This function is particularly tricky to understand.. take a breath. void ImGui::TableDrawMergeChannels(ImGuiTable* table) @@ -1658,7 +1658,10 @@ void ImGui::TableEndRow(ImGuiTable* table) } if (bg_col != 0 || border_col != 0) + { + window->DrawList->_CmdHeader.ClipRect = table->HostClipRect.ToVec4(); table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); + } // Draw background // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle @@ -1896,6 +1899,9 @@ void ImGui::PushTableBackground() ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiTable* table = g.CurrentTable; + + // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop + window->DrawList->_CmdHeader.ClipRect = table->HostClipRect.ToVec4(); table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); PushClipRect(table->HostClipRect.Min, table->HostClipRect.Max, false); } @@ -1906,6 +1912,10 @@ void ImGui::PopTableBackground() ImGuiWindow* window = g.CurrentWindow; ImGuiTable* table = g.CurrentTable; ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; + + // Set cmd header ahead to avoid SetCurrentChannel+PopClipRect doing an unnecessary AddDrawCmd/Pop + ImVec4 pop_clip_rect = window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 2]; + window->DrawList->_CmdHeader.ClipRect = pop_clip_rect; table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); PopClipRect(); } From 363eae94e6ccc73472f841f620ceb242cd20125b Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Jun 2020 17:27:51 +0200 Subject: [PATCH 440/959] Tables: Further fix #3293, #3163 + fixed for row unfreezing border not always showing due to unset clip rect. --- imgui.h | 4 ++-- imgui_demo.cpp | 4 ++-- imgui_internal.h | 1 + imgui_tables.cpp | 46 +++++++++++++++++++--------------------------- 4 files changed, 24 insertions(+), 31 deletions(-) diff --git a/imgui.h b/imgui.h index 122facf4..3d9898d6 100644 --- a/imgui.h +++ b/imgui.h @@ -1036,8 +1036,8 @@ enum ImGuiTableFlags_ ImGuiTableFlags_BordersVFullHeight = 1 << 11, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. // Padding, Sizing ImGuiTableFlags_NoClipX = 1 << 12, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow) - ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use WidthFixed or WidthAlwaysAutoResize policy. Read description above for more details. - ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use WidthStretch policy. Read description above for more details. + ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. + ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) ImGuiTableFlags_NoKeepColumnsVisible = 1 << 17, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index b55d5492..fab06d81 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3790,10 +3790,10 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyStretchX); // Can't specify both sizing polices so we clear the other - ImGui::SameLine(); HelpMarker("Default if _ScrollX if disabled."); + ImGui::SameLine(); HelpMarker("Default if _ScrollX if disabled. Makes columns use _WidthStretch policy by default."); if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyFixedX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyFixedX)) flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyFixedX); // Can't specify both sizing polices so we clear the other - ImGui::SameLine(); HelpMarker("Default if _ScrollX if enabled."); + ImGui::SameLine(); HelpMarker("Default if _ScrollX if enabled. Makes columns use _WidthFixed by default, or _WidthAlwaysAutoResize if _Resizable is not set."); ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_NoClipX", (unsigned int*)&flags, ImGuiTableFlags_NoClipX); diff --git a/imgui_internal.h b/imgui_internal.h index 0112685d..989570e2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1992,6 +1992,7 @@ struct ImGuiTable ImRect BackgroundClipRect; // We use this to cpu-clip cell background color fill ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. ImRect HostWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() + ImRect HostBackupClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground() ImVec2 HostCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() ImGuiWindow* OuterWindow; // Parent window for the table ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ba9fcabb..297c3ad4 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1626,6 +1626,8 @@ void ImGui::TableEndRow(ImGuiTable* table) const float bg_y1 = table->RowPosY1; const float bg_y2 = table->RowPosY2; + const bool unfreeze_rows = (table->CurrentRow + 1 == table->FreezeRowsCount && table->FreezeRowsCount > 0); + if (table->CurrentRow == 0) table->LastFirstRowHeight = bg_y2 - bg_y1; @@ -1657,8 +1659,11 @@ void ImGui::TableEndRow(ImGuiTable* table) } } - if (bg_col != 0 || border_col != 0) + const bool draw_stong_bottom_border = unfreeze_rows;// || (table->RowFlags & ImGuiTableRowFlags_Headers); + if (bg_col != 0 || border_col != 0 || draw_stong_bottom_border) { + // In theory we could call SetWindowClipRectBeforeChannelChange() but since we know TableEndRow() is + // always followed by a change of clipping rectangle we perform the smallest overwrite possible here. window->DrawList->_CmdHeader.ClipRect = table->HostClipRect.ToVec4(); table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); } @@ -1674,18 +1679,14 @@ void ImGui::TableEndRow(ImGuiTable* table) } // Draw top border - const float border_y = bg_y1; - if (border_col && border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y) - window->DrawList->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), border_col); - } - - const bool unfreeze_rows = (table->CurrentRow + 1 == table->FreezeRowsCount && table->FreezeRowsCount > 0); + if (border_col && bg_y1 >= table->BackgroundClipRect.Min.y && bg_y1 < table->BackgroundClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col); - // Draw bottom border (always strong) - const bool draw_separating_border = unfreeze_rows;// || (table->RowFlags & ImGuiTableRowFlags_Headers); - if (draw_separating_border) - if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y) - window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong); + // Draw bottom border at the row unfreezing mark (always strong) + if (draw_stong_bottom_border) + if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y) + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong); + } // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and @@ -1755,15 +1756,8 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n) } else { + SetWindowClipRectBeforeSetChannel(window, column->ClipRect); table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); - //window->ClipRect = column->ClipRect; - //IM_ASSERT(column->ClipRect.Max.x > column->ClipRect.Min.x && column->ClipRect.Max.y > column->ClipRect.Min.y); - //window->DrawList->_ClipRectStack.back() = ImVec4(column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y); - //window->DrawList->UpdateClipRect(); - window->DrawList->PopClipRect(); - window->DrawList->PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); - //IMGUI_DEBUG_LOG("%d (%.0f,%.0f)(%.0f,%.0f)\n", column_n, column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y); - window->ClipRect = window->DrawList->_ClipRectStack.back(); } } @@ -1900,10 +1894,10 @@ void ImGui::PushTableBackground() ImGuiWindow* window = g.CurrentWindow; ImGuiTable* table = g.CurrentTable; - // Set cmd header ahead to avoid SetCurrentChannel+PushClipRect doing an unnecessary AddDrawCmd/Pop - window->DrawList->_CmdHeader.ClipRect = table->HostClipRect.ToVec4(); + // Optimization: avoid SetCurrentChannel() + PushClipRect() + table->HostBackupClipRect = window->ClipRect; + SetWindowClipRectBeforeSetChannel(window, table->HostClipRect); table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); - PushClipRect(table->HostClipRect.Min, table->HostClipRect.Max, false); } void ImGui::PopTableBackground() @@ -1913,11 +1907,9 @@ void ImGui::PopTableBackground() ImGuiTable* table = g.CurrentTable; ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; - // Set cmd header ahead to avoid SetCurrentChannel+PopClipRect doing an unnecessary AddDrawCmd/Pop - ImVec4 pop_clip_rect = window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 2]; - window->DrawList->_CmdHeader.ClipRect = pop_clip_rect; + // Optimization: avoid PopClipRect() + SetCurrentChannel() + SetWindowClipRectBeforeSetChannel(window, table->HostBackupClipRect); table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent); - PopClipRect(); } // Output context menu into current window (generally a popup) From 8530b6af3dfcde4b0653b6ffccb2a34eab5bd7e4 Mon Sep 17 00:00:00 2001 From: omar Date: Sat, 13 Jun 2020 18:02:02 +0200 Subject: [PATCH 441/959] Tables: Not flagging whole column as SkipItems based on clipping visibility (breaks layout) --- imgui.h | 2 +- imgui_tables.cpp | 48 +++++++++++++++++++++++------------------------- 2 files changed, 24 insertions(+), 26 deletions(-) diff --git a/imgui.h b/imgui.h index 3d9898d6..df9cb8d8 100644 --- a/imgui.h +++ b/imgui.h @@ -672,7 +672,7 @@ namespace ImGui // - If you are using tables as a sort of grid, populating every columns with the same type of contents, // you may prefer using TableNextCell() instead of TableNextRow() + TableSetColumnIndex(). // - See Demo->Tables for details. - // - See ImGuiTableFlags_ enums for a description of available flags. + // - See ImGuiTableFlags_ and ImGuiTableColumnsFlags_ enums for a description of available flags. #define IMGUI_HAS_TABLE 1 IMGUI_API bool BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 297c3ad4..c7ab20aa 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -753,7 +753,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == visible_n) offset_x += work_rect.Min.x - table->OuterRect.Min.x; - if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n))) + if ((table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)) == 0) { // Hidden column: clear a few fields and we are done with it for the remainder of the function. // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. @@ -798,31 +798,27 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->ClipRect.ClipWithFull(host_clip_rect); column->IsClipped = (column->ClipRect.Max.x <= column->ClipRect.Min.x) && (column->AutoFitQueue & 1) == 0 && (column->CannotSkipItemsQueue & 1) == 0; - column->SkipItems = column->IsClipped || table->HostSkipItems; if (column->IsClipped) - { - // Columns with the _WidthAlwaysAutoResize sizing policy will never be updated then. - table->VisibleUnclippedMaskByIndex &= ~((ImU64)1 << column_n); - } - else - { - // Starting cursor position - column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1; - - // Alignment - // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in - // many cases (to be able to honor this we might be able to store a log of cells width, per row, for - // visible rows, but nav/programmatic scroll would have visible artifacts.) - //if (column->Flags & ImGuiTableColumnFlags_AlignRight) - // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->ContentWidthRowsUnfrozen); - //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) - // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f); - - // Reset content width variables - const float initial_max_pos_x = column->MinX + table->CellPaddingX1; - column->ContentMaxPosRowsFrozen = column->ContentMaxPosRowsUnfrozen = initial_max_pos_x; - column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersIdeal = initial_max_pos_x; - } + table->VisibleUnclippedMaskByIndex &= ~((ImU64)1 << column_n); // Columns with the _WidthAlwaysAutoResize sizing policy will never be updated then. + + column->SkipItems = !column->IsVisible || table->HostSkipItems; + + // Starting cursor position + column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1; + + // Alignment + // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in + // many cases (to be able to honor this we might be able to store a log of cells width, per row, for + // visible rows, but nav/programmatic scroll would have visible artifacts.) + //if (column->Flags & ImGuiTableColumnFlags_AlignRight) + // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->ContentWidthRowsUnfrozen); + //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter) + // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f); + + // Reset content width variables + const float initial_max_pos_x = column->MinX + table->CellPaddingX1; + column->ContentMaxPosRowsFrozen = column->ContentMaxPosRowsUnfrozen = initial_max_pos_x; + column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersIdeal = initial_max_pos_x; // Don't decrement auto-fit counters until container window got a chance to submit its items if (table->HostSkipItems == false) @@ -1798,6 +1794,7 @@ bool ImGui::TableNextCell() TableNextRow(); } + // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping. int column_n = table->CurrentColumn; return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; } @@ -1849,6 +1846,7 @@ bool ImGui::TableSetColumnIndex(int column_idx) TableBeginCell(table, column_idx); } + // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping. return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_idx)) != 0; } From 4c4882ffe4bbe8408437a1a8aa8f1520cba76a78 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 15 Jun 2020 15:24:59 +0200 Subject: [PATCH 442/959] Tables: Fixed channel merge when resizing columns with headers. Disable unnecessary and broken merge when using _NoClipX. --- imgui_internal.h | 2 +- imgui_tables.cpp | 73 ++++++++++++++++++++++++++---------------------- 2 files changed, 40 insertions(+), 35 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 989570e2..5523f2ca 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2263,8 +2263,8 @@ namespace ImGui IMGUI_API void TableSetColumnWidth(int column_n, float width); IMGUI_API void TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column, float width); IMGUI_API void TableDrawBorders(ImGuiTable* table); - IMGUI_API void TableDrawMergeChannels(ImGuiTable* table); IMGUI_API void TableDrawContextMenu(ImGuiTable* table, int column_n); + IMGUI_API void TableReorderDrawChannelsForMerge(ImGuiTable* table); IMGUI_API void TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* column, bool add_to_existing_sort_orders); IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); IMGUI_API void TableSortSpecsBuild(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index c7ab20aa..866b0a4c 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -82,7 +82,7 @@ // - [...] user emit contents // - EndTable() user ends the table // | TableDrawBorders() - draw outer borders, inner vertical borders -// | TableDrawMergeChannels() - merge draw channels if clipping isn't required +// | TableReorderDrawChannelsForMerge() - merge draw channels if clipping isn't required // | EndChild() - (if ScrollX/ScrollY is set) //----------------------------------------------------------------------------- @@ -991,9 +991,34 @@ void ImGui::EndTable() if ((flags & ImGuiTableFlags_Borders) != 0) TableDrawBorders(table); + // Store content width reference for each column (before attempting to merge draw calls) + const float backup_outer_cursor_pos_x = outer_window->DC.CursorPos.x; + const float backup_outer_max_pos_x = outer_window->DC.CursorMaxPos.x; + const float backup_inner_max_pos_x = inner_window->DC.CursorMaxPos.x; + float max_pos_x = backup_inner_max_pos_x; + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + + // Store content width (for both Headers and Rows) + //float ref_x = column->MinX; + float ref_x_rows = column->StartXRows - table->CellPaddingX1; + float ref_x_headers = column->StartXHeaders - table->CellPaddingX1; + column->ContentWidthRowsFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsFrozen - ref_x_rows); + column->ContentWidthRowsUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsUnfrozen - ref_x_rows); + column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers); + column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x_headers); + + // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. + if (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) + max_pos_x = ImMax(max_pos_x, column->MaxX + 1.0f); + } + // Flatten channels and merge draw calls table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0); - TableDrawMergeChannels(table); + if ((table->Flags & ImGuiTableFlags_NoClipX) == 0) + TableReorderDrawChannelsForMerge(table); + table->DrawSplitter.Merge(inner_window->DrawList); // When releasing a column being resized, scroll to keep the resulting column in sight const float min_column_width = TableGetMinColumnWidth(); @@ -1020,9 +1045,6 @@ void ImGui::EndTable() } // Layout in outer window - const float backup_outer_cursor_pos_x = outer_window->DC.CursorPos.x; - const float backup_outer_max_pos_x = outer_window->DC.CursorMaxPos.x; - const float backup_inner_max_pos_x = inner_window->DC.CursorMaxPos.x; inner_window->WorkRect = table->HostWorkRect; inner_window->SkipItems = table->HostSkipItems; outer_window->DC.CursorPos = table->OuterRect.Min; @@ -1039,26 +1061,6 @@ void ImGui::EndTable() ItemSize(item_size); } - // Store content width reference for each column - float max_pos_x = backup_inner_max_pos_x; - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - { - ImGuiTableColumn* column = &table->Columns[column_n]; - - // Store content width (for both Headers and Rows) - //float ref_x = column->MinX; - float ref_x_rows = column->StartXRows - table->CellPaddingX1; - float ref_x_headers = column->StartXHeaders - table->CellPaddingX1; - column->ContentWidthRowsFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsFrozen - ref_x_rows); - column->ContentWidthRowsUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsUnfrozen - ref_x_rows); - column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers); - column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x_headers); - - // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. - if (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) - max_pos_x = ImMax(max_pos_x, column->MaxX + 1.0f); - } - // Override EndChild/ItemSize max extent with our own to enable auto-resize on the X axis when possible // FIXME-TABLE: This can be improved (e.g. for Fixed columns we don't want to auto AutoFitWidth? or propagate window auto-fit to table?) if (table->Flags & ImGuiTableFlags_ScrollX) @@ -1292,9 +1294,13 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f } } -// Columns where the contents didn't stray off their local clip rectangle can be merged into a same draw command. -// To achieve this we merge their clip rect and make them contiguous in the channel list so they can be merged. -// This function first reorder the draw cmd which can be merged, by arranging them into a maximum of 4 distinct groups: +// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. +// +// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve +// this we merge their clip rect and make them contiguous in the channel list, so they can be merged +// by the call to DrawSplitter.Merge() following to the call to this function. +// +// We reorder draw commands by arranging them into a maximum of 4 distinct groups: // // 1 group: 2 groups: 2 groups: 4 groups: // [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 02 ] row+col freeze @@ -1303,8 +1309,10 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). // When the contents of a column didn't stray off its limit, we move its channels into the corresponding group // based on its position (within frozen rows/columns groups or not). -// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect, and they will be -// merged by the DrawSplitter.Merge() call. +// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect. +// +// This function assume that each column are pointing to a distinct draw channel, +// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask. // // Column channels will not be merged into one of the 1-4 groups in the following cases: // - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). @@ -1315,7 +1323,7 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. // // This function is particularly tricky to understand.. take a breath. -void ImGui::TableDrawMergeChannels(ImGuiTable* table) +void ImGui::TableReorderDrawChannelsForMerge(ImGuiTable* table) { ImGuiContext& g = *GImGui; ImDrawListSplitter* splitter = &table->DrawSplitter; @@ -1472,9 +1480,6 @@ void ImGui::TableDrawMergeChannels(ImGuiTable* table) IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size); memcpy(splitter->_Channels.Data + 1, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - 1) * sizeof(ImDrawChannel)); } - - // 3. Actually merge (channels using the same clip rect will be contiguous and naturally merged) - splitter->Merge(table->InnerWindow->DrawList); } // We use a default parameter of 'init_width_or_weight == -1' From 798aed729a0042bc1a544891bd2fde39475efff8 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 21:15:49 +0200 Subject: [PATCH 443/959] Tables: Added TableGetHoveredColumn(), extracted some context menu code out, simplifying TableAutoHeaders() toward aim of it being a user-land function. --- imgui.h | 1 + imgui_internal.h | 14 +++-- imgui_tables.cpp | 137 ++++++++++++++++++++++++++--------------------- 3 files changed, 87 insertions(+), 65 deletions(-) diff --git a/imgui.h b/imgui.h index df9cb8d8..f1e280f8 100644 --- a/imgui.h +++ b/imgui.h @@ -683,6 +683,7 @@ namespace ImGui IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Pass -1 to use current column. IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Pass -1 to use current column. + IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. // Tables: Headers & Columns declaration // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. // - The name passed to TableSetupColumn() is used by TableAutoHeaders() and by the context-menu diff --git a/imgui_internal.h b/imgui_internal.h index 5523f2ca..48d50230 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2002,7 +2002,7 @@ struct ImGuiTable ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() ImS8 SortSpecsCount; ImS8 DeclColumnsCount; // Count calls to TableSetupColumn() - ImS8 HoveredColumnBody; // [DEBUG] Unlike HoveredColumnBorder this doesn't fulfill all Hovering rules properly. Used for debugging/tools for now. + ImS8 HoveredColumnBody; // Index of column whose visible region is being hovered. Important: == ColumnsCount when hovering empty region after the right-most column! ImS8 HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). ImS8 ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0. ImS8 LastResizedColumn; // Index of column being resized from previous frame. @@ -2041,6 +2041,7 @@ struct ImGuiTable ContextPopupColumn = -1; ReorderColumn = -1; ResizedColumn = -1; + HoveredColumnBody = HoveredColumnBorder = -1; } }; @@ -2263,7 +2264,8 @@ namespace ImGui IMGUI_API void TableSetColumnWidth(int column_n, float width); IMGUI_API void TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column, float width); IMGUI_API void TableDrawBorders(ImGuiTable* table); - IMGUI_API void TableDrawContextMenu(ImGuiTable* table, int column_n); + IMGUI_API void TableDrawContextMenu(ImGuiTable* table); + IMGUI_API void TableOpenContextMenu(ImGuiTable* table, int column_n); IMGUI_API void TableReorderDrawChannelsForMerge(ImGuiTable* table); IMGUI_API void TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* column, bool add_to_existing_sort_orders); IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); @@ -2278,13 +2280,15 @@ namespace ImGui IMGUI_API void TableSetColumnAutofit(ImGuiTable* table, int column_n); IMGUI_API void PushTableBackground(); IMGUI_API void PopTableBackground(); + + // Tables - Settings + IMGUI_API void TableLoadSettings(ImGuiTable* table); + IMGUI_API void TableSaveSettings(ImGuiTable* table); + IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table); IMGUI_API void TableSettingsInstallHandler(ImGuiContext* context); IMGUI_API ImGuiTableSettings* TableSettingsCreate(ImGuiID id, int columns_count); IMGUI_API ImGuiTableSettings* TableSettingsFindByID(ImGuiID id); IMGUI_API void TableSettingsClearByID(ImGuiID id); - IMGUI_API void TableLoadSettings(ImGuiTable* table); - IMGUI_API void TableSaveSettings(ImGuiTable* table); - IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table); // Tab Bars IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 866b0a4c..0027b854 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -284,8 +284,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->FreezeColumnsCount = (inner_window->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); table->DeclColumnsCount = 0; - table->HoveredColumnBody = -1; - table->HoveredColumnBorder = -1; table->RightMostVisibleColumn = -1; // Using opaque colors facilitate overlapping elements of the grid @@ -571,8 +569,12 @@ static float TableGetMinColumnWidth() // for WidthAlwaysAutoResize columns? void ImGui::TableUpdateLayout(ImGuiTable* table) { + ImGuiContext& g = *GImGui; IM_ASSERT(table->IsLayoutLocked == false); + table->HoveredColumnBody = -1; + table->HoveredColumnBorder = -1; + // Compute offset, clip rect for the frame // (can't make auto padding larger than what WorkRect knows about so right-alignment matches) const ImRect work_rect = table->WorkRect; @@ -741,6 +743,10 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) width_remaining_for_stretched_columns -= 1.0f; } + // Detect hovered column + const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table->LastOuterHeight)); + const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0); + // Setup final position, offset and clipping rectangles int visible_n = 0; float offset_x = (table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x; @@ -803,6 +809,10 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->SkipItems = !column->IsVisible || table->HostSkipItems; + // Detect hovered column + if (is_hovering_table && g.IO.MousePos.x >= column->ClipRect.Min.x && g.IO.MousePos.x < column->ClipRect.Max.x) + table->HoveredColumnBody = (ImS8)column_n; + // Starting cursor position column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1; @@ -834,6 +844,16 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) visible_n++; } + // Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it) + if (is_hovering_table && table->HoveredColumnBody == -1) + { + float unused_x1 = table->WorkRect.Min.x; + if (table->RightMostVisibleColumn != -1) + unused_x1 = ImMax(unused_x1, table->Columns[table->RightMostVisibleColumn].ClipRect.Max.x); + if (g.IO.MousePos.x >= unused_x1) + table->HoveredColumnBody = (ImS8)table->ColumnsCount; + } + // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, // either because of using _WidthAlwaysAutoResize/_WidthStretch). // This will hide the resizing option from the context menu. @@ -857,7 +877,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) { if (BeginPopup("##TableContextMenu")) { - TableDrawContextMenu(table, table->ContextPopupColumn); + TableDrawContextMenu(table); EndPopup(); } else @@ -897,7 +917,6 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) const float hit_y1 = table->OuterRect.Min.y; const float hit_y2_full = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight); const float hit_y2 = borders_full_height ? hit_y2_full : (hit_y1 + table->LastFirstRowHeight); - const float mouse_x_hover_body = (g.IO.MousePos.y >= hit_y1 && g.IO.MousePos.y < hit_y2_full) ? g.IO.MousePos.x : FLT_MAX; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { @@ -906,13 +925,6 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; - - // Detect hovered column: - // - we perform an unusually low-level check here.. not using IsMouseHoveringRect() to avoid touch padding. - // - we don't care about the full set of IsItemHovered() feature either. - if (mouse_x_hover_body >= column->MinX && mouse_x_hover_body < column->MaxX) - table->HoveredColumnBody = (ImS8)column_n; - if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) continue; @@ -1798,9 +1810,12 @@ bool ImGui::TableNextCell() { TableNextRow(); } + int column_n = table->CurrentColumn; + + // FIXME-TABLE: Need to clarify if we want to allow IsItemHovered() here + //g.CurrentWindow->DC.LastItemStatusFlags = (column_n == table->HoveredColumn) ? ImGuiItemStatusFlags_HoveredRect : ImGuiItemStatusFlags_None; // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping. - int column_n = table->CurrentColumn; return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; } @@ -1851,6 +1866,9 @@ bool ImGui::TableSetColumnIndex(int column_idx) TableBeginCell(table, column_idx); } + // FIXME-TABLE: Need to clarify if we want to allow IsItemHovered() here + //g.CurrentWindow->DC.LastItemStatusFlags = (column_n == table->HoveredColumn) ? ImGuiItemStatusFlags_HoveredRect : ImGuiItemStatusFlags_None; + // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping. return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_idx)) != 0; } @@ -1917,7 +1935,7 @@ void ImGui::PopTableBackground() // Output context menu into current window (generally a popup) // FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? -void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) +void ImGui::TableDrawContextMenu(ImGuiTable* table) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; @@ -1925,7 +1943,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) return; bool want_separator = false; - selected_column_n = ImClamp(selected_column_n, -1, table->ColumnsCount - 1); + const int selected_column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1; // Sizing if (table->Flags & ImGuiTableFlags_Resizable) @@ -1983,28 +2001,44 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n) } } +// Use -1 to open menu not specific to a given column. +void ImGui::TableOpenContextMenu(ImGuiTable* table, int column_n) +{ + IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount); + if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) + { + table->IsContextPopupOpen = true; + table->ContextPopupColumn = (ImS8)column_n; + table->InstanceInteracted = table->InstanceCurrent; + OpenPopup("##TableContextMenu"); + } +} + // This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). -// The intent is that advanced users willing to create customized headers would not need to use this helper and may -// create their own. However presently this function uses too many internal structures/calls. +// The intent is that advanced users willing to create customized headers would not need to use this helper +// and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets. +// FIXME-TABLE: However presently this function uses too many internal structures/calls. void ImGui::TableAutoHeaders() { + ImGuiStyle& style = ImGui::GetStyle(); + ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); const int columns_count = table->ColumnsCount; // Calculate row height (for the unlikely case that labels may be are multi-line) + float row_y1 = GetCursorScreenPos().y; float row_height = GetTextLineHeight(); for (int column_n = 0; column_n < columns_count; column_n++) if (TableGetColumnIsVisible(column_n)) row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y); - row_height += g.Style.CellPadding.y * 2.0f; + row_height += style.CellPadding.y * 2.0f; // Open row TableNextRow(ImGuiTableRowFlags_Headers, row_height); - if (table->HostSkipItems) // Merely an optimization + if (table->HostSkipItems) // Merely an optimization, you may skip in your own code. return; // This for loop is constructed to not make use of internal functions, @@ -2027,64 +2061,35 @@ void ImGui::TableAutoHeaders() Checkbox("##", &b[column_n]); PopStyleVar(); PopID(); - SameLine(0.0f, g.Style.ItemInnerSpacing.x); + SameLine(0.0f, style.ItemInnerSpacing.x); } #endif - // [DEBUG] - //if (g.IO.KeyCtrl) { static char buf[32]; name = buf; ImGuiTableColumn* c = &table->Columns[column_n]; if (c->Flags & ImGuiTableColumnFlags_WidthStretch) ImFormatString(buf, 32, "%.3f>%.1f", c->ResizeWeight, c->WidthGiven); else ImFormatString(buf, 32, "%.1f", c->WidthGiven); } - // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them) + // - in your own code you may omit the PushID/PopID all-together, provided you know you know they won't collide + // - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier. PushID(table->InstanceCurrent * table->ColumnsCount + column_n); TableHeader(name); PopID(); // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden - if (IsMouseReleased(1) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + if (IsMouseReleased(1) && IsItemHovered()) open_context_popup = column_n; } - // FIXME-TABLE: This is not user-land code any more + need to explain WHY this is here! + // FIXME-TABLE: This is not user-land code any more + need to explain WHY this is here! (added in fa88f023) window->SkipItems = table->HostSkipItems; // Allow opening popup from the right-most section after the last column - // FIXME-TABLE: This is not user-land code any more... perhaps instead we should expose hovered column. - // and allow some sort of row-centric IsItemHovered() for full flexibility? - float unused_x1 = table->WorkRect.Min.x; - if (table->RightMostVisibleColumn != -1) - unused_x1 = ImMax(unused_x1, table->Columns[table->RightMostVisibleColumn].MaxX); - if (unused_x1 < table->WorkRect.Max.x) - { - // FIXME: We inherit ClipRect/SkipItem from last submitted column (active or not), let's temporarily override it. - // Because we don't perform any rendering here we just overwrite window->ClipRect used by logic. - window->ClipRect = table->InnerClipRect; - - ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; - window->DC.CursorPos = ImVec2(unused_x1, table->RowPosY1); - ImVec2 size = ImVec2(table->WorkRect.Max.x - window->DC.CursorPos.x, table->RowPosY2 - table->RowPosY1); - if (size.x > 0.0f && size.y > 0.0f) - { - InvisibleButton("##RemainingSpace", size); - window->DC.CursorPos.y -= g.Style.ItemSpacing.y; - window->DC.CursorMaxPos = backup_cursor_max_pos; // Don't feed back into the width of the Header row - - // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden. - if (IsMouseReleased(1) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) - open_context_popup = -1; - } - - window->ClipRect = window->DrawList->_ClipRectStack.back(); - } + // (We don't actually need to ImGuiHoveredFlags_AllowWhenBlockedByPopup because in reality this is generally + // not required anymore.. because popup opening code tends to be reacting on IsMouseReleased() and the click + // would already have closed any other popups!) + if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count && g.IO.MousePos.y >= row_y1 && g.IO.MousePos.y < row_y1 + row_height) + open_context_popup = -1; // Will open a non-column-specific popup. // Open Context Menu if (open_context_popup != INT_MAX) - if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) - { - table->IsContextPopupOpen = true; - table->ContextPopupColumn = (ImS8)open_context_popup; - table->InstanceInteracted = table->InstanceCurrent; - OpenPopup("##TableContextMenu"); - } + TableOpenContextMenu(table, open_context_popup); } // Emit a column header (text + optional sort order) @@ -2281,6 +2286,15 @@ bool ImGui::TableGetColumnIsSorted(int column_n) return (column->SortOrder != -1); } +int ImGui::TableGetHoveredColumn() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return -1; + return (int)table->HoveredColumnBody; +} + void ImGui::TableSortSpecsSanitize(ImGuiTable* table) { IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable); @@ -2679,7 +2693,10 @@ void ImGui::DebugNodeTable(ImGuiTable* table) GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); if (!open) return; - BulletText("OuterWidth: %.1f, InnerWidth: %.1f%s, ColumnsWidth: %.1f, AutoFitWidth: %.1f", table->OuterRect.GetWidth(), table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "", table->ColumnsTotalWidth, table->ColumnsAutoFitWidth); + BulletText("OuterWidth: %.1f, InnerWidth: %.1f%s", table->OuterRect.GetWidth(), table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : ""); + BulletText("ColumnsWidth: %.1f, AutoFitWidth: %.1f", table->ColumnsTotalWidth, table->ColumnsAutoFitWidth); + BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder); + BulletText("ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn); for (int n = 0; n < table->ColumnsCount; n++) { ImGuiTableColumn* column = &table->Columns[n]; From 7ca70dcb81c77c37b5e225d476c0fc82256735ae Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 17 Jun 2020 15:27:17 +0200 Subject: [PATCH 444/959] Tables: Using same seed ID regardless of when using a child window or not. --- imgui_tables.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 0027b854..8e9cb702 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -216,6 +216,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->OuterRect = outer_rect; table->WorkRect = outer_rect; + // When not using a child window, WorkRect.Max will grow as we append contents. if (use_child_window) { // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent @@ -241,11 +242,9 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->WorkRect = table->InnerWindow->WorkRect; table->OuterRect = table->InnerWindow->Rect(); } - else - { - // WorkRect.Max will grow as we append contents. - PushID(instance_id); - } + + // Push a standardized ID for both child and not-child using tables, equivalent to BeginTable() doing PushID(label) matching + PushOverrideID(instance_id); // Backup a copy of host window members we will modify ImGuiWindow* inner_window = table->InnerWindow; @@ -1057,6 +1056,8 @@ void ImGui::EndTable() } // Layout in outer window + IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table->ID + table->InstanceCurrent, "Mismatching PushID/PopID!"); + PopID(); inner_window->WorkRect = table->HostWorkRect; inner_window->SkipItems = table->HostSkipItems; outer_window->DC.CursorPos = table->OuterRect.Min; @@ -1067,7 +1068,6 @@ void ImGui::EndTable() } else { - PopID(); ImVec2 item_size = table->OuterRect.GetSize(); item_size.x = table->ColumnsTotalWidth; ItemSize(item_size); From 27e779b3efbad1b20a24c6fac6641431ad8ad3e7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 16 Jun 2020 23:40:06 +0200 Subject: [PATCH 445/959] Tables: Removed dubious window->SkipItem assignment in TableAutoHeaders(). --- imgui_tables.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 8e9cb702..1fad48b7 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2023,7 +2023,7 @@ void ImGui::TableAutoHeaders() ImGuiStyle& style = ImGui::GetStyle(); ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + //ImGuiWindow* window = g.CurrentWindow; ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); const int columns_count = table->ColumnsCount; @@ -2078,7 +2078,7 @@ void ImGui::TableAutoHeaders() } // FIXME-TABLE: This is not user-land code any more + need to explain WHY this is here! (added in fa88f023) - window->SkipItems = table->HostSkipItems; + //window->SkipItems = table->HostSkipItems; // Allow opening popup from the right-most section after the last column // (We don't actually need to ImGuiHoveredFlags_AllowWhenBlockedByPopup because in reality this is generally From 745d8cdb497ca77e03e3d2c4136492756b398bda Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 17:28:06 +0200 Subject: [PATCH 446/959] Tables: Made TableHeader() responsible for opening per-column context menu to move responsibility away from TableAutoHeaders(). --- imgui_demo.cpp | 3 +-- imgui_tables.cpp | 35 ++++++++++++++++------------------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index fab06d81..35844b88 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3960,13 +3960,12 @@ static void ShowDemoWindowTables() } // Demonstrate using TableHeader() calls instead of TableAutoHeaders() - // FIXME-TABLE: Currently this doesn't get us feature-parity with TableAutoHeaders(), e.g. missing context menu. Tables API needs some work! if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Custom headers")) { const int COLUMNS_COUNT = 3; - if (ImGui::BeginTable("##table1", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable)) + if (ImGui::BeginTable("##table1", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) { ImGui::TableSetupColumn("Apricot"); ImGui::TableSetupColumn("Banana"); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 1fad48b7..accc75f3 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -874,7 +874,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Context menu if (table->IsContextPopupOpen && table->InstanceCurrent == table->InstanceInteracted) { - if (BeginPopup("##TableContextMenu")) + const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID); + if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings)) { TableDrawContextMenu(table); EndPopup(); @@ -2010,20 +2011,19 @@ void ImGui::TableOpenContextMenu(ImGuiTable* table, int column_n) table->IsContextPopupOpen = true; table->ContextPopupColumn = (ImS8)column_n; table->InstanceInteracted = table->InstanceCurrent; - OpenPopup("##TableContextMenu"); + const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID); + OpenPopupEx(context_menu_id, ImGuiPopupFlags_None); } } // This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). // The intent is that advanced users willing to create customized headers would not need to use this helper // and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets. -// FIXME-TABLE: However presently this function uses too many internal structures/calls. void ImGui::TableAutoHeaders() { ImGuiStyle& style = ImGui::GetStyle(); ImGuiContext& g = *GImGui; - //ImGuiWindow* window = g.CurrentWindow; ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); const int columns_count = table->ColumnsCount; @@ -2043,7 +2043,6 @@ void ImGui::TableAutoHeaders() // This for loop is constructed to not make use of internal functions, // as this is intended to be a base template to copy and build from. - int open_context_popup = INT_MAX; for (int column_n = 0; column_n < columns_count; column_n++) { if (!TableSetColumnIndex(column_n)) @@ -2071,25 +2070,19 @@ void ImGui::TableAutoHeaders() PushID(table->InstanceCurrent * table->ColumnsCount + column_n); TableHeader(name); PopID(); - - // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden - if (IsMouseReleased(1) && IsItemHovered()) - open_context_popup = column_n; } // FIXME-TABLE: This is not user-land code any more + need to explain WHY this is here! (added in fa88f023) //window->SkipItems = table->HostSkipItems; - // Allow opening popup from the right-most section after the last column - // (We don't actually need to ImGuiHoveredFlags_AllowWhenBlockedByPopup because in reality this is generally - // not required anymore.. because popup opening code tends to be reacting on IsMouseReleased() and the click - // would already have closed any other popups!) - if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count && g.IO.MousePos.y >= row_y1 && g.IO.MousePos.y < row_y1 + row_height) - open_context_popup = -1; // Will open a non-column-specific popup. - - // Open Context Menu - if (open_context_popup != INT_MAX) - TableOpenContextMenu(table, open_context_popup); + // Allow opening popup from the right-most section after the last column. + // (We don't actually need to use ImGuiHoveredFlags_AllowWhenBlockedByPopup because in reality this is generally + // not required anymore.. because popup opening code tends to be reacting on IsMouseReleased() and the click would + // already have closed any other popups!) + // FIXME-TABLE: TableOpenContextMenu() is not public yet. + if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count) + if (g.IO.MousePos.y >= row_y1 && g.IO.MousePos.y < row_y1 + row_height) + TableOpenContextMenu(table, -1); // Will open a non-column-specific popup. } // Emit a column header (text + optional sort order) @@ -2214,6 +2207,10 @@ void ImGui::TableHeader(const char* label) column->ContentMaxPosHeadersIdeal = ImMax(column->ContentMaxPosHeadersIdeal, max_pos_x); PopID(); + + // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden + if (IsMouseReleased(1) && IsItemHovered()) + TableOpenContextMenu(table, column_n); } void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* clicked_column, bool add_to_existing_sort_orders) From 353bb68e904cab6dc324105bef778e0731dc3934 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 19 Jun 2020 15:39:56 +0200 Subject: [PATCH 447/959] Tables: Demo custom per-popup popups, demonstrate TableGetHoveredColumn() and ImGuiPopupFlags_NoOpenOverExistingPopup. --- imgui_demo.cpp | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 35844b88..9f789b40 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4006,6 +4006,70 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } + // Demonstrate creating custom context menus inside columns, while playing it nice with context menus provided by TableHeader()/TableAutoHeaders() + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Context menus")) + { + HelpMarker("By default, TableHeader()/TableAutoHeaders() will open a context-menu on right-click."); + ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders; + const int COLUMNS_COUNT = 3; + if (ImGui::BeginTable("##table1", COLUMNS_COUNT, flags)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + + // Context Menu 1: right-click on header (including empty section after the third column!) should open Default Table Popup + ImGui::TableAutoHeaders(); + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::PushID(row * COLUMNS_COUNT + column); + ImGui::Text("Cell %d,%d", column, row); + ImGui::SameLine(); + + // Context Menu 2: right-click on buttons open Custom Button Popup + ImGui::SmallButton(".."); + if (ImGui::BeginPopupContextItem()) + { + ImGui::Text("This is the popup for Button() On Cell %d,%d", column, row); + ImGui::Selectable("Close"); + ImGui::EndPopup(); + } + ImGui::PopID(); + } + } + + // Context Menu 3: Right-click anywhere in columns opens a custom popup + // We use the ImGuiPopupFlags_NoOpenOverExistingPopup flag to avoid displaying over either the standard TableHeader context-menu or the Button context-menu. + const int hovered_column = ImGui::TableGetHoveredColumn(); + for (int column = 0; column < COLUMNS_COUNT + 1; column++) + { + ImGui::PushID(column); + if (hovered_column == column && ImGui::IsMouseReleased(1)) + ImGui::OpenPopup("MyPopup", ImGuiPopupFlags_NoOpenOverExistingPopup); + if (ImGui::BeginPopup("MyPopup")) + { + if (column == COLUMNS_COUNT) + ImGui::Text("This is the popup for unused space after the last column."); + else + ImGui::Text("This is the popup for Column '%s'", ImGui::TableGetColumnName(column)); + ImGui::Selectable("Close"); + ImGui::EndPopup(); + } + ImGui::PopID(); + } + + ImGui::EndTable(); + ImGui::Text("TableGetHoveredColumn() returned: %d", hovered_column); + } + ImGui::TreePop(); + } + static const char* template_items_names[] = { "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", From 03c8bfaf23d2ec18b969abdfba6383ae89b6fe81 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 2 Jul 2020 13:59:30 +0200 Subject: [PATCH 448/959] Tables: Removed extra +1.0f pixels initially allocated to make right-most column visible, fix visible padding asymmetry. Tweaked debug code in demo. Seems visible enough without. Whole thing is/was fishy, may return to it but right cleaning up seems viable. --- imgui_demo.cpp | 47 +++++++++++++++++++++++++++-------------------- imgui_tables.cpp | 14 +++++++------- 2 files changed, 34 insertions(+), 27 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9f789b40..391ec248 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3416,22 +3416,27 @@ static void ShowDemoWindowTables() for (int column = 0; column < 3; column++) { ImGui::TableSetColumnIndex(column); + char buf[32]; if (display_width) { + // [DEBUG] Draw limits ImVec2 p = ImGui::GetCursorScreenPos(); - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - float x1 = p.x; - float x2 = ImGui::GetWindowPos().x + ImGui::GetContentRegionMax().x; - float x3 = draw_list->GetClipRectMax().x; - float y2 = p.y + ImGui::GetTextLineHeight(); - draw_list->AddLine(ImVec2(x1, y2), ImVec2(x3, y2), IM_COL32(255, 255, 0, 255)); // Hard clipping limit - draw_list->AddLine(ImVec2(x1, y2), ImVec2(x2, y2), IM_COL32(255, 0, 0, 255)); // Normal limit - ImGui::Text("w=%.2f", x2 - x1); + float contents_x1 = p.x; + float contents_x2 = ImGui::GetWindowPos().x + ImGui::GetContentRegionMax().x; + float cliprect_x1 = ImGui::GetWindowDrawList()->GetClipRectMin().x; + float cliprect_x2 = ImGui::GetWindowDrawList()->GetClipRectMax().x; + float y1 = p.y; + float y2 = p.y + ImGui::GetTextLineHeight() + 2.0f; + ImDrawList* fg_draw_list = ImGui::GetForegroundDrawList(); + fg_draw_list->AddRect(ImVec2(contents_x1, y1 + 0.0f), ImVec2(contents_x2, y2 + 0.0f), IM_COL32(255, 0, 0, 255)); // Contents limit (e.g. Cell + Padding) + fg_draw_list->AddLine(ImVec2(cliprect_x1, y2 + 1.0f), ImVec2(cliprect_x2, y2 + 1.0f), IM_COL32(255, 255, 0, 255)); // Hard clipping limit + sprintf(buf, "w=%.2f", contents_x2 - contents_x1); } else { - ImGui::Text("Hello %d,%d", row, column); + sprintf(buf, "Hello %d,%d", row, column); } + ImGui::TextUnformatted(buf); } } ImGui::EndTable(); @@ -3776,10 +3781,10 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Sizing policies, cell contents")) { HelpMarker("This section allows you to interact and see the effect of StretchX vs FixedX sizing policies depending on whether Scroll is enabled and the contents of your columns."); - enum ContentsType { CT_ShortText, CT_LongText, CT_Button, CT_StretchButton, CT_InputText }; - static int contents_type = CT_StretchButton; + enum ContentsType { CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText }; + static int contents_type = CT_FillButton; ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - ImGui::Combo("Contents", &contents_type, "Short Text\0Long Text\0Button\0Stretch Button\0InputText\0"); + ImGui::Combo("Contents", &contents_type, "Short Text\0Long Text\0Button\0Fill Button\0InputText\0"); static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; ImGui::CheckboxFlags("ImGuiTableFlags_BordersHInner", (unsigned int*)&flags, ImGuiTableFlags_BordersHInner); @@ -3810,11 +3815,11 @@ static void ShowDemoWindowTables() sprintf(label, "Hello %d,%d", row, column); switch (contents_type) { - case CT_ShortText: ImGui::TextUnformatted(label); break; - case CT_LongText: ImGui::Text("Some longer text %d,%d\nOver two lines..", row, column); break; - case CT_Button: ImGui::Button(label); break; - case CT_StretchButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break; - case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_ARRAYSIZE(text_buf)); break; + case CT_ShortText: ImGui::TextUnformatted(label); break; + case CT_LongText: ImGui::Text("Some longer text %d,%d\nOver two lines..", row, column); break; + case CT_Button: ImGui::Button(label); break; + case CT_FillButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break; + case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_ARRAYSIZE(text_buf)); break; } } } @@ -4163,9 +4168,9 @@ static void ShowDemoWindowTables() | ImGuiTableFlags_SizingPolicyFixedX ; - enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_Selectable }; - static int contents_type = CT_Button; - const char* contents_type_names[] = { "Text", "Button", "SmallButton", "Selectable" }; + enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable }; + static int contents_type = CT_FillButton; + const char* contents_type_names[] = { "Text", "Button", "SmallButton", "FillButton", "Selectable" }; static int items_count = IM_ARRAYSIZE(template_items_names); static ImVec2 outer_size_value = ImVec2(0, 250); @@ -4354,6 +4359,8 @@ static void ShowDemoWindowTables() ImGui::Button(label); else if (contents_type == CT_SmallButton) ImGui::SmallButton(label); + else if (contents_type == CT_FillButton) + ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); else if (contents_type == CT_Selectable) { if (ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap, ImVec2(0, row_min_height))) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index accc75f3..3c0e6f33 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -70,10 +70,11 @@ // | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of weighted columns) from their respective width // - TableSetupColumn() user submit columns details (optional) // - TableAutoHeaders() or TableHeader() user submit a headers row (optional) -// | TableSortSpecsClickColumn() - when clicked: alter sort order and sort direction +// | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction +// | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu // - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) // - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders() -// | TableUpdateLayout() - lock all widths and columns positions! called by the FIRST call to TableNextRow()! +// | TableUpdateLayout() - lock all widths, columns positions, clipping rectangles. called by the FIRST call to TableNextRow()! // | - TableUpdateDrawChannels() - setup ImDrawList channels // | - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission // | - TableDrawContextMenu() - draw right-click context menu @@ -650,13 +651,12 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->ColumnsAutoFitWidth += spacing_auto_x * (table->ColumnsVisibleCount - 1); // Layout - // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible const float width_spacings = table->CellSpacingX * (table->ColumnsVisibleCount - 1); float width_avail; if ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) - width_avail = table->InnerClipRect.GetWidth() - width_spacings - 1.0f; + width_avail = table->InnerClipRect.GetWidth() - width_spacings; else - width_avail = work_rect.GetWidth() - width_spacings - 1.0f; + width_avail = work_rect.GetWidth() - width_spacings; const float width_avail_for_stretched_columns = width_avail - sum_width_fixed_requests; float width_remaining_for_stretched_columns = width_avail_for_stretched_columns; @@ -1023,7 +1023,7 @@ void ImGui::EndTable() // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge. if (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) - max_pos_x = ImMax(max_pos_x, column->MaxX + 1.0f); + max_pos_x = ImMax(max_pos_x, column->MaxX); } // Flatten channels and merge draw calls @@ -1079,7 +1079,7 @@ void ImGui::EndTable() if (table->Flags & ImGuiTableFlags_ScrollX) { inner_window->DC.CursorMaxPos.x = max_pos_x; // Set contents width for scrolling - outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos_x, backup_outer_cursor_pos_x + table->ColumnsTotalWidth + 1.0f + inner_window->ScrollbarSizes.x); // For auto-fit + outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos_x, backup_outer_cursor_pos_x + table->ColumnsTotalWidth + inner_window->ScrollbarSizes.x); // For auto-fit } else { From fcdfde2bc62b9da01bf7e208c303aa4e5a27b57a Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 2 Jul 2020 18:59:02 +0200 Subject: [PATCH 449/959] Tables: Extracted border size into a named variable. --- imgui_tables.cpp | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3c0e6f33..2de7fc89 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -88,6 +88,7 @@ //----------------------------------------------------------------------------- // Configuration +static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded. static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders. static const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f; // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped. @@ -1110,6 +1111,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) ImDrawList* outer_drawlist = outer_window->DrawList; // Draw inner border and resizing feedback + const float border_size = TABLE_BORDER_SIZE; const float draw_y1 = table->OuterRect.Min.y; float draw_y2_base = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight; float draw_y2_full = table->OuterRect.Max.y; @@ -1125,7 +1127,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) } if ((table->Flags & ImGuiTableFlags_BordersVOuter) && (table->InnerWindow == table->OuterWindow)) - inner_drawlist->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, 1.0f); + inner_drawlist->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, border_size); if (table->Flags & ImGuiTableFlags_BordersVInner) { @@ -1154,7 +1156,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) float draw_y2 = draw_y2_base; if (is_hovered || is_resized || (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1)) draw_y2 = draw_y2_full; - inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, 1.0f); + inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size); } } } @@ -1172,16 +1174,18 @@ void ImGui::TableDrawBorders(ImGuiTable* table) if (inner_window != outer_window) outer_border.Expand(1.0f); if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) - outer_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col); + { + outer_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, ~0, border_size); + } else if (table->Flags & ImGuiTableFlags_BordersVOuter) { - outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col); - outer_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col); + outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size); + outer_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size); } else if (table->Flags & ImGuiTableFlags_BordersHOuter) { - outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col); - outer_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col); + outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size); + outer_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size); } } if ((table->Flags & ImGuiTableFlags_BordersHInner) && table->RowPosY2 < table->OuterRect.Max.y) @@ -1189,7 +1193,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) // Draw bottom-most row border const float border_y = table->RowPosY2; if (border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y) - inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight); + inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight, border_size); } } @@ -1656,6 +1660,7 @@ void ImGui::TableEndRow(ImGuiTable* table) // Decide of top border color ImU32 border_col = 0; + const float border_size = TABLE_BORDER_SIZE; if (table->CurrentRow != 0 || table->InnerWindow == table->OuterWindow) { if (table->Flags & ImGuiTableFlags_BordersHInner) @@ -1694,12 +1699,12 @@ void ImGui::TableEndRow(ImGuiTable* table) // Draw top border if (border_col && bg_y1 >= table->BackgroundClipRect.Min.y && bg_y1 < table->BackgroundClipRect.Max.y) - window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col); + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col, border_size); // Draw bottom border at the row unfreezing mark (always strong) if (draw_stong_bottom_border) if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y) - window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong); + window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size); } // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) From 57916b891bdeacd44f084335e9780d1e5b44e5f8 Mon Sep 17 00:00:00 2001 From: omar Date: Thu, 2 Jul 2020 21:41:29 +0200 Subject: [PATCH 450/959] Tables: Simplified TableHeader() and not relying on Selectable(), fixed various padding issues. Added work-around for CellRect.Min.x offset by CellSpacing.x. --- imgui_tables.cpp | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2de7fc89..98f18176 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2117,25 +2117,27 @@ void ImGui::TableHeader(const char* label) // If we already got a row height, there's use that. ImRect cell_r = TableGetCellRect(); + cell_r.Min.x -= table->CellSpacingX; // FIXME-TABLE: TableGetCellRect() is misleading. float label_height = ImMax(label_size.y, table->RowMinHeight - g.Style.CellPadding.y * 2.0f); //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG] - ImRect work_r = cell_r; - work_r.Min.x = window->DC.CursorPos.x; - work_r.Max.y = work_r.Min.y + label_height; - float ellipsis_max = work_r.Max.x; - - // Selectable - PushID(label); - - // FIXME-TABLE: Fix when padding are disabled. - //window->DC.CursorPos.x = column->MinX + table->CellPadding.x; // Keep header highlighted when context menu is open. // (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...) const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent); - const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld | ImGuiSelectableFlags_DontClosePopups, ImVec2(0.0f, label_height)); - const bool held = IsItemActive(); + ImGuiID id = window->GetID(label); + ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f)); + if (!ItemAdd(bb, id)) + return; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); + if (hovered || selected) + { + const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb.Min, bb.Max, col, false, 0.0f); + RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); + } if (held) table->HeldHeaderColumn = (ImS8)column_n; window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f; @@ -2164,6 +2166,7 @@ void ImGui::TableHeader(const char* label) // Sort order arrow float w_arrow = 0.0f; float w_sort_text = 0.0f; + float ellipsis_max = cell_r.Max.x; if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort)) { const float ARROW_SCALE = 0.65f; @@ -2179,7 +2182,7 @@ void ImGui::TableHeader(const char* label) w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x; } - float x = ImMax(cell_r.Min.x, work_r.Max.x - w_arrow - w_sort_text); + float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text); ellipsis_max -= w_arrow + w_sort_text; float y = label_pos.y; @@ -2208,11 +2211,9 @@ void ImGui::TableHeader(const char* label) // for merging. // FIXME-TABLE: Clarify policies of how label width and potential decorations (arrows) fit into auto-resize of the column float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow; - column->ContentMaxPosHeadersUsed = ImMax(column->ContentMaxPosHeadersUsed, work_r.Max.x);// ImMin(max_pos_x, work_r.Max.x)); + column->ContentMaxPosHeadersUsed = ImMax(column->ContentMaxPosHeadersUsed, cell_r.Max.x);// ImMin(max_pos_x, cell_r.Max.x)); column->ContentMaxPosHeadersIdeal = ImMax(column->ContentMaxPosHeadersIdeal, max_pos_x); - PopID(); - // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden if (IsMouseReleased(1) && IsItemHovered()) TableOpenContextMenu(table, column_n); From c96c84b6dcac2aaea8c63fc71336f93ae9dc3e27 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 17 Jul 2020 22:39:28 +0200 Subject: [PATCH 451/959] Tables: Store submitted column width and avoid saving default default widths. --- imgui_internal.h | 1 + imgui_tables.cpp | 32 ++++++++++++++++++-------------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 48d50230..0f2d0c68 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1897,6 +1897,7 @@ struct ImGuiTableColumn ImGuiTableColumnFlags Flags; // Effective flags. See ImGuiTableColumnFlags_ float MinX; // Absolute positions float MaxX; + float WidthOrWeightInitValue; // Value passed to TableSetupColumn() float WidthStretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from WidthStretchWeight in TableUpdateLayout() float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be >WidthRequest to honor minimum width, may be Flags; // Initialize defaults - // FIXME-TABLE: We don't restore widths/weight so let's avoid using IsSettingsLoaded for now - if (table->IsInitializing && column->WidthRequest < 0.0f && column->WidthStretchWeight < 0.0f)// && !table->IsSettingsLoaded) + if (flags & ImGuiTableColumnFlags_WidthStretch) + { + IM_ASSERT(init_width_or_weight != 0.0f && "Need to provide a valid weight!"); + if (init_width_or_weight < 0.0f) + init_width_or_weight = 1.0f; + } + column->WidthOrWeightInitValue = init_width_or_weight; + if (table->IsInitializing && column->WidthRequest < 0.0f && column->WidthStretchWeight < 0.0f) { // Init width or weight - // Disable auto-fit if a default fixed width has been specified if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) { + // Disable auto-fit if a default fixed width has been specified column->WidthRequest = init_width_or_weight; column->AutoFitQueue = 0x00; } if (flags & ImGuiTableColumnFlags_WidthStretch) - { - IM_ASSERT(init_width_or_weight < 0.0f || init_width_or_weight > 0.0f); - column->WidthStretchWeight = (init_width_or_weight < 0.0f ? 1.0f : init_width_or_weight); - } + column->WidthStretchWeight = init_width_or_weight; else - { column->WidthStretchWeight = 1.0f; - } } if (table->IsInitializing) { @@ -2087,7 +2088,7 @@ void ImGui::TableAutoHeaders() // FIXME-TABLE: TableOpenContextMenu() is not public yet. if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count) if (g.IO.MousePos.y >= row_y1 && g.IO.MousePos.y < row_y1 + row_height) - TableOpenContextMenu(table, -1); // Will open a non-column-specific popup. + TableOpenContextMenu(table, -1); // Will open a non-column-specific popup. } // Emit a column header (text + optional sort order) @@ -2475,12 +2476,12 @@ void ImGui::TableSaveSettings(ImGuiTable* table) ImGuiTableColumn* column = table->Columns.Data; ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); - // FIXME-TABLE: Logic to avoid saving default widths? bool save_ref_scale = false; - settings->SaveFlags = ImGuiTableFlags_Resizable; + settings->SaveFlags = ImGuiTableFlags_None; for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++) { - column_settings->WidthOrWeight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->WidthStretchWeight : column->WidthRequest; + const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->WidthStretchWeight : column->WidthRequest; + column_settings->WidthOrWeight = width_or_weight; column_settings->Index = (ImS8)n; column_settings->DisplayOrder = column->DisplayOrder; column_settings->SortOrder = column->SortOrder; @@ -2490,8 +2491,11 @@ void ImGui::TableSaveSettings(ImGuiTable* table) if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0) save_ref_scale = true; - // We skip saving some data in the .ini file when they are unnecessary to restore our state + // We skip saving some data in the .ini file when they are unnecessary to restore our state. + // Note that fixed width where initial width was derived from auto-fit will always be saved as WidthOrWeightInitValue will be 0.0f. // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. + if (width_or_weight != column->WidthOrWeightInitValue) + settings->SaveFlags |= ImGuiTableFlags_Resizable; if (column->DisplayOrder != n) settings->SaveFlags |= ImGuiTableFlags_Reorderable; if (column->SortOrder != -1) From a0e6aa1766f161054efc7b421cfa8b3029cca1d1 Mon Sep 17 00:00:00 2001 From: omar Date: Fri, 17 Jul 2020 23:23:04 +0200 Subject: [PATCH 452/959] Tables: Fix calculation of auto-fit (remove padding). Demo setting a width in columns setup + ImGuiTableFlags_NoKeepColumnsVisible. --- imgui.h | 2 +- imgui_demo.cpp | 28 ++++++++++++++++++++++++++++ imgui_tables.cpp | 9 ++++----- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/imgui.h b/imgui.h index f1e280f8..c72757ad 100644 --- a/imgui.h +++ b/imgui.h @@ -1041,7 +1041,7 @@ enum ImGuiTableFlags_ ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) - ImGuiTableFlags_NoKeepColumnsVisible = 1 << 17, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small. + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 17, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. // Scrolling ImGuiTableFlags_ScrollX = 1 << 18, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. ImGuiTableFlags_ScrollY = 1 << 19, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 391ec248..2d8fa1a0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3596,6 +3596,32 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Explicit widths")) + { + static ImGuiTableFlags flags = ImGuiTableFlags_None; + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", (unsigned int*)&flags, ImGuiTableFlags_NoKeepColumnsVisible); + if (ImGui::BeginTable("##table1", 3, flags)) + { + // We could also set ImGuiTableFlags_SizingPolicyFixedX on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 200.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f); + for (int row = 0; row < 5; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < 3; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("Hello %d,%d", row, column); + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Vertical scrolling, with clipping")) @@ -4223,6 +4249,8 @@ static void ShowDemoWindowTables() ImGui::SameLine(); HelpMarker("[Default if ScrollX is on]\nEnlarge as needed: enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rectangle. Only Fixed columns allowed. Stretched columns will calculate their width assuming no scrolling."); ImGui::CheckboxFlags("ImGuiTableFlags_NoHeadersWidth", (unsigned int*)&flags, ImGuiTableFlags_NoHeadersWidth); ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", (unsigned int*)&flags, ImGuiTableFlags_NoHostExtendY); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", (unsigned int*)&flags, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled."); ImGui::Unindent(); ImGui::BulletText("Scrolling:"); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ab5c1803..2ead3fd8 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -580,7 +580,6 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // (can't make auto padding larger than what WorkRect knows about so right-alignment matches) const ImRect work_rect = table->WorkRect; const float padding_auto_x = table->CellPaddingX2; - const float spacing_auto_x = table->CellSpacingX * (1.0f + 2.0f); // CellSpacingX is >0.0f when there's no vertical border, in which case we add two extra CellSpacingX to make auto-fit look nice instead of cramped. We may want to expose this somehow. const float min_column_width = TableGetMinColumnWidth(); int count_fixed = 0; @@ -614,7 +613,11 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (!(table->Flags & ImGuiTableFlags_NoHeadersWidth) && !(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth)) column_width_ideal = ImMax(column_width_ideal, column_content_width_headers); column_width_ideal = ImMax(column_width_ideal + padding_auto_x, min_column_width); + + // CellSpacingX is >0.0f when there's no vertical border table->ColumnsAutoFitWidth += column_width_ideal; + if (column->PrevVisibleColumn != -1) + table->ColumnsAutoFitWidth += table->CellSpacingX; if (column->Flags & (ImGuiTableColumnFlags_WidthAlwaysAutoResize | ImGuiTableColumnFlags_WidthFixed)) { @@ -647,10 +650,6 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } } - // CellSpacingX is >0.0f when there's no vertical border, in which case we add two extra CellSpacingX to make auto-fit look nice instead of cramped. - // We may want to expose this somehow. - table->ColumnsAutoFitWidth += spacing_auto_x * (table->ColumnsVisibleCount - 1); - // Layout const float width_spacings = table->CellSpacingX * (table->ColumnsVisibleCount - 1); float width_avail; From 30e21eb2805e90039e3f628705910056b13d398f Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 21 Jul 2020 14:36:31 +0200 Subject: [PATCH 453/959] Tables: non-resizable columns also submit their requested width for auto-fit, --- imgui_tables.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 2ead3fd8..4167fd49 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -614,6 +614,12 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column_width_ideal = ImMax(column_width_ideal, column_content_width_headers); column_width_ideal = ImMax(column_width_ideal + padding_auto_x, min_column_width); + // Non-resizable columns also submit their requested width + if (column->Flags & ImGuiTableColumnFlags_WidthFixed) + if (column->WidthOrWeightInitValue > 0.0f) + if (!(table->Flags & ImGuiTableFlags_Resizable) || !(column->Flags & ImGuiTableColumnFlags_NoResize)) + column_width_ideal = ImMax(column_width_ideal, column->WidthOrWeightInitValue); + // CellSpacingX is >0.0f when there's no vertical border table->ColumnsAutoFitWidth += column_width_ideal; if (column->PrevVisibleColumn != -1) From 0847373b98c4bc2ced43531b9b52634df573091e Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 27 Jul 2020 21:45:38 +0200 Subject: [PATCH 454/959] Tables: Comments on Sizing Policies + Rename border V/H flags HInner -> InnerH + offset every flags by two. --- imgui.h | 70 ++++++++++++++++++++++++++++-------------------- imgui_demo.cpp | 36 ++++++++++++------------- imgui_internal.h | 4 +-- imgui_tables.cpp | 48 ++++++++++++++++----------------- 4 files changed, 85 insertions(+), 73 deletions(-) diff --git a/imgui.h b/imgui.h index c72757ad..b3a70ae2 100644 --- a/imgui.h +++ b/imgui.h @@ -1009,10 +1009,22 @@ enum ImGuiTabItemFlags_ }; // Flags for ImGui::BeginTable() -// - Columns can either varying resizing policy: "Fixed", "Stretch" or "AlwaysAutoResize". Toggling ScrollX needs to alter default sizing policy. -// - Sizing policy have many subtle side effects which may be hard to fully comprehend at first.. They'll eventually make sense. -// - with SizingPolicyFixedX (default is ScrollX is on): Columns can be enlarged as needed. Enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rect. Only Fixed columns allowed. Weighted columns will calculate their width assuming no scrolling. -// - with SizingPolicyStretchX (default is ScrollX is off): Fit all columns within available table width (so it doesn't make sense to use ScrollX with Stretch columns!). Fixed and Weighted columns allowed. +// - Important! Sizing policies have particularly complex and subtle side effects, more so than you would expect. +// Read comments/demos carefully + experiment with live demos to get acquainted with them. +// - The default sizing policy for columns depends on whether the ScrollX flag is set on the table: +// When ScrollX is off: +// - Table defaults to ImGuiTableFlags_SizingPolicyStretchX -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch. +// - Columns sizing policy allowed: Fixed/Auto or Stretch. +// - Stretch Columns will share the width available in table. +// - Fixed Columns will generally obtain their requested width unless the Table cannot fit them all. +// When ScrollX is on: +// - Table defaults to ImGuiTableFlags_SizingPolicyFixedX -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed. +// - Columns sizing policy allowed: Fixed/Auto mostly! Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +// - Fixed Columns can be enlarged as needed. Table will show an horizontal scrollbar if needed. +// - Stretch Columns, if any, will calculate their width using inner_width, assuming no scrolling (it really doesn't make sense to do otherwise). +// - Mixing up columns with different sizing policy is possible BUT can be tricky and has some side-effects and restrictions. +// (their visible order and the scrolling state have subtle but necessary effects on how they can be manually resized). +// The typical use of mixing sizing policies is to have ScrollX disabled, one or two Stretch Column and many Fixed Columns. enum ImGuiTableFlags_ { // Features @@ -1025,38 +1037,38 @@ enum ImGuiTableFlags_ ImGuiTableFlags_NoSavedSettings = 1 << 5, // Disable persisting columns order, width and sort settings in the .ini file. // Decoration ImGuiTableFlags_RowBg = 1 << 6, // Use ImGuiCol_TableRowBg and ImGuiCol_TableRowBgAlt colors behind each rows. - ImGuiTableFlags_BordersHInner = 1 << 7, // Draw horizontal borders between rows. - ImGuiTableFlags_BordersHOuter = 1 << 8, // Draw horizontal borders at the top and bottom. - ImGuiTableFlags_BordersVInner = 1 << 9, // Draw vertical borders between columns. - ImGuiTableFlags_BordersVOuter = 1 << 10, // Draw vertical borders on the left and right sides. - ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersHInner | ImGuiTableFlags_BordersHOuter, // Draw horizontal borders. - ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersVInner | ImGuiTableFlags_BordersVOuter, // Draw vertical borders. - ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersVInner | ImGuiTableFlags_BordersHInner, // Draw inner borders. - ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersVOuter | ImGuiTableFlags_BordersHOuter, // Draw outer borders. + ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. + ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. - ImGuiTableFlags_BordersVFullHeight = 1 << 11, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. + ImGuiTableFlags_BordersFullHeightV = 1 << 11, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. // Padding, Sizing - ImGuiTableFlags_NoClipX = 1 << 12, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow) - ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. - ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. - ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. - ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) - ImGuiTableFlags_NoKeepColumnsVisible = 1 << 17, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. + ImGuiTableFlags_NoClipX = 1 << 14, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow) + ImGuiTableFlags_SizingPolicyFixedX = 1 << 15, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. + ImGuiTableFlags_SizingPolicyStretchX = 1 << 16, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. + ImGuiTableFlags_NoHeadersWidth = 1 << 17, // Disable header width contribution to automatic width calculation. + ImGuiTableFlags_NoHostExtendY = 1 << 18, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 19, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. // Scrolling - ImGuiTableFlags_ScrollX = 1 << 18, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - ImGuiTableFlags_ScrollY = 1 << 19, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + ImGuiTableFlags_ScrollX = 1 << 20, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 21, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, - ImGuiTableFlags_ScrollFreezeTopRow = 1 << 20, // We can lock 1 to 3 rows (starting from the top). Use with ScrollY enabled. - ImGuiTableFlags_ScrollFreeze2Rows = 2 << 20, - ImGuiTableFlags_ScrollFreeze3Rows = 3 << 20, - ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << 22, // We can lock 1 to 3 columns (starting from the left). Use with ScrollX enabled. - ImGuiTableFlags_ScrollFreeze2Columns = 2 << 22, - ImGuiTableFlags_ScrollFreeze3Columns = 3 << 22, + ImGuiTableFlags_ScrollFreezeTopRow = 1 << 22, // We can lock 1 to 3 rows (starting from the top). Use with ScrollY enabled. + ImGuiTableFlags_ScrollFreeze2Rows = 2 << 22, + ImGuiTableFlags_ScrollFreeze3Rows = 3 << 22, + ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << 24, // We can lock 1 to 3 columns (starting from the left). Use with ScrollX enabled. + ImGuiTableFlags_ScrollFreeze2Columns = 2 << 24, + ImGuiTableFlags_ScrollFreeze3Columns = 3 << 24, // [Internal] Combinations and masks ImGuiTableFlags_SizingPolicyMaskX_ = ImGuiTableFlags_SizingPolicyStretchX | ImGuiTableFlags_SizingPolicyFixedX, - ImGuiTableFlags_ScrollFreezeRowsShift_ = 20, - ImGuiTableFlags_ScrollFreezeColumnsShift_ = 22, + ImGuiTableFlags_ScrollFreezeRowsShift_ = 22, + ImGuiTableFlags_ScrollFreezeColumnsShift_ = 24, ImGuiTableFlags_ScrollFreezeRowsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeRowsShift_, ImGuiTableFlags_ScrollFreezeColumnsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeColumnsShift_ }; diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 2d8fa1a0..f38bf4a8 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3388,19 +3388,19 @@ static void ShowDemoWindowTables() static bool display_width = false; ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&flags, ImGuiTableFlags_Borders); - ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersVInner\n | ImGuiTableFlags_BordersVOuter\n | ImGuiTableFlags_BordersHInner\n | ImGuiTableFlags_BordersHOuter"); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterH"); ImGui::Indent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); ImGui::Indent(); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersHOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersHOuter); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersHInner", (unsigned int*)&flags, ImGuiTableFlags_BordersHInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerH); ImGui::Unindent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); ImGui::Indent(); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersVOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersVOuter); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersVInner", (unsigned int*)&flags, ImGuiTableFlags_BordersVInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); ImGui::Unindent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); @@ -3476,7 +3476,7 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Resizable, fixed")) { // Here we use ImGuiTableFlags_SizingPolicyFixedX (even though _ScrollX is not set) - // So columns will adopt the "Fixed" policy and will maintain a fixed weight regardless of the whole available width. + // So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small) // If there is not enough available width to fit all columns, they will however be resized down. // FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings HelpMarker("Using _Resizable + _SizingPolicyFixedX flags.\nFixed-width columns generally makes more sense if you want to use horizontal scrolling."); @@ -3767,7 +3767,7 @@ static void ShowDemoWindowTables() { HelpMarker("This demonstrate embedding a table into another table cell."); - if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersVFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeightV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("A0"); ImGui::TableSetupColumn("A1"); @@ -3776,7 +3776,7 @@ static void ShowDemoWindowTables() ImGui::TableNextRow(); ImGui::Text("A0 Cell 0"); { float rows_height = ImGui::GetTextLineHeightWithSpacing() * 2; - if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersVFullHeight | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeightV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("B0"); ImGui::TableSetupColumn("B1"); @@ -3813,10 +3813,10 @@ static void ShowDemoWindowTables() ImGui::Combo("Contents", &contents_type, "Short Text\0Long Text\0Button\0Fill Button\0InputText\0"); static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; - ImGui::CheckboxFlags("ImGuiTableFlags_BordersHInner", (unsigned int*)&flags, ImGuiTableFlags_BordersHInner); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersHOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersHOuter); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersVInner", (unsigned int*)&flags, ImGuiTableFlags_BordersVInner); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersVOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersVOuter); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterV); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) @@ -3922,7 +3922,7 @@ static void ShowDemoWindowTables() ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Tree view")) { - static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersHOuter | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg; + static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg; //ImGui::CheckboxFlags("ImGuiTableFlags_Scroll", (unsigned int*)&flags, ImGuiTableFlags_Scroll); //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); @@ -4230,12 +4230,12 @@ static void ShowDemoWindowTables() ImGui::Indent(); ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersVOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersVOuter); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersVInner", (unsigned int*)&flags, ImGuiTableFlags_BordersVInner); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersHOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersHOuter); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersHInner", (unsigned int*)&flags, ImGuiTableFlags_BordersHInner); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersVFullHeight", (unsigned int*)&flags, ImGuiTableFlags_BordersVFullHeight); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersFullHeightV", (unsigned int*)&flags, ImGuiTableFlags_BordersFullHeightV); ImGui::Unindent(); ImGui::BulletText("Padding, Sizing:"); diff --git a/imgui_internal.h b/imgui_internal.h index 0f2d0c68..4dc5f0f2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2056,7 +2056,7 @@ struct ImGuiTableColumnSettings ImS8 SortOrder; ImU8 SortDirection : 2; ImU8 IsVisible : 1; - ImU8 IsWeighted : 1; + ImU8 IsStretch : 1; ImGuiTableColumnSettings() { @@ -2066,7 +2066,7 @@ struct ImGuiTableColumnSettings DisplayOrder = SortOrder = -1; SortDirection = ImGuiSortDirection_None; IsVisible = 1; - IsWeighted = 0; + IsStretch = 0; } }; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 4167fd49..22acdf26 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -67,7 +67,7 @@ // | BeginChild() - (if ScrollX/ScrollY is set) // | TableBeginUpdateColumns() - apply resize/order requests, lock columns active state, order // | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) -// | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of weighted columns) from their respective width +// | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width // - TableSetupColumn() user submit columns details (optional) // - TableAutoHeaders() or TableHeader() user submit a headers row (optional) // | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction @@ -109,7 +109,7 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) // Adjust flags: enforce borders when resizable if (flags & ImGuiTableFlags_Resizable) - flags |= ImGuiTableFlags_BordersVInner; + flags |= ImGuiTableFlags_BordersInnerV; // Adjust flags: disable top rows freezing if there's no scrolling. // We could want to assert if ScrollFreeze was set without the corresponding scroll flag, but that would hinder demos. @@ -258,11 +258,11 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // Borders // - None ........Content..... Pad .....Content........ - // - VOuter | Pad ..Content..... Pad .....Content.. Pad | // FIXME-TABLE: Not handled properly - // - VInner ........Content.. Pad | Pad ..Content........ // FIXME-TABLE: Not handled properly - // - VOuter+VInner | Pad ..Content.. Pad | Pad ..Content.. Pad | + // - OuterV | Pad ..Content..... Pad .....Content.. Pad | // FIXME-TABLE: Not handled properly + // - InnerV ........Content.. Pad | Pad ..Content........ // FIXME-TABLE: Not handled properly + // - OuterV+InnerV | Pad ..Content.. Pad | Pad ..Content.. Pad | - const bool has_cell_padding_x = (flags & ImGuiTableFlags_BordersVOuter) != 0; + const bool has_cell_padding_x = (flags & ImGuiTableFlags_BordersOuterV) != 0; table->CellPaddingX1 = has_cell_padding_x ? g.Style.CellPadding.x + 1.0f : 0.0f; table->CellPaddingX2 = has_cell_padding_x ? g.Style.CellPadding.x : 0.0f; table->CellPaddingY = g.Style.CellPadding.y; @@ -513,7 +513,7 @@ void ImGui::TableUpdateDrawChannels(ImGuiTable* table) } } -// Adjust flags: default width mode + weighted columns are not allowed when auto extending +// Adjust flags: default width mode + stretch columns are not allowed when auto extending static ImGuiTableColumnFlags TableFixColumnFlags(ImGuiTable* table, ImGuiTableColumnFlags flags) { // Sizing Policy @@ -684,7 +684,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) column->WidthRequest = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, min_column_width) + 0.01f); width_remaining_for_stretched_columns -= column->WidthRequest; - // [Resize Rule 2] Resizing from right-side of a weighted column preceding a fixed column + // [Resize Rule 2] Resizing from right-side of a stretch column preceding a fixed column // needs to forward resizing to left-side of fixed column. We also need to copy the NoResize flag.. if (column->NextVisibleColumn != -1) if (ImGuiTableColumn* next_column = &table->Columns[column->NextVisibleColumn]) @@ -918,7 +918,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). // Actual columns highlight/render will be performed in EndTable() and not be affected. - const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersVFullHeight); + const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersFullHeightV); const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS; const float hit_y1 = table->OuterRect.Min.y; const float hit_y2_full = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight); @@ -943,7 +943,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick); if (pressed && IsMouseDoubleClicked(0) && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) { - // FIXME-TABLE: Double-clicking on column edge could auto-fit weighted column? + // FIXME-TABLE: Double-clicking on column edge could auto-fit Stretch column? TableSetColumnAutofit(table, column_n); ClearActiveID(); held = hovered = false; @@ -1121,7 +1121,7 @@ void ImGui::TableDrawBorders(ImGuiTable* table) float draw_y2_base = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight; float draw_y2_full = table->OuterRect.Max.y; ImU32 border_base_col; - if (!table->IsUsingHeaders || (table->Flags & ImGuiTableFlags_BordersVFullHeight)) + if (!table->IsUsingHeaders || (table->Flags & ImGuiTableFlags_BordersFullHeightV)) { draw_y2_base = draw_y2_full; border_base_col = table->BorderColorLight; @@ -1131,10 +1131,10 @@ void ImGui::TableDrawBorders(ImGuiTable* table) border_base_col = table->BorderColorStrong; } - if ((table->Flags & ImGuiTableFlags_BordersVOuter) && (table->InnerWindow == table->OuterWindow)) + if ((table->Flags & ImGuiTableFlags_BordersOuterV) && (table->InnerWindow == table->OuterWindow)) inner_drawlist->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, border_size); - if (table->Flags & ImGuiTableFlags_BordersVInner) + if (table->Flags & ImGuiTableFlags_BordersInnerV) { for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { @@ -1182,18 +1182,18 @@ void ImGui::TableDrawBorders(ImGuiTable* table) { outer_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, ~0, border_size); } - else if (table->Flags & ImGuiTableFlags_BordersVOuter) + else if (table->Flags & ImGuiTableFlags_BordersOuterV) { outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size); outer_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size); } - else if (table->Flags & ImGuiTableFlags_BordersHOuter) + else if (table->Flags & ImGuiTableFlags_BordersOuterH) { outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size); outer_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size); } } - if ((table->Flags & ImGuiTableFlags_BordersHInner) && table->RowPosY2 < table->OuterRect.Max.y) + if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) { // Draw bottom-most row border const float border_y = table->RowPosY2; @@ -1262,7 +1262,7 @@ void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, f // Scenarios: // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset. // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered. - // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Weighted column will always be minimal size. + // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size. // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) // - W1 W2 W3 resize from W1| or W2| --> FIXME // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) @@ -1669,7 +1669,7 @@ void ImGui::TableEndRow(ImGuiTable* table) const float border_size = TABLE_BORDER_SIZE; if (table->CurrentRow != 0 || table->InnerWindow == table->OuterWindow) { - if (table->Flags & ImGuiTableFlags_BordersHInner) + if (table->Flags & ImGuiTableFlags_BordersInnerH) { //if (table->CurrentRow == 0 && table->InnerWindow == table->OuterWindow) // border_col = table->BorderOuterColor; @@ -2492,7 +2492,7 @@ void ImGui::TableSaveSettings(ImGuiTable* table) column_settings->SortOrder = column->SortOrder; column_settings->SortDirection = column->SortDirection; column_settings->IsVisible = column->IsVisible; - column_settings->IsWeighted = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0; + column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0; if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0) save_ref_scale = true; @@ -2549,7 +2549,7 @@ void ImGui::TableLoadSettings(ImGuiTable* table) ImGuiTableColumn* column = &table->Columns[column_n]; if (settings->SaveFlags & ImGuiTableFlags_Resizable) { - if (column_settings->IsWeighted) + if (column_settings->IsStretch) column->WidthStretchWeight = column_settings->WidthOrWeight; else column->WidthRequest = column_settings->WidthOrWeight; @@ -2626,8 +2626,8 @@ static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n; column->Index = (ImS8)column_n; if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; } - if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsWeighted = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; } - if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsWeighted = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; } + if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; } if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsVisible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; } if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImS8)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; } if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImS8)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; } @@ -2661,8 +2661,8 @@ static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandle // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" buf->appendf("Column %-2d", column_n); if (column->UserID != 0) buf->appendf(" UserID=%08X", column->UserID); - if (save_size && column->IsWeighted) buf->appendf(" Weight=%.4f", column->WidthOrWeight); - if (save_size && !column->IsWeighted) buf->appendf(" Width=%d", (int)column->WidthOrWeight); + if (save_size && column->IsStretch) buf->appendf(" Weight=%.4f", column->WidthOrWeight); + if (save_size && !column->IsStretch) buf->appendf(" Width=%d", (int)column->WidthOrWeight); if (save_visible) buf->appendf(" Visible=%d", column->IsVisible); if (save_order) buf->appendf(" Order=%d", column->DisplayOrder); if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^'); From b6405a291d361d9b12ffb674970cc10c7ddbb077 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 Jul 2020 15:27:22 +0200 Subject: [PATCH 455/959] Tables: Fixed TableHeader() not declaring its height properly. Do NOT declare width. --- imgui_tables.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 22acdf26..cb7a1b34 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2133,6 +2133,7 @@ void ImGui::TableHeader(const char* label) const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent); ImGuiID id = window->GetID(label); ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f)); + ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal if (!ItemAdd(bb, id)) return; From 9d8b40414a30fa1d036540269e3196fff186e4b8 Mon Sep 17 00:00:00 2001 From: omar Date: Tue, 28 Jul 2020 15:53:14 +0200 Subject: [PATCH 456/959] Tables: Added TableSetBgColor() api with color for RowBg and CellBg colors. --- imgui.h | 23 +++++++++++- imgui_demo.cpp | 62 ++++++++++++++++++++++++++++--- imgui_internal.h | 16 ++++++-- imgui_tables.cpp | 97 +++++++++++++++++++++++++++++++++++++++--------- 4 files changed, 172 insertions(+), 26 deletions(-) diff --git a/imgui.h b/imgui.h index b3a70ae2..ebbfa771 100644 --- a/imgui.h +++ b/imgui.h @@ -157,6 +157,7 @@ typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier typedef int ImGuiSortDirection; // -> enum ImGuiSortDirection_ // Enum: A sorting direction (ascending or descending) typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling +typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect(), AddRectFilled() etc. typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build @@ -684,6 +685,7 @@ namespace ImGui IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Pass -1 to use current column. IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Pass -1 to use current column. IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. + IMGUI_API void TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. // Tables: Headers & Columns declaration // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. // - The name passed to TableSetupColumn() is used by TableAutoHeaders() and by the context-menu @@ -1036,7 +1038,7 @@ enum ImGuiTableFlags_ ImGuiTableFlags_MultiSortable = 1 << 4, // Allow sorting on multiple columns by holding Shift (sort_specs_count may be > 1). Call TableGetSortSpecs() to obtain sort specs. ImGuiTableFlags_NoSavedSettings = 1 << 5, // Disable persisting columns order, width and sort settings in the .ini file. // Decoration - ImGuiTableFlags_RowBg = 1 << 6, // Use ImGuiCol_TableRowBg and ImGuiCol_TableRowBgAlt colors behind each rows. + ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent to calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. @@ -1109,6 +1111,25 @@ enum ImGuiTableRowFlags_ ImGuiTableRowFlags_Headers = 1 << 0 // Identify header row (set default background color + width of its contents accounted different for auto column width) }; +// Enum for ImGui::TableSetBgColor() +// Background colors are rendering in 3 layers: +// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +// - Layer 2: draw with CellBg color if set. +// The purpose of the two row/columns layers is to let you decide if a background color changes should override or blend with the existing color. +// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +enum ImGuiTableBgTarget_ +{ + ImGuiTableBgTarget_None = 0, + ImGuiTableBgTarget_ColumnBg0 = 1, // FIXME-TABLE: Todo. Set column background color 0 (generally used for background + ImGuiTableBgTarget_ColumnBg1 = 2, // FIXME-TABLE: Todo. Set column background color 1 (generally used for selection marking) + ImGuiTableBgTarget_RowBg0 = 3, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) + ImGuiTableBgTarget_RowBg1 = 4, // Set row background color 1 (generally used for selection marking) + ImGuiTableBgTarget_CellBg = 5 // Set cell background color (top-most color) +}; + // Flags for ImGui::IsWindowFocused() enum ImGuiFocusedFlags_ { diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f38bf4a8..08005cbd 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3902,14 +3902,11 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Row height")) { HelpMarker("You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\n\nWe cannot honor a _maximum_ row height as that would requires a unique clipping rectangle per row."); - if (ImGui::BeginTable("##2ways", 2, ImGuiTableFlags_Borders)) + if (ImGui::BeginTable("##Table", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerV)) { - float min_row_height = ImGui::GetFontSize() + ImGui::GetStyle().CellPadding.y * 2.0f; - ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); - ImGui::Text("min_row_height = %.2f", min_row_height); for (int row = 0; row < 10; row++) { - min_row_height = (float)(int)(ImGui::GetFontSize() * 0.30f * row); + float min_row_height = (float)(int)(ImGui::GetFontSize() * 0.30f * row); ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); ImGui::Text("min_row_height = %.2f", min_row_height); } @@ -3918,6 +3915,61 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } + if (open_action != -1) + ImGui::SetNextItemOpen(open_action != 0); + if (ImGui::TreeNode("Background color")) + { + static ImGuiTableFlags table_flags = ImGuiTableFlags_RowBg; + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&table_flags, ImGuiTableFlags_Borders); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&table_flags, ImGuiTableFlags_RowBg); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style."); + + static int row_bg_type = 1; + static int row_bg_target = 1; + static int cell_bg_type = 1; + ImGui::Combo("row bg type", (int*)&row_bg_type, "None\0Red\0Gradient\0"); + ImGui::Combo("row bg target", (int*)&row_bg_target, "RowBg0\0RowBg1\0"); ImGui::SameLine(); HelpMarker("Target RowBg0 to override the alternating odd/even colors,\nTarget RowBg1 to blend with them."); + ImGui::Combo("cell bg type", (int*)&cell_bg_type, "None\0Blue\0"); ImGui::SameLine(); HelpMarker("We are colorizing cells to B1->C2 here."); + IM_ASSERT(row_bg_type >= 0 && row_bg_type <= 2); + IM_ASSERT(row_bg_target >= 0 && row_bg_target <= 1); + IM_ASSERT(cell_bg_type >= 0 && cell_bg_type <= 1); + + if (ImGui::BeginTable("##Table", 5, table_flags)) + { + for (int row = 0; row < 6; row++) + { + ImGui::TableNextRow(); + + // Demonstrate setting a row background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBgX, ...)' + // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. + if (row_bg_type != 0) + { + ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient? + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color); + } + + // Fill cells + for (int column = 0; column < 5; column++) + { + ImGui::TableSetColumnIndex(column); + ImGui::Text("%c%c", 'A' + row, '0' + column); + + // Change background of Cells B1->C2 + // Demonstrate setting a cell background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ...)' + // (the CellBg color will be blended over the RowBg and ColumnBg colors) + // We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop. + if (row >= 1 && row <= 2 && column >= 1 && column <= 2 && cell_bg_type == 1) + { + ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f)); + ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color); + } + } + } + ImGui::EndTable(); + } + ImGui::TreePop(); + } + if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Tree view")) diff --git a/imgui_internal.h b/imgui_internal.h index 4dc5f0f2..513b7f24 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1883,11 +1883,11 @@ struct ImGuiTabBar #ifdef IMGUI_HAS_TABLE -#define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code +#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 64 // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64. #define IMGUI_TABLE_MAX_DRAW_CHANNELS (2 + 64 * 2) // See TableUpdateDrawChannels() -// [Internal] sizeof() ~ 100 +// [Internal] sizeof() ~ 104 // We use the terminology "Visible" to refer to a column that is not Hidden by user or settings. However it may still be out of view and clipped (see IsClipped). struct ImGuiTableColumn { @@ -1943,6 +1943,14 @@ struct ImGuiTableColumn } }; +// Transient cell data stored per row. +// sizeof() ~ 6 +struct ImGuiTableCellData +{ + ImU32 BgColor; // Actual color + ImS8 Column; // Column number +}; + struct ImGuiTable { ImGuiID ID; @@ -1950,6 +1958,7 @@ struct ImGuiTable ImVector RawData; ImSpan Columns; // Point within RawData[] ImSpan DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) + ImSpan RowCellData; // Point within RawData[]. Store cells background requests for current row. ImU64 VisibleMaskByIndex; // Column Index -> IsVisible map (== not hidden by user/api) in a format adequate for iterating column without touching cold data ImU64 VisibleMaskByDisplayOrder; // Column DisplayOrder -> IsVisible map ImU64 VisibleUnclippedMaskByIndex;// Visible and not Clipped, aka "actually visible" "not hidden by some scrolling" @@ -1970,7 +1979,7 @@ struct ImGuiTable ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ ImGuiTableRowFlags LastRowFlags : 16; int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper) - ImU32 RowBgColor; // Request for current row background color + ImU32 RowBgColor[2]; // Background color override for current row. ImU32 BorderColorStrong; ImU32 BorderColorLight; float BorderX1; @@ -2018,6 +2027,7 @@ struct ImGuiTable ImS8 FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset) ImS8 FreezeColumnsRequest; // Requested frozen columns count ImS8 FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) + ImS8 RowCellDataCount; // Number of RowCellData[] entries in current row bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). bool IsInitializing; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index cb7a1b34..5e785af3 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -307,13 +307,15 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (table->RawData.Size == 0) { // Allocate single buffer for our arrays - ImSpanAllocator<2> span_allocator; + ImSpanAllocator<3> span_allocator; span_allocator.ReserveBytes(0, columns_count * sizeof(ImGuiTableColumn)); span_allocator.ReserveBytes(1, columns_count * sizeof(ImS8)); + span_allocator.ReserveBytes(2, columns_count * sizeof(ImGuiTableCellData)); table->RawData.resize(span_allocator.GetArenaSizeInBytes()); span_allocator.SetArenaBasePtr(table->RawData.Data); span_allocator.GetSpan(0, &table->Columns); span_allocator.GetSpan(1, &table->DisplayOrderToIndex); + span_allocator.GetSpan(2, &table->RowCellData); for (int n = 0; n < columns_count; n++) { @@ -1609,7 +1611,8 @@ void ImGui::TableBeginRow(ImGuiTable* table) // New row table->CurrentRow++; table->CurrentColumn = -1; - table->RowBgColor = IM_COL32_DISABLE; + table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE; + table->RowCellDataCount = 0; table->IsInsideRow = true; // Begin frozen rows @@ -1626,7 +1629,7 @@ void ImGui::TableBeginRow(ImGuiTable* table) // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging. if (table->RowFlags & ImGuiTableRowFlags_Headers) { - table->RowBgColor = GetColorU32(ImGuiCol_TableHeaderBg); + TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg)); if (table->CurrentRow == 0) table->IsUsingHeaders = true; } @@ -1655,14 +1658,18 @@ void ImGui::TableEndRow(ImGuiTable* table) if (table->CurrentRow == 0) table->LastFirstRowHeight = bg_y2 - bg_y1; - if (table->CurrentRow >= 0 && bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y) + const bool is_visible = table->CurrentRow >= 0 && bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y; + if (is_visible) { // Decide of background color for the row - ImU32 bg_col = 0; - if (table->RowBgColor != IM_COL32_DISABLE) - bg_col = table->RowBgColor; + ImU32 bg_col0 = 0; + ImU32 bg_col1 = 0; + if (table->RowBgColor[0] != IM_COL32_DISABLE) + bg_col0 = table->RowBgColor[0]; else if (table->Flags & ImGuiTableFlags_RowBg) - bg_col = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg); + bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg); + if (table->RowBgColor[1] != IM_COL32_DISABLE) + bg_col1 = table->RowBgColor[1]; // Decide of top border color ImU32 border_col = 0; @@ -1684,8 +1691,9 @@ void ImGui::TableEndRow(ImGuiTable* table) } } - const bool draw_stong_bottom_border = unfreeze_rows;// || (table->RowFlags & ImGuiTableRowFlags_Headers); - if (bg_col != 0 || border_col != 0 || draw_stong_bottom_border) + const bool draw_cell_bg_color = table->RowCellDataCount > 0; + const bool draw_strong_bottom_border = unfreeze_rows;// || (table->RowFlags & ImGuiTableRowFlags_Headers); + if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color) { // In theory we could call SetWindowClipRectBeforeChannelChange() but since we know TableEndRow() is // always followed by a change of clipping rectangle we perform the smallest overwrite possible here. @@ -1693,14 +1701,29 @@ void ImGui::TableEndRow(ImGuiTable* table) table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); } - // Draw background + // Draw row background // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle - if (bg_col) + if (bg_col0 || bg_col1) { - ImRect bg_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2); - bg_rect.ClipWith(table->BackgroundClipRect); - if (bg_rect.Min.y < bg_rect.Max.y) - window->DrawList->AddRectFilledMultiColor(bg_rect.Min, bg_rect.Max, bg_col, bg_col, bg_col, bg_col); + ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2); + row_rect.ClipWith(table->BackgroundClipRect); + if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y) + window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0); + if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y) + window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1); + } + + // Draw cell background color + if (draw_cell_bg_color) + { + ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCount - 1]; + for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++) + { + ImGuiTableColumn* column = &table->Columns[cell_data->Column]; + ImRect cell_rect(column->MinX - table->CellSpacingX, bg_y1, column->MaxX, bg_y2); // FIXME-TABLE: Padding currently wrong until we finish the padding refactor + cell_rect.ClipWith(table->BackgroundClipRect); + window->DrawList->AddRectFilled(cell_rect.Min, cell_rect.Max, cell_data->BgColor); + } } // Draw top border @@ -1708,7 +1731,7 @@ void ImGui::TableEndRow(ImGuiTable* table) window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col, border_size); // Draw bottom border at the row unfreezing mark (always strong) - if (draw_stong_bottom_border) + if (draw_strong_bottom_border) if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y) window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size); } @@ -2305,6 +2328,46 @@ int ImGui::TableGetHoveredColumn() return (int)table->HoveredColumnBody; } +void ImGui::TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(bg_target != ImGuiTableBgTarget_None); + + if (color == IM_COL32_DISABLE) + color = 0; + + // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time. + switch (bg_target) + { + case ImGuiTableBgTarget_CellBg: + { + if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard + return; + if (column_n == -1) + column_n = table->CurrentColumn; + if ((table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) == 0) + return; + ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCount++]; + cell_data->BgColor = color; + cell_data->Column = (ImS8)column_n; + break; + } + case ImGuiTableBgTarget_RowBg0: + case ImGuiTableBgTarget_RowBg1: + { + if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard + return; + IM_ASSERT(column_n == -1); + int bg_idx = (bg_target == ImGuiTableBgTarget_RowBg1) ? 1 : 0; + table->RowBgColor[bg_idx] = color; + break; + } + default: + IM_ASSERT(0); + } +} + void ImGui::TableSortSpecsSanitize(ImGuiTable* table) { IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable); From eb18636e0287d90a3756115d90b99f4a7201e638 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 5 Aug 2020 19:26:54 +0200 Subject: [PATCH 457/959] Tables: Fix settings not being saved in child window (issue 3367) + fix for change in master. --- imgui_internal.h | 2 +- imgui_tables.cpp | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 513b7f24..73c7ba58 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2001,7 +2001,7 @@ struct ImGuiTable ImRect InnerClipRect; ImRect BackgroundClipRect; // We use this to cpu-clip cell background color fill ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. - ImRect HostWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() + ImRect HostBackupParentWorkRect; // Backup of InnerWindow->ParentWorkRect at the end of BeginTable() ImRect HostBackupClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground() ImVec2 HostCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() ImGuiWindow* OuterWindow; // Parent window for the table diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 5e785af3..ad98797a 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -193,7 +193,14 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG } flags = TableFixFlags(flags); - if (outer_window->Flags & ImGuiWindowFlags_NoSavedSettings) + + // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set) +#ifdef IMGUI_HAS_DOCK + ImGuiWindow* window_for_settings = outer_window->RootWindowDockStop; +#else + ImGuiWindow* window_for_settings = outer_window->RootWindow; +#endif + if (window_for_settings->Flags & ImGuiWindowFlags_NoSavedSettings) flags |= ImGuiTableFlags_NoSavedSettings; // Acquire storage for the table @@ -253,8 +260,9 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->HostIndentX = inner_window->DC.Indent.x; table->HostClipRect = inner_window->ClipRect; table->HostSkipItems = inner_window->SkipItems; - table->HostWorkRect = inner_window->WorkRect; + table->HostBackupParentWorkRect = inner_window->ParentWorkRect; table->HostCursorMaxPos = inner_window->DC.CursorMaxPos; + inner_window->ParentWorkRect = inner_window->WorkRect; // Borders // - None ........Content..... Pad .....Content........ @@ -1067,7 +1075,8 @@ void ImGui::EndTable() // Layout in outer window IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table->ID + table->InstanceCurrent, "Mismatching PushID/PopID!"); PopID(); - inner_window->WorkRect = table->HostWorkRect; + inner_window->WorkRect = inner_window->ParentWorkRect; + inner_window->ParentWorkRect = table->HostBackupParentWorkRect; inner_window->SkipItems = table->HostSkipItems; outer_window->DC.CursorPos = table->OuterRect.Min; outer_window->DC.ColumnsOffset.x = 0.0f; From 9372601322c620640e5a8c709d51a211bc663e54 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 17 Aug 2020 13:25:27 +0200 Subject: [PATCH 458/959] Tables: Fixed stacked popups incorrectly accessing g.CurrentTable of parent-in-stack windows. --- imgui.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/imgui.cpp b/imgui.cpp index bc1ac4b7..e12cbae1 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2931,6 +2931,7 @@ static void SetCurrentWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.CurrentWindow = window; + g.CurrentTable = window ? window->DC.CurrentTable : NULL; if (window) g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } From 45a80716b19a3a8695e3fd9c0b1e0deaad97f1f7 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 18 Aug 2020 18:39:57 +0200 Subject: [PATCH 459/959] Tables: Fixed three bugs + metrics tweaks. - Fixed bug when ending a table within another (outer table column offset was overwritten instead of restored). - Fixed assert when settings data has mismatching column count. - Fixed restoring g.CurrentTable when calling EndChild() from inside table inner window. - Made inactive tables grey in metrics. - Fix warning. (amended twice) --- imgui_internal.h | 3 ++- imgui_tables.cpp | 20 ++++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 73c7ba58..ed7b465d 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -542,7 +542,7 @@ struct ImSpanAllocator int Offsets[CHUNKS]; ImSpanAllocator() { memset(this, 0, sizeof(*this)); } - inline void ReserveBytes(int n, size_t sz) { IM_ASSERT(n == CurrSpan && n < CHUNKS); Offsets[CurrSpan++] = TotalSize; TotalSize += (int)sz; } + inline void ReserveBytes(int n, size_t sz) { IM_ASSERT(n == CurrSpan && n < CHUNKS); IM_UNUSED(n); Offsets[CurrSpan++] = TotalSize; TotalSize += (int)sz; } inline int GetArenaSizeInBytes() { return TotalSize; } inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; } inline void* GetSpanPtrBegin(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrSpan == CHUNKS); return (void*)(BasePtr + Offsets[n]); } @@ -2004,6 +2004,7 @@ struct ImGuiTable ImRect HostBackupParentWorkRect; // Backup of InnerWindow->ParentWorkRect at the end of BeginTable() ImRect HostBackupClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground() ImVec2 HostCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() + ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->ColumnsOffset at the end of BeginTable() ImGuiWindow* OuterWindow; // Parent window for the table ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names diff --git a/imgui_tables.cpp b/imgui_tables.cpp index ad98797a..1d66501a 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -261,6 +261,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->HostClipRect = inner_window->ClipRect; table->HostSkipItems = inner_window->SkipItems; table->HostBackupParentWorkRect = inner_window->ParentWorkRect; + table->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset; table->HostCursorMaxPos = inner_window->DC.CursorMaxPos; inner_window->ParentWorkRect = inner_window->WorkRect; @@ -305,6 +306,8 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG g.CurrentTableStack.push_back(ImGuiPtrOrIndex(g.Tables.GetIndex(table))); g.CurrentTable = table; outer_window->DC.CurrentTable = table; + if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly. + inner_window->DC.CurrentTable = table; if ((table_last_flags & ImGuiTableFlags_Reorderable) && !(flags & ImGuiTableFlags_Reorderable)) table->IsResetDisplayOrderRequest = true; @@ -1079,7 +1082,7 @@ void ImGui::EndTable() inner_window->ParentWorkRect = table->HostBackupParentWorkRect; inner_window->SkipItems = table->HostSkipItems; outer_window->DC.CursorPos = table->OuterRect.Min; - outer_window->DC.ColumnsOffset.x = 0.0f; + outer_window->DC.ColumnsOffset = table->HostBackupColumnsOffset; if (inner_window != outer_window) { EndChild(); @@ -1110,9 +1113,8 @@ void ImGui::EndTable() // Clear or restore current table, if any IM_ASSERT(g.CurrentWindow == outer_window); IM_ASSERT(g.CurrentTable == table); - outer_window->DC.CurrentTable = NULL; g.CurrentTableStack.pop_back(); - g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL; + outer_window->DC.CurrentTable = g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL; } // FIXME-TABLE: This is a mess, need to redesign how we render borders. @@ -2601,15 +2603,17 @@ void ImGui::TableLoadSettings(ImGuiTable* table) settings = TableSettingsFindByID(table->ID); if (settings == NULL) return; + if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return... + table->IsSettingsDirty = true; table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings); } else { settings = TableGetBoundSettings(table); } + table->SettingsLoadedFlags = settings->SaveFlags; table->RefScale = settings->RefScale; - IM_ASSERT(settings->ColumnsCount == table->ColumnsCount); // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings(); @@ -2772,13 +2776,17 @@ void ImGui::DebugNodeTable(ImGuiTable* table) char buf[256]; char* p = buf; const char* buf_end = buf + IM_ARRAYSIZE(buf); - ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name); + const bool is_active = (table->LastFrameActive >= ImGui::GetFrameCount() - 2); + ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*"); + if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } bool open = TreeNode(table, "%s", buf); + if (!is_active) { PopStyleColor(); } if (IsItemHovered()) GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255)); if (!open) return; - BulletText("OuterWidth: %.1f, InnerWidth: %.1f%s", table->OuterRect.GetWidth(), table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : ""); + BulletText("OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f)", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight()); + BulletText("InnerWidth: %.1f%s", table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : ""); BulletText("ColumnsWidth: %.1f, AutoFitWidth: %.1f", table->ColumnsTotalWidth, table->ColumnsAutoFitWidth); BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder); BulletText("ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn); From 8e97cdf8e8b41e92ec2ca6194335398797b4c2cf Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 24 Aug 2020 15:34:43 +0200 Subject: [PATCH 460/959] Tables: Fix for calling TableSetBgColor(ImGuiTableBgTarget_CellBg) multiple times on the same cell. --- imgui.h | 4 ++-- imgui_internal.h | 2 +- imgui_tables.cpp | 10 ++++++---- imgui_widgets.cpp | 2 +- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/imgui.h b/imgui.h index ebbfa771..019e8721 100644 --- a/imgui.h +++ b/imgui.h @@ -1022,8 +1022,8 @@ enum ImGuiTabItemFlags_ // When ScrollX is on: // - Table defaults to ImGuiTableFlags_SizingPolicyFixedX -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed. // - Columns sizing policy allowed: Fixed/Auto mostly! Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). -// - Fixed Columns can be enlarged as needed. Table will show an horizontal scrollbar if needed. -// - Stretch Columns, if any, will calculate their width using inner_width, assuming no scrolling (it really doesn't make sense to do otherwise). +// - Fixed Columns can be enlarged as needed. Table will show an horizontal scrollbar if needed. +// - Stretch Columns, if any, will calculate their width using inner_width, assuming no scrolling (it really doesn't make sense to do otherwise). // - Mixing up columns with different sizing policy is possible BUT can be tricky and has some side-effects and restrictions. // (their visible order and the scrolling state have subtle but necessary effects on how they can be manually resized). // The typical use of mixing sizing policies is to have ScrollX disabled, one or two Stretch Column and many Fixed Columns. diff --git a/imgui_internal.h b/imgui_internal.h index ed7b465d..3f733d62 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2028,7 +2028,7 @@ struct ImGuiTable ImS8 FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset) ImS8 FreezeColumnsRequest; // Requested frozen columns count ImS8 FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) - ImS8 RowCellDataCount; // Number of RowCellData[] entries in current row + ImS8 RowCellDataCurrent; // Index of current RowCellData[] entry in current row bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). bool IsInitializing; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 1d66501a..c780f1f2 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1623,7 +1623,7 @@ void ImGui::TableBeginRow(ImGuiTable* table) table->CurrentRow++; table->CurrentColumn = -1; table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE; - table->RowCellDataCount = 0; + table->RowCellDataCurrent = -1; table->IsInsideRow = true; // Begin frozen rows @@ -1702,7 +1702,7 @@ void ImGui::TableEndRow(ImGuiTable* table) } } - const bool draw_cell_bg_color = table->RowCellDataCount > 0; + const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0; const bool draw_strong_bottom_border = unfreeze_rows;// || (table->RowFlags & ImGuiTableRowFlags_Headers); if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color) { @@ -1727,7 +1727,7 @@ void ImGui::TableEndRow(ImGuiTable* table) // Draw cell background color if (draw_cell_bg_color) { - ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCount - 1]; + ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent]; for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++) { ImGuiTableColumn* column = &table->Columns[cell_data->Column]; @@ -2359,7 +2359,9 @@ void ImGui::TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int colum column_n = table->CurrentColumn; if ((table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) == 0) return; - ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCount++]; + if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n) + table->RowCellDataCurrent++; + ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent]; cell_data->BgColor = color; cell_data->Column = (ImS8)column_n; break; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index 6954960b..3df58daa 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -5999,7 +5999,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // which would be advantageous since most selectable are not selected. if (span_all_columns && window->DC.CurrentColumns) PushColumnsBackground(); - else if ((flags & ImGuiSelectableFlags_SpanAllColumns) && g.CurrentTable) + else if (span_all_columns && g.CurrentTable) PushTableBackground(); // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries From 3d573103b68b931cb3793d29d042c0c6e8d6a303 Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2020 20:42:05 +0200 Subject: [PATCH 461/959] Tables: Fixed lower clipping when using ImGuiTableFlags_NoHostExtendY. --- imgui_tables.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index c780f1f2..13fa9269 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -284,7 +284,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width table->InnerClipRect.ClipWith(table->HostClipRect); - table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? table->WorkRect.Max.y : inner_window->ClipRect.Max.y; + table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : inner_window->ClipRect.Max.y; table->BackgroundClipRect = table->InnerClipRect; table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() From f6800e9d3b92513022716691364c0183ffa6b8bd Mon Sep 17 00:00:00 2001 From: ocornut Date: Fri, 18 Sep 2020 20:44:50 +0200 Subject: [PATCH 462/959] Tables: Extend outer-most clip limits to match those of host when merging draw calls. Generally clarify/simplify ClipRect extending/merging code in TableReorderDrawChannelsForMerge(). Amend/fix Sep 23 --- imgui_tables.cpp | 69 +++++++++++++++++++++++------------------------- 1 file changed, 33 insertions(+), 36 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 13fa9269..a54a8f9e 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -69,18 +69,20 @@ // | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) // | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width // - TableSetupColumn() user submit columns details (optional) +// - TableUpdateLayout() [Internal] automatically called by the FIRST call to TableNextRow() or Table*Header(): lock all widths, columns positions, clipping rectangles +// | TableUpdateDrawChannels() - setup ImDrawList channels +// | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +// | TableDrawContextMenu() - draw right-click context menu +//----------------------------------------------------------------------------- // - TableAutoHeaders() or TableHeader() user submit a headers row (optional) // | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction // | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu // - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) // - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders() -// | TableUpdateLayout() - lock all widths, columns positions, clipping rectangles. called by the FIRST call to TableNextRow()! -// | - TableUpdateDrawChannels() - setup ImDrawList channels -// | - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission -// | - TableDrawContextMenu() - draw right-click context menu // | TableEndCell() - close existing cell if not the first time // | TableBeginCell() - enter into current cell // - [...] user emit contents +//----------------------------------------------------------------------------- // - EndTable() user ends the table // | TableDrawBorders() - draw outer borders, inner vertical borders // | TableReorderDrawChannelsForMerge() - merge draw channels if clipping isn't required @@ -1375,7 +1377,6 @@ void ImGui::TableReorderDrawChannelsForMerge(ImGuiTable* table) int merge_group_mask = 0x00; MergeGroup merge_groups[4]; memset(merge_groups, 0, sizeof(merge_groups)); - bool merge_groups_all_fit_within_inner_rect = (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0; // 1. Scan channels and take note of those which can be merged for (int column_n = 0; column_n < table->ColumnsCount; column_n++) @@ -1396,7 +1397,8 @@ void ImGui::TableReorderDrawChannelsForMerge(ImGuiTable* table) if (src_channel->_CmdBuffer.Size != 1) continue; - // Find out the width of this merge group and check if it will fit in our column. + // Find out the width of this merge group and check if it will fit in our column + // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it) if (!(column->Flags & ImGuiTableColumnFlags_NoClipX)) { float width_contents; @@ -1410,28 +1412,15 @@ void ImGui::TableReorderDrawChannelsForMerge(ImGuiTable* table) continue; } - const int merge_group_dst_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1); + const int merge_group_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1); IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS); - MergeGroup* merge_group = &merge_groups[merge_group_dst_n]; + MergeGroup* merge_group = &merge_groups[merge_group_n]; if (merge_group->ChannelsCount == 0) merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); merge_group->ChannelsMask.SetBit(channel_no); merge_group->ChannelsCount++; merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect); - merge_group_mask |= (1 << merge_group_dst_n); - - // If we end with a single group and hosted by the outer window, we'll attempt to merge our draw command - // with the existing outer window command. But we can only do so if our columns all fit within the expected - // clip rect, otherwise clipping will be incorrect when ScrollX is disabled. - // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column don't fit within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect - - // 2019/10/22: (1) This is breaking table_2_draw_calls but I cannot seem to repro what it is attempting to - // fix... cf git fce2e8dc "Fixed issue with clipping when outerwindow==innerwindow / support ScrollH without ScrollV." - // 2019/10/22: (2) Clamping code in TableUpdateLayout() seemingly made this not necessary... -#if 0 - if (column->MinX < table->InnerClipRect.Min.x || column->MaxX > table->InnerClipRect.Max.x) - merge_groups_all_fit_within_inner_rect = false; -#endif + merge_group_mask |= (1 << merge_group_n); } // Invalidate current draw channel @@ -1460,10 +1449,6 @@ void ImGui::TableReorderDrawChannelsForMerge(ImGuiTable* table) // 2. Rewrite channel list in our preferred order if (merge_group_mask != 0) { - // Conceptually we want to test if only 1 bit of merge_group_mask is set, but with no freezing we know it's always going to be group 3. - // We need to test for !is_frozen because any unfitting column will not be part of a merge group, so testing for merge_group_mask isn't enough. - const bool may_extend_clip_rect_to_host_rect = (merge_group_mask == (1 << 3)) && !is_frozen_v && !is_frozen_h; - // Use shared temporary storage so the allocation gets amortized g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - 1); ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data; @@ -1475,16 +1460,28 @@ void ImGui::TableReorderDrawChannelsForMerge(ImGuiTable* table) if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount) { MergeGroup* merge_group = &merge_groups[merge_group_n]; - ImRect merge_clip_rect = merge_groups[merge_group_n].ClipRect; - if (may_extend_clip_rect_to_host_rect) - { - IM_ASSERT(merge_group_n == 3); - //GetOverlayDrawList()->AddRect(table->HostClipRect.Min, table->HostClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 3.0f); - //GetOverlayDrawList()->AddRect(table->InnerClipRect.Min, table->InnerClipRect.Max, IM_COL32(0, 255, 0, 200), 0.0f, ~0, 1.0f); - //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 2.0f); - merge_clip_rect.Add(merge_groups_all_fit_within_inner_rect ? table->HostClipRect : table->InnerClipRect); - //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(0, 255, 0, 200)); - } + ImRect merge_clip_rect = merge_group->ClipRect; + + // Extend outer-most clip limits to match those of host, so draw calls can be merged even if + // outer-most columns have some outer padding offsetting them from their parent ClipRect. + // The principal cases this is dealing with are: + // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge + // - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge + // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit + // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect. + if ((merge_group_n & 2) == 0 || !is_frozen_h) + merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, table->HostClipRect.Min.x); + if ((merge_group_n & 1) == 0 || !is_frozen_v) + merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, table->HostClipRect.Min.y); + if ((merge_group_n & 2) != 0) + merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, table->HostClipRect.Max.x); + if ((merge_group_n & 1) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0) + merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, table->HostClipRect.Max.y); +#if 0 + GetOverlayDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 1.0f); + GetOverlayDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200)); + GetOverlayDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200)); +#endif remaining_count -= merge_group->ChannelsCount; for (int n = 0; n < IM_ARRAYSIZE(remaining_mask.Storage); n++) remaining_mask.Storage[n] &= ~merge_group->ChannelsMask.Storage[n]; From 931829f701143780d921b3478a8aef0df7b2d7bb Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 23 Sep 2020 12:53:10 +0200 Subject: [PATCH 463/959] Tables: (Breaking change) Sorting: Made it users responsability to clear SpecsDirty back to false, so TableGetSortSpecs() doesn't have side-effect any more. + comments --- imgui.h | 28 ++++++++++++++++------------ imgui_demo.cpp | 15 ++++++++++----- imgui_internal.h | 1 - imgui_tables.cpp | 9 +++------ 4 files changed, 29 insertions(+), 24 deletions(-) diff --git a/imgui.h b/imgui.h index 019e8721..42229755 100644 --- a/imgui.h +++ b/imgui.h @@ -688,17 +688,19 @@ namespace ImGui IMGUI_API void TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. // Tables: Headers & Columns declaration // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. - // - The name passed to TableSetupColumn() is used by TableAutoHeaders() and by the context-menu - // - Use TableAutoHeaders() to submit the whole header row, otherwise you may treat the header row as a regular row, manually call TableHeader() and other widgets. - // - Headers are required to perform some interactions: reordering, sorting, context menu (FIXME-TABLE: context menu should work without!) + // Important: this will not display anything! The name passed to TableSetupColumn() is used by TableAutoHeaders() and context-menus. + // - Use TableAutoHeaders() to create a row and automatically submit a TableHeader() for each column. + // Headers are required to perform some interactions: reordering, sorting, context menu (FIXME-TABLE: context menu should work without!) + // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in some advanced cases (e.g. adding custom widgets in header row). IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = -1.0f, ImU32 user_id = 0); IMGUI_API void TableAutoHeaders(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu - IMGUI_API void TableHeader(const char* label); // submit one header cell manually. + IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) // Tables: Sorting // - Call TableGetSortSpecs() to retrieve latest sort specs for the table. Return value will be NULL if no sorting. - // - You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since last call, or the first time. + // - When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. + // Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! // - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! - IMGUI_API const ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). + IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). // Tab Bars, Tabs IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar @@ -1890,15 +1892,17 @@ struct ImGuiTableSortSpecsColumn }; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) -// Obtained by calling TableGetSortSpecs() +// Obtained by calling TableGetSortSpecs(). +// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! struct ImGuiTableSortSpecs { - const ImGuiTableSortSpecsColumn* Specs; // Pointer to sort spec array. - int SpecsCount; // Sort spec count. Most often 1 unless e.g. ImGuiTableFlags_MultiSortable is enabled. - bool SpecsChanged; // Set to true by TableGetSortSpecs() call if the specs have changed since the previous call. Use this to sort again! - ImU64 ColumnsMask; // Set to the mask of column indexes included in the Specs array. e.g. (1 << N) when column N is sorted. + const ImGuiTableSortSpecsColumn* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1 unless e.g. ImGuiTableFlags_MultiSortable is enabled. + bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. + ImU64 ColumnsMask; // Set to the mask of column indexes included in the Specs array. e.g. (1 << N) when column N is sorted. - ImGuiTableSortSpecs() { Specs = NULL; SpecsCount = 0; SpecsChanged = false; ColumnsMask = 0x00; } + ImGuiTableSortSpecs() { Specs = NULL; SpecsCount = 0; SpecsDirty = false; ColumnsMask = 0x00; } }; //----------------------------------------------------------------------------- diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 08005cbd..54f58586 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3250,6 +3250,8 @@ struct MyItem // however qsort doesn't allow passing user data to comparing function. // As a workaround, we are storing the sort specs in a static/global for the comparing function to access. // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global. + // We could technically call ImGui::TableGetSortSpecs() in CompareWithSortSpecs(), but considering that this function is called + // very often by the sorting algorithm it would be a little wasteful. static const ImGuiTableSortSpecs* s_current_sort_specs; // Compare function to be used by qsort() @@ -4201,12 +4203,14 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, -1.0f, MyItemColumnID_Quantity); // Sort our data if sort specs have been changed! - if (const ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs()) - if (sorts_specs->SpecsChanged && items.Size > 1) + if (ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs()) + if (sorts_specs->SpecsDirty) { MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. - qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); + if (items.Size > 1) + qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); MyItem::s_current_sort_specs = NULL; + sorts_specs->SpecsDirty = false; } // Display data @@ -4389,14 +4393,15 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("Hidden", ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort); // Sort our data if sort specs have been changed! - const ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs(); - if (sorts_specs && sorts_specs->SpecsChanged) + ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs(); + if (sorts_specs && sorts_specs->SpecsDirty) items_need_sort = true; if (sorts_specs && items_need_sort && items.Size > 1) { MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function. qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs); MyItem::s_current_sort_specs = NULL; + sorts_specs->SpecsDirty = false; } items_need_sort = false; diff --git a/imgui_internal.h b/imgui_internal.h index 3f733d62..261f1be1 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2033,7 +2033,6 @@ struct ImGuiTable bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). bool IsInitializing; bool IsSortSpecsDirty; - bool IsSortSpecsChangedForUser; // Reported to end-user via TableGetSortSpecs()->SpecsChanged and then clear. 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 IsSettingsRequestLoad; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index a54a8f9e..efa41dd9 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -2298,7 +2298,7 @@ void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* click // You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since // last call, or the first time. // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! -const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() +ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; @@ -2310,8 +2310,6 @@ const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs() if (table->IsSortSpecsDirty) TableSortSpecsBuild(table); - table->SortSpecs.SpecsChanged = table->IsSortSpecsChangedForUser; - table->IsSortSpecsChangedForUser = false; return table->SortSpecs.SpecsCount ? &table->SortSpecs : NULL; } @@ -2466,9 +2464,8 @@ void ImGui::TableSortSpecsBuild(ImGuiTable* table) } table->SortSpecs.Specs = table->SortSpecsData.Data; table->SortSpecs.SpecsCount = table->SortSpecsData.Size; - - table->IsSortSpecsDirty = false; - table->IsSortSpecsChangedForUser = true; + table->SortSpecs.SpecsDirty = true; // Mark as dirty for user + table->IsSortSpecsDirty = false; // Mark as not dirty for us } //------------------------------------------------------------------------- From 8ec05fc0342e81a023fba85b8b19e7ad6104ff46 Mon Sep 17 00:00:00 2001 From: omar Date: Wed, 23 Sep 2020 14:22:41 +0200 Subject: [PATCH 464/959] Tables: Fixed holding on table pointers accross resize/invalidation of the pool buffer. --- imgui.cpp | 3 ++- imgui_internal.h | 2 +- imgui_tables.cpp | 10 ++++++---- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index e12cbae1..823fe725 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2931,7 +2931,7 @@ static void SetCurrentWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.CurrentWindow = window; - g.CurrentTable = window ? window->DC.CurrentTable : NULL; + g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL; if (window) g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } @@ -5623,6 +5623,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX); window->IDStack.resize(1); window->DrawList->_ResetForNewFrame(); + window->DC.CurrentTableIdx = -1; // Restore buffer capacity when woken from a compacted state, to avoid if (window->MemoryCompacted) diff --git a/imgui_internal.h b/imgui_internal.h index 261f1be1..054252f2 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1657,7 +1657,7 @@ struct IMGUI_API ImGuiWindowTempData ImVector ChildWindows; ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) ImGuiOldColumns* CurrentColumns; // Current columns set - ImGuiTable* CurrentTable; // Current table set + int CurrentTableIdx; // Current table index (into g.Tables) ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() int FocusCounterRegular; // (Legacy Focus/Tabbing system) Sequential counter, start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index efa41dd9..51249f4b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -305,11 +305,12 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f); // Make table current - g.CurrentTableStack.push_back(ImGuiPtrOrIndex(g.Tables.GetIndex(table))); + const int table_idx = g.Tables.GetIndex(table); + g.CurrentTableStack.push_back(ImGuiPtrOrIndex(table_idx)); g.CurrentTable = table; - outer_window->DC.CurrentTable = table; + outer_window->DC.CurrentTableIdx = table_idx; if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly. - inner_window->DC.CurrentTable = table; + inner_window->DC.CurrentTableIdx = table_idx; if ((table_last_flags & ImGuiTableFlags_Reorderable) && !(flags & ImGuiTableFlags_Reorderable)) table->IsResetDisplayOrderRequest = true; @@ -1116,7 +1117,8 @@ void ImGui::EndTable() IM_ASSERT(g.CurrentWindow == outer_window); IM_ASSERT(g.CurrentTable == table); g.CurrentTableStack.pop_back(); - outer_window->DC.CurrentTable = g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL; + g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL; + outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1; } // FIXME-TABLE: This is a mess, need to redesign how we render borders. From 36b2f3b4f1bb245ec59dc06e4c1b78a791d66c1c Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Sep 2020 16:42:44 +0200 Subject: [PATCH 465/959] Tables: renamed ImGuiTableFlags_NoClipX to ImGuiTableFlags_NoClip, clarified purpose, moved lower in the list as it doesn't need to be so prominent. --- imgui.h | 12 ++++++------ imgui_demo.cpp | 7 ++++--- imgui_tables.cpp | 18 +++++++++--------- 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/imgui.h b/imgui.h index 42229755..83b5747d 100644 --- a/imgui.h +++ b/imgui.h @@ -1052,12 +1052,12 @@ enum ImGuiTableFlags_ ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. ImGuiTableFlags_BordersFullHeightV = 1 << 11, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. // Padding, Sizing - ImGuiTableFlags_NoClipX = 1 << 14, // Disable pushing clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow) - ImGuiTableFlags_SizingPolicyFixedX = 1 << 15, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. - ImGuiTableFlags_SizingPolicyStretchX = 1 << 16, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. - ImGuiTableFlags_NoHeadersWidth = 1 << 17, // Disable header width contribution to automatic width calculation. - ImGuiTableFlags_NoHostExtendY = 1 << 18, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) - ImGuiTableFlags_NoKeepColumnsVisible = 1 << 19, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. + ImGuiTableFlags_SizingPolicyFixedX = 1 << 12, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. + ImGuiTableFlags_SizingPolicyStretchX = 1 << 13, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. + ImGuiTableFlags_NoHeadersWidth = 1 << 14, // Disable header width contribution to automatic width calculation. + ImGuiTableFlags_NoHostExtendY = 1 << 15, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 16, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. + ImGuiTableFlags_NoClip = 1 << 17, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options. // Scrolling ImGuiTableFlags_ScrollX = 1 << 20, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. ImGuiTableFlags_ScrollY = 1 << 21, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 54f58586..f26d6349 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3828,7 +3828,7 @@ static void ShowDemoWindowTables() flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyFixedX); // Can't specify both sizing polices so we clear the other ImGui::SameLine(); HelpMarker("Default if _ScrollX if enabled. Makes columns use _WidthFixed by default, or _WidthAlwaysAutoResize if _Resizable is not set."); ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); - ImGui::CheckboxFlags("ImGuiTableFlags_NoClipX", (unsigned int*)&flags, ImGuiTableFlags_NoClipX); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", (unsigned int*)&flags, ImGuiTableFlags_NoClip); if (ImGui::BeginTable("##3ways", 3, flags, ImVec2(0, 100))) { @@ -4296,7 +4296,6 @@ static void ShowDemoWindowTables() ImGui::BulletText("Padding, Sizing:"); ImGui::Indent(); - ImGui::CheckboxFlags("ImGuiTableFlags_NoClipX", (unsigned int*)&flags, ImGuiTableFlags_NoClipX); if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyStretchX); // Can't specify both sizing polices so we clear the other ImGui::SameLine(); HelpMarker("[Default if ScrollX is off]\nFit all columns within available width (or specified inner_width). Fixed and Stretch columns allowed."); @@ -4307,6 +4306,8 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", (unsigned int*)&flags, ImGuiTableFlags_NoHostExtendY); ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", (unsigned int*)&flags, ImGuiTableFlags_NoKeepColumnsVisible); ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", (unsigned int*)&flags, ImGuiTableFlags_NoClip); + ImGui::SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options."); ImGui::Unindent(); ImGui::BulletText("Scrolling:"); @@ -4424,7 +4425,7 @@ static void ShowDemoWindowTables() for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++) #else { - for (int row_n = 0; row_n < items_count; n++) + for (int row_n = 0; row_n < items_count; row_n++) #endif { MyItem* item = &items[row_n]; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 51249f4b..65701724 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -124,10 +124,10 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) if ((flags & ImGuiTableFlags_NoHostExtendY) && (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0) flags &= ~ImGuiTableFlags_NoHostExtendY; - // Adjust flags: we don't support NoClipX with (FreezeColumns > 0) + // Adjust flags: we don't support NoClip with (FreezeColumns > 0) // We could with some work but it doesn't appear to be worth the effort. - if (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) - flags &= ~ImGuiTableFlags_NoClipX; + //if (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) + // flags &= ~ImGuiTableFlags_NoClip; return flags; } @@ -503,7 +503,7 @@ void ImGui::TableUpdateDrawChannels(ImGuiTable* table) // - FreezeRows || FreezeColumns --> 1+N*2 (unless scrolling value is zero) // - FreezeRows && FreezeColunns --> 2+N*2 (unless scrolling value is zero) const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1; - const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClipX) ? 1 : table->ColumnsVisibleCount; + const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsVisibleCount; const int channels_for_background = 1; const int channels_for_dummy = (table->ColumnsVisibleCount < table->ColumnsCount || table->VisibleUnclippedMaskByIndex != table->VisibleMaskByIndex) ? +1 : 0; const int channels_total = channels_for_background + (channels_for_row * freeze_row_multiplier) + channels_for_dummy; @@ -518,7 +518,7 @@ void ImGui::TableUpdateDrawChannels(ImGuiTable* table) { column->DrawChannelRowsBeforeFreeze = (ImS8)(draw_channel_current); column->DrawChannelRowsAfterFreeze = (ImS8)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row : 0)); - if (!(table->Flags & ImGuiTableFlags_NoClipX)) + if (!(table->Flags & ImGuiTableFlags_NoClip)) draw_channel_current++; } else @@ -910,7 +910,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) // Initial state ImGuiWindow* inner_window = table->InnerWindow; - if (table->Flags & ImGuiTableFlags_NoClipX) + if (table->Flags & ImGuiTableFlags_NoClip) table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 1); else inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false); @@ -1017,7 +1017,7 @@ void ImGui::EndTable() table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y); table->LastOuterHeight = table->OuterRect.GetHeight(); - if (!(flags & ImGuiTableFlags_NoClipX)) + if (!(flags & ImGuiTableFlags_NoClip)) inner_window->DrawList->PopClipRect(); inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back(); @@ -1050,7 +1050,7 @@ void ImGui::EndTable() // Flatten channels and merge draw calls table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0); - if ((table->Flags & ImGuiTableFlags_NoClipX) == 0) + if ((table->Flags & ImGuiTableFlags_NoClip) == 0) TableReorderDrawChannelsForMerge(table); table->DrawSplitter.Merge(inner_window->DrawList); @@ -1808,7 +1808,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n) window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2); window->SkipItems = column->SkipItems; - if (table->Flags & ImGuiTableFlags_NoClipX) + if (table->Flags & ImGuiTableFlags_NoClip) { table->DrawSplitter.SetCurrentChannel(window->DrawList, 1); } From 30216083920fa2bcefa5760d0a2e07b8cb52bb46 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 23 Sep 2020 17:53:52 +0200 Subject: [PATCH 466/959] Tables: (Breaking) Add TableSetupScrollFreeze() api, remove ImGuiTableFlags_ScrollFreezeXXX flags, tweak comments, move columns block. Avoid awkwardly named ScrollFreeze flags, raise limit over 3, and will allow for future api maybe freezing bottom/right side. --- imgui.h | 72 +++++++++++++++++++++++------------------------- imgui_demo.cpp | 40 ++++++++++++--------------- imgui_tables.cpp | 39 ++++++++++++++------------ 3 files changed, 74 insertions(+), 77 deletions(-) diff --git a/imgui.h b/imgui.h index 83b5747d..b9515138 100644 --- a/imgui.h +++ b/imgui.h @@ -652,28 +652,22 @@ namespace ImGui // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. - // Columns - // - You can also use SameLine(pos_x) to mimic simplified columns. - // - The columns API is work-in-progress and rather lacking (columns are arguably the worst part of dear imgui at the moment!) - // - There is a maximum of 64 columns. - // - Currently working on new 'Tables' api which will replace columns around Q2 2020 (see GitHub #2957). - IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); - IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished - IMGUI_API int GetColumnIndex(); // get current column index - IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column - IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column - IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f - IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column - IMGUI_API int GetColumnsCount(); - // Tables - // [ALPHA API] API will evolve! (FIXME-TABLE) + // [ALPHA API] API will evolve! (see: FIXME-TABLE) // - Full-featured replacement for old Columns API - // - In most situations you can use TableNextRow() + TableSetColumnIndex() to populate a table. - // - If you are using tables as a sort of grid, populating every columns with the same type of contents, - // you may prefer using TableNextCell() instead of TableNextRow() + TableSetColumnIndex(). // - See Demo->Tables for details. // - See ImGuiTableFlags_ and ImGuiTableColumnsFlags_ enums for a description of available flags. + // The typical call flow is: + // - 1. Call BeginTable() + // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults + // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows + // - 4. Optionally call TableAutoHeaders() to submit a header row (names will be pulled from data submitted to TableSetupColumns) + // - 4. Populate contents + // - In most situations you can use TableNextRow() + TableSetColumnIndex() to start appending into a column. + // - If you are using tables as a sort of grid, where every columns is holding the same type of contents, + // you may prefer using TableNextCell() instead of TableNextRow() + TableSetColumnIndex(). + // - Submit your content with regular ImGui function. + // - 5. Call EndTable() #define IMGUI_HAS_TABLE 1 IMGUI_API bool BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! @@ -681,26 +675,40 @@ namespace ImGui IMGUI_API bool TableNextCell(); // append into the next column (next column, or next row if currently in last column). Return true if column is visible. IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true if column is visible. IMGUI_API int TableGetColumnIndex(); // return current column index. - IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. - IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Pass -1 to use current column. - IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Pass -1 to use current column. - IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. - IMGUI_API void TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. // Tables: Headers & Columns declaration + // - Use TableSetupScrollFreeze() to lock columns (from the right) or rows (from the top) so they stay visible when scrolled. // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. // Important: this will not display anything! The name passed to TableSetupColumn() is used by TableAutoHeaders() and context-menus. // - Use TableAutoHeaders() to create a row and automatically submit a TableHeader() for each column. // Headers are required to perform some interactions: reordering, sorting, context menu (FIXME-TABLE: context menu should work without!) // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in some advanced cases (e.g. adding custom widgets in header row). + IMGUI_API void TableSetupScrollFreeze(int columns, int rows); IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = -1.0f, ImU32 user_id = 0); IMGUI_API void TableAutoHeaders(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) - // Tables: Sorting - // - Call TableGetSortSpecs() to retrieve latest sort specs for the table. Return value will be NULL if no sorting. - // - When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. + // Tables: Miscellaneous functions + // - Most functions taking 'int column_n' treat the default value of -1 as the same as passing the current column index + // - Sorting: call TableGetSortSpecs() to retrieve latest sort specs for the table. Return value will be NULL if no sorting. + // When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed since last call, or the first time. // Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! - // - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()! + // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). + IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. + IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Pass -1 to use current column. + IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Pass -1 to use current column. + IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). + IMGUI_API void TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. + + // Columns (Legacy API, prefer using Tables) + // - You can also use SameLine(pos_x) to mimic simplified columns. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); + IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column + IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API int GetColumnsCount(); // Tab Bars, Tabs IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar @@ -1062,19 +1070,9 @@ enum ImGuiTableFlags_ ImGuiTableFlags_ScrollX = 1 << 20, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. ImGuiTableFlags_ScrollY = 1 << 21, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, - ImGuiTableFlags_ScrollFreezeTopRow = 1 << 22, // We can lock 1 to 3 rows (starting from the top). Use with ScrollY enabled. - ImGuiTableFlags_ScrollFreeze2Rows = 2 << 22, - ImGuiTableFlags_ScrollFreeze3Rows = 3 << 22, - ImGuiTableFlags_ScrollFreezeLeftColumn = 1 << 24, // We can lock 1 to 3 columns (starting from the left). Use with ScrollX enabled. - ImGuiTableFlags_ScrollFreeze2Columns = 2 << 24, - ImGuiTableFlags_ScrollFreeze3Columns = 3 << 24, // [Internal] Combinations and masks ImGuiTableFlags_SizingPolicyMaskX_ = ImGuiTableFlags_SizingPolicyStretchX | ImGuiTableFlags_SizingPolicyFixedX, - ImGuiTableFlags_ScrollFreezeRowsShift_ = 22, - ImGuiTableFlags_ScrollFreezeColumnsShift_ = 24, - ImGuiTableFlags_ScrollFreezeRowsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeRowsShift_, - ImGuiTableFlags_ScrollFreezeColumnsMask_ = 0x03 << ImGuiTableFlags_ScrollFreezeColumnsShift_ }; // Flags for ImGui::TableSetupColumn() diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f26d6349..78c4ecb0 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3630,12 +3630,12 @@ static void ShowDemoWindowTables() { HelpMarker("Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\nWe also demonstrate using ImGuiListClipper to virtualize the submission of many items."); ImVec2 size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 7); - static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); - ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); if (ImGui::BeginTable("##table1", 3, flags, size)) { + ImGui::TableSetupScrollFreeze(0, 1); // Make top row always visible ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None); @@ -3665,14 +3665,19 @@ static void ShowDemoWindowTables() { HelpMarker("When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingPolicyFixedX, as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\nAlso note that as of the current version, you will almost always want to enable ScrollY along with ScrollX, because the container window won't automatically extend vertically to fix contents (this may be improved in future versions)."); ImVec2 size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 10); - static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_ScrollFreezeLeftColumn | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + static int freeze_cols = 1; + static int freeze_rows = 1; ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); - ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); - ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); if (ImGui::BeginTable("##table1", 7, flags, size)) { - ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of ImGuiTableFlags_ScrollFreezeLeftColumn + ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); + ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of TableSetupScrollFreeze() ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None); @@ -3978,7 +3983,6 @@ static void ShowDemoWindowTables() { static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg; //ImGui::CheckboxFlags("ImGuiTableFlags_Scroll", (unsigned int*)&flags, ImGuiTableFlags_Scroll); - //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); if (ImGui::BeginTable("##3ways", 3, flags)) { @@ -4187,7 +4191,7 @@ static void ShowDemoWindowTables() static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_MultiSortable | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV - | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollFreezeTopRow; + | ImGuiTableFlags_ScrollY; if (ImGui::BeginTable("##table", 4, flags, ImVec2(0, 250), 0.0f)) { // Declare columns @@ -4201,6 +4205,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Name); ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Action); ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, -1.0f, MyItemColumnID_Quantity); + ImGui::TableSetupScrollFreeze(0, 1); // Make row always visible // Sort our data if sort specs have been changed! if (ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs()) @@ -4246,14 +4251,14 @@ static void ShowDemoWindowTables() ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_MultiSortable | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY - | ImGuiTableFlags_ScrollFreezeTopRow | ImGuiTableFlags_ScrollFreezeLeftColumn | ImGuiTableFlags_SizingPolicyFixedX ; enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable }; static int contents_type = CT_FillButton; const char* contents_type_names[] = { "Text", "Button", "SmallButton", "FillButton", "Selectable" }; - + static int freeze_cols = 1; + static int freeze_rows = 1; static int items_count = IM_ARRAYSIZE(template_items_names); static ImVec2 outer_size_value = ImVec2(0, 250); static float row_min_height = 0.0f; // Auto @@ -4314,20 +4319,10 @@ static void ShowDemoWindowTables() ImGui::Indent(); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); - - // For the purpose of our "advanced" demo, we expose the 3 freezing variants on both axises instead of only exposing the most common flag. - //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeTopRow", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeTopRow); - //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollFreezeLeftColumn", (unsigned int*)&flags, ImGuiTableFlags_ScrollFreezeLeftColumn); - int freeze_row_count = (flags & ImGuiTableFlags_ScrollFreezeRowsMask_) >> ImGuiTableFlags_ScrollFreezeRowsShift_; - int freeze_col_count = (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) >> ImGuiTableFlags_ScrollFreezeColumnsShift_; ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); - if (ImGui::DragInt("ImGuiTableFlags_ScrollFreezeTopRow/2Rows/3Rows", &freeze_row_count, 0.2f, 0, 3)) - if (freeze_row_count >= 0 && freeze_row_count <= 3) - flags = (flags & ~ImGuiTableFlags_ScrollFreezeRowsMask_) | (freeze_row_count << ImGuiTableFlags_ScrollFreezeRowsShift_); + ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); - if (ImGui::DragInt("ImGuiTableFlags_ScrollFreezeLeftColumn/2Columns/3Columns", &freeze_col_count, 0.2f, 0, 3)) - if (freeze_col_count >= 0 && freeze_col_count <= 3) - flags = (flags & ~ImGuiTableFlags_ScrollFreezeColumnsMask_) | (freeze_col_count << ImGuiTableFlags_ScrollFreezeColumnsShift_); + ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); ImGui::Unindent(); @@ -4386,6 +4381,7 @@ static void ShowDemoWindowTables() // Declare columns // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | (lock_first_column_visibility ? ImGuiTableColumnFlags_NoHide : 0), -1.0f, MyItemColumnID_ID); ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Name); ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Action); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 65701724..b67f1107 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -69,6 +69,7 @@ // | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) // | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width // - TableSetupColumn() user submit columns details (optional) +// - TableSetupScrollFreeze() user submit scroll freeze information (optional) // - TableUpdateLayout() [Internal] automatically called by the FIRST call to TableNextRow() or Table*Header(): lock all widths, columns positions, clipping rectangles // | TableUpdateDrawChannels() - setup ImDrawList channels // | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission @@ -113,22 +114,10 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) if (flags & ImGuiTableFlags_Resizable) flags |= ImGuiTableFlags_BordersInnerV; - // Adjust flags: disable top rows freezing if there's no scrolling. - // We could want to assert if ScrollFreeze was set without the corresponding scroll flag, but that would hinder demos. - if ((flags & ImGuiTableFlags_ScrollX) == 0) - flags &= ~ImGuiTableFlags_ScrollFreezeColumnsMask_; - if ((flags & ImGuiTableFlags_ScrollY) == 0) - flags &= ~ImGuiTableFlags_ScrollFreezeRowsMask_; - // Adjust flags: disable NoHostExtendY if we have any scrolling going on if ((flags & ImGuiTableFlags_NoHostExtendY) && (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0) flags &= ~ImGuiTableFlags_NoHostExtendY; - // Adjust flags: we don't support NoClip with (FreezeColumns > 0) - // We could with some work but it doesn't appear to be worth the effort. - //if (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) - // flags &= ~ImGuiTableFlags_NoClip; - return flags; } @@ -290,11 +279,9 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->BackgroundClipRect = table->InnerClipRect; table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() - table->FreezeRowsRequest = (ImS8)((flags & ImGuiTableFlags_ScrollFreezeRowsMask_) >> ImGuiTableFlags_ScrollFreezeRowsShift_); - table->FreezeRowsCount = (inner_window->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0; - table->FreezeColumnsRequest = (ImS8)((flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) >> ImGuiTableFlags_ScrollFreezeColumnsShift_); - table->FreezeColumnsCount = (inner_window->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; - table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); + table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any + table->FreezeColumnsRequest = table->FreezeColumnsCount = 0; + table->IsFreezeRowsPassed = true; table->DeclColumnsCount = 0; table->RightMostVisibleColumn = -1; @@ -487,6 +474,22 @@ void ImGui::TableBeginUpdateColumns(ImGuiTable* table) table->InnerWindow->SkipItems = false; } +void ImGui::TableSetupScrollFreeze(int columns, int rows) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); + IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!"); + IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS); + IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit + + table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImS8)columns : 0; + table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; + table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImS8)rows : 0; + table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0; + table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); +} + void ImGui::TableUpdateDrawChannels(ImGuiTable* table) { // Allocate draw channels. @@ -1527,7 +1530,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); - IM_ASSERT(!table->IsLayoutLocked && "Need to call call TableSetupColumn() before first row!"); + IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!"); IM_ASSERT(table->DeclColumnsCount >= 0 && table->DeclColumnsCount < table->ColumnsCount && "Called TableSetupColumn() too many times!"); ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount]; From 9b37087fbee0d8b9a33bb4ec456a5a349ba1a18b Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 24 Sep 2020 14:33:40 +0200 Subject: [PATCH 467/959] Tables: (Breaking) Rename TableAutoHeaders() to TableHeadersRow() + added TableGetColumnCount(). --- imgui.h | 11 ++++++----- imgui_demo.cpp | 36 ++++++++++++++++++------------------ imgui_tables.cpp | 37 ++++++++++++++++++++----------------- 3 files changed, 44 insertions(+), 40 deletions(-) diff --git a/imgui.h b/imgui.h index b9515138..9f0e9c8b 100644 --- a/imgui.h +++ b/imgui.h @@ -661,7 +661,7 @@ namespace ImGui // - 1. Call BeginTable() // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows - // - 4. Optionally call TableAutoHeaders() to submit a header row (names will be pulled from data submitted to TableSetupColumns) + // - 4. Optionally call TableHeadersRow() to submit a header row (names will be pulled from data submitted to TableSetupColumns) // - 4. Populate contents // - In most situations you can use TableNextRow() + TableSetColumnIndex() to start appending into a column. // - If you are using tables as a sort of grid, where every columns is holding the same type of contents, @@ -678,13 +678,13 @@ namespace ImGui // Tables: Headers & Columns declaration // - Use TableSetupScrollFreeze() to lock columns (from the right) or rows (from the top) so they stay visible when scrolled. // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. - // Important: this will not display anything! The name passed to TableSetupColumn() is used by TableAutoHeaders() and context-menus. - // - Use TableAutoHeaders() to create a row and automatically submit a TableHeader() for each column. + // Important: this will not display anything! The name passed to TableSetupColumn() is used by TableHeadersRow() and context-menus. + // - Use TableHeadersRow() to create a row and automatically submit a TableHeader() for each column. // Headers are required to perform some interactions: reordering, sorting, context menu (FIXME-TABLE: context menu should work without!) // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in some advanced cases (e.g. adding custom widgets in header row). IMGUI_API void TableSetupScrollFreeze(int columns, int rows); IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = -1.0f, ImU32 user_id = 0); - IMGUI_API void TableAutoHeaders(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu + IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) // Tables: Miscellaneous functions // - Most functions taking 'int column_n' treat the default value of -1 as the same as passing the current column index @@ -692,6 +692,7 @@ namespace ImGui // When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed since last call, or the first time. // Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). + IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Pass -1 to use current column. IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Pass -1 to use current column. @@ -1042,7 +1043,7 @@ enum ImGuiTableFlags_ // Features ImGuiTableFlags_None = 0, ImGuiTableFlags_Resizable = 1 << 0, // Allow resizing columns. - ImGuiTableFlags_Reorderable = 1 << 1, // Allow reordering columns (need calling TableSetupColumn() + TableAutoHeaders() or TableHeaders() to display headers) + ImGuiTableFlags_Reorderable = 1 << 1, // Allow reordering columns (need calling TableSetupColumn() + TableHeadersRow() to display headers) ImGuiTableFlags_Hideable = 1 << 2, // Allow hiding columns (with right-click on header) (FIXME-TABLE: allow without headers). ImGuiTableFlags_Sortable = 1 << 3, // Allow sorting on one column (sort_specs_count will always be == 1). Call TableGetSortSpecs() to obtain sort specs. ImGuiTableFlags_MultiSortable = 1 << 4, // Allow sorting on multiple columns by holding Shift (sort_specs_count may be > 1). Call TableGetSortSpecs() to obtain sort specs. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 78c4ecb0..f95bbffe 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3513,7 +3513,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);// | ImGuiTableColumnFlags_NoResize); ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthStretch); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); for (int row = 0; row < 5; row++) { ImGui::TableNextRow(); @@ -3533,7 +3533,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("DDD", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("EEE", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("FFF", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); for (int row = 0; row < 5; row++) { ImGui::TableNextRow(); @@ -3560,12 +3560,12 @@ static void ShowDemoWindowTables() if (ImGui::BeginTable("##table1", 3, flags)) { - // Submit columns name with TableSetupColumn() and call TableAutoHeaders() to create a row with a header in each column. + // Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column. // (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.) ImGui::TableSetupColumn("One"); ImGui::TableSetupColumn("Two"); ImGui::TableSetupColumn("Three"); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); for (int row = 0; row < 6; row++) { ImGui::TableNextRow(); @@ -3583,7 +3583,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("One"); ImGui::TableSetupColumn("Two"); ImGui::TableSetupColumn("Three"); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); for (int row = 0; row < 6; row++) { ImGui::TableNextRow(); @@ -3639,7 +3639,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); ImGuiListClipper clipper; clipper.Begin(1000); while (clipper.Step()) @@ -3684,7 +3684,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("Four", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Five", ImGuiTableColumnFlags_None); ImGui::TableSetupColumn("Six", ImGuiTableColumnFlags_None); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); for (int row = 0; row < 20; row++) { ImGui::TableNextRow(); @@ -3750,7 +3750,7 @@ static void ShowDemoWindowTables() { for (int column = 0; column < column_count; column++) ImGui::TableSetupColumn(column_names[column], column_flags[column]); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); for (int row = 0; row < 8; row++) { ImGui::Indent(2.0f); // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags. @@ -3778,7 +3778,7 @@ static void ShowDemoWindowTables() { ImGui::TableSetupColumn("A0"); ImGui::TableSetupColumn("A1"); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); ImGui::TableNextRow(); ImGui::Text("A0 Cell 0"); { @@ -3787,7 +3787,7 @@ static void ShowDemoWindowTables() { ImGui::TableSetupColumn("B0"); ImGui::TableSetupColumn("B1"); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); ImGui::Text("B0 Cell 0"); @@ -3990,7 +3990,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 6); ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 10); - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); // Simple storage to output a dummy file-system. struct MyTreeNode @@ -4048,7 +4048,7 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } - // Demonstrate using TableHeader() calls instead of TableAutoHeaders() + // Demonstrate using TableHeader() calls instead of TableHeadersRow() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Custom headers")) @@ -4064,7 +4064,7 @@ static void ShowDemoWindowTables() // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. static bool column_selected[3] = {}; - // Instead of calling TableAutoHeaders() we'll submit custom headers ourselves + // Instead of calling TableHeadersRow() we'll submit custom headers ourselves ImGui::TableNextRow(ImGuiTableRowFlags_Headers); for (int column = 0; column < COLUMNS_COUNT; column++) { @@ -4095,12 +4095,12 @@ static void ShowDemoWindowTables() ImGui::TreePop(); } - // Demonstrate creating custom context menus inside columns, while playing it nice with context menus provided by TableHeader()/TableAutoHeaders() + // Demonstrate creating custom context menus inside columns, while playing it nice with context menus provided by TableHeadersRow()/TableHeader() if (open_action != -1) ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Context menus")) { - HelpMarker("By default, TableHeader()/TableAutoHeaders() will open a context-menu on right-click."); + HelpMarker("By default, TableHeadersRow()/TableHeader() will open a context-menu on right-click."); ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders; const int COLUMNS_COUNT = 3; if (ImGui::BeginTable("##table1", COLUMNS_COUNT, flags)) @@ -4110,7 +4110,7 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("Three"); // Context Menu 1: right-click on header (including empty section after the third column!) should open Default Table Popup - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); for (int row = 0; row < 4; row++) { ImGui::TableNextRow(); @@ -4219,7 +4219,7 @@ static void ShowDemoWindowTables() } // Display data - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); ImGuiListClipper clipper; clipper.Begin(items.Size); while (clipper.Step()) @@ -4408,7 +4408,7 @@ static void ShowDemoWindowTables() // Show headers if (show_headers) - ImGui::TableAutoHeaders(); + ImGui::TableHeadersRow(); // Show data // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b67f1107..9a28a00d 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -75,11 +75,11 @@ // | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission // | TableDrawContextMenu() - draw right-click context menu //----------------------------------------------------------------------------- -// - TableAutoHeaders() or TableHeader() user submit a headers row (optional) +// - TableHeadersRow() or TableHeader() user submit a headers row (optional) // | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction // | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu // - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) -// - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders() +// - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableHeadersRow() // | TableEndCell() - close existing cell if not the first time // | TableBeginCell() - enter into current cell // - [...] user emit contents @@ -1867,6 +1867,13 @@ bool ImGui::TableNextCell() return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; } +int ImGui::TableGetColumnCount() +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + return table ? table->ColumnsCount : 0; +} + const char* ImGui::TableGetColumnName(int column_n) { ImGuiContext& g = *GImGui; @@ -2066,18 +2073,20 @@ void ImGui::TableOpenContextMenu(ImGuiTable* table, int column_n) // This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). // The intent is that advanced users willing to create customized headers would not need to use this helper // and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets. -void ImGui::TableAutoHeaders() +// See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this. +void ImGui::TableHeadersRow() { ImGuiStyle& style = ImGui::GetStyle(); ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); - const int columns_count = table->ColumnsCount; + IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!"); // Calculate row height (for the unlikely case that labels may be are multi-line) - float row_y1 = GetCursorScreenPos().y; + // If we didn't do that, uneven header height would work but their highlight won't cover the full row height. float row_height = GetTextLineHeight(); + const float row_y1 = GetCursorScreenPos().y; + const int columns_count = TableGetColumnCount(); for (int column_n = 0; column_n < columns_count; column_n++) if (TableGetColumnIsVisible(column_n)) row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y); @@ -2095,8 +2104,6 @@ void ImGui::TableAutoHeaders() if (!TableSetColumnIndex(column_n)) continue; - const char* name = TableGetColumnName(column_n); - // [DEBUG] Test custom user elements #if 0 if (column_n < 2) @@ -2112,23 +2119,19 @@ void ImGui::TableAutoHeaders() #endif // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them) - // - in your own code you may omit the PushID/PopID all-together, provided you know you know they won't collide + // - in your own code you may omit the PushID/PopID all-together, provided you know they won't collide // - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier. + const char* name = TableGetColumnName(column_n); PushID(table->InstanceCurrent * table->ColumnsCount + column_n); TableHeader(name); PopID(); } - // FIXME-TABLE: This is not user-land code any more + need to explain WHY this is here! (added in fa88f023) - //window->SkipItems = table->HostSkipItems; - // Allow opening popup from the right-most section after the last column. - // (We don't actually need to use ImGuiHoveredFlags_AllowWhenBlockedByPopup because in reality this is generally - // not required anymore.. because popup opening code tends to be reacting on IsMouseReleased() and the click would - // already have closed any other popups!) // FIXME-TABLE: TableOpenContextMenu() is not public yet. + ImVec2 mouse_pos = ImGui::GetMousePos(); if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count) - if (g.IO.MousePos.y >= row_y1 && g.IO.MousePos.y < row_y1 + row_height) + if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height) TableOpenContextMenu(table, -1); // Will open a non-column-specific popup. } @@ -2145,7 +2148,7 @@ void ImGui::TableHeader(const char* label) return; ImGuiTable* table = g.CurrentTable; - IM_ASSERT(table != NULL && "Need to call TableAutoHeaders() after BeginTable()!"); + IM_ASSERT(table != NULL && "Need to call TableHeader() after BeginTable()!"); IM_ASSERT(table->CurrentColumn != -1); const int column_n = table->CurrentColumn; ImGuiTableColumn* column = &table->Columns[column_n]; From cc12ea084bb68893fc23e220ce44bcf3a6764acd Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 24 Sep 2020 15:10:47 +0200 Subject: [PATCH 468/959] Tables: Added TableSetColumnSortDirection() + added in default context menu code (disabled, feels unnecessary, but work is done to ensure programmatic access) --- imgui.h | 2 +- imgui_internal.h | 4 +- imgui_tables.cpp | 104 +++++++++++++++++++++++++++-------------------- 3 files changed, 64 insertions(+), 46 deletions(-) diff --git a/imgui.h b/imgui.h index 9f0e9c8b..bee32fc3 100644 --- a/imgui.h +++ b/imgui.h @@ -1073,7 +1073,7 @@ enum ImGuiTableFlags_ ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, // [Internal] Combinations and masks - ImGuiTableFlags_SizingPolicyMaskX_ = ImGuiTableFlags_SizingPolicyStretchX | ImGuiTableFlags_SizingPolicyFixedX, + ImGuiTableFlags_SizingPolicyMaskX_ = ImGuiTableFlags_SizingPolicyStretchX | ImGuiTableFlags_SizingPolicyFixedX }; // Flags for ImGui::TableSetupColumn() diff --git a/imgui_internal.h b/imgui_internal.h index 054252f2..df026c06 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2278,7 +2278,7 @@ namespace ImGui IMGUI_API void TableDrawContextMenu(ImGuiTable* table); IMGUI_API void TableOpenContextMenu(ImGuiTable* table, int column_n); IMGUI_API void TableReorderDrawChannelsForMerge(ImGuiTable* table); - IMGUI_API void TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* column, bool add_to_existing_sort_orders); + IMGUI_API void TableSetColumnSortDirection(ImGuiTable* table, int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs); IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); IMGUI_API void TableSortSpecsBuild(ImGuiTable* table); IMGUI_API void TableBeginRow(ImGuiTable* table); @@ -2292,7 +2292,7 @@ namespace ImGui IMGUI_API void PushTableBackground(); IMGUI_API void PopTableBackground(); - // Tables - Settings + // Tables: Settings IMGUI_API void TableLoadSettings(ImGuiTable* table); IMGUI_API void TableSaveSettings(ImGuiTable* table); IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 9a28a00d..372b1edf 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1998,25 +1998,26 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table) return; bool want_separator = false; - const int selected_column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1; + const int column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1; + ImGuiTableColumn* column = (column_n != -1) ? &table->Columns[column_n] : NULL; // Sizing if (table->Flags & ImGuiTableFlags_Resizable) { - if (ImGuiTableColumn* selected_column = (selected_column_n != -1) ? &table->Columns[selected_column_n] : NULL) + if (column != NULL) { - const bool can_resize = !(selected_column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && selected_column->IsVisible; + const bool can_resize = !(column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && column->IsVisible; if (MenuItem("Size column to fit", NULL, false, can_resize)) - TableSetColumnAutofit(table, selected_column_n); + TableSetColumnAutofit(table, column_n); } if (MenuItem("Size all columns to fit", NULL)) { - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) { - ImGuiTableColumn* column = &table->Columns[column_n]; - if (column->IsVisible) - TableSetColumnAutofit(table, column_n); + ImGuiTableColumn* other_column = &table->Columns[other_column_n]; + if (other_column->IsVisible) + TableSetColumnAutofit(table, other_column_n); } } want_separator = true; @@ -2030,27 +2031,43 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table) want_separator = true; } + // Sorting +#if 0 + if ((table->Flags & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0) + { + if (want_separator) + Separator(); + want_separator = true; + + bool append_to_sort_specs = g.IO.KeyShift; + if (MenuItem("Sort in Ascending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0)) + TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs); + if (MenuItem("Sort in Descending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0)) + TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs); + } +#endif + // Hiding / Visibility if (table->Flags & ImGuiTableFlags_Hideable) { if (want_separator) Separator(); - want_separator = false; + want_separator = true; PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true); - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) { - ImGuiTableColumn* column = &table->Columns[column_n]; - const char* name = TableGetColumnName(table, column_n); + ImGuiTableColumn* other_column = &table->Columns[other_column_n]; + const char* name = TableGetColumnName(table, other_column_n); if (name == NULL) name = ""; // Make sure we can't hide the last active column - bool menu_item_active = (column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true; - if (column->IsVisible && table->ColumnsVisibleCount <= 1) + bool menu_item_active = (other_column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true; + if (other_column->IsVisible && table->ColumnsVisibleCount <= 1) menu_item_active = false; - if (MenuItem(name, NULL, column->IsVisible, menu_item_active)) - column->IsVisibleNextFrame = !column->IsVisible; + if (MenuItem(name, NULL, other_column->IsVisible, menu_item_active)) + other_column->IsVisibleNextFrame = !other_column->IsVisible; } PopItemFlag(); } @@ -2245,7 +2262,17 @@ void ImGui::TableHeader(const char* label) // Handle clicking on column header to adjust Sort Order if (pressed && table->ReorderColumn != column_n) - TableSortSpecsClickColumn(table, column, g.IO.KeyShift); + { + // Set new sort direction + // - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. + // - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. + ImGuiSortDirection sort_direction; + if (column->SortOrder == -1) + sort_direction = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; + else + sort_direction = (column->SortDirection == ImGuiSortDirection_Ascending) ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; + TableSetColumnSortDirection(table, column_n, sort_direction, g.IO.KeyShift); + } } // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will @@ -2265,38 +2292,29 @@ void ImGui::TableHeader(const char* label) TableOpenContextMenu(table, column_n); } -void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* clicked_column, bool add_to_existing_sort_orders) +// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert +// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code. +void ImGui::TableSetColumnSortDirection(ImGuiTable* table, int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs) { if (!(table->Flags & ImGuiTableFlags_MultiSortable)) - add_to_existing_sort_orders = false; + append_to_sort_specs = false; ImS8 sort_order_max = 0; - if (add_to_existing_sort_orders) - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) - sort_order_max = ImMax(sort_order_max, table->Columns[column_n].SortOrder); + if (append_to_sort_specs) + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) + sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder); - for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + ImGuiTableColumn* column = &table->Columns[column_n]; + column->SortDirection = (ImS8)sort_direction; + if (column->SortOrder == -1 || !append_to_sort_specs) + column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0; + + for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++) { - ImGuiTableColumn* column = &table->Columns[column_n]; - if (column == clicked_column) - { - // Set new sort direction and sort order - // - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. - // - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. - // - Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert - // the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code. - if (column->SortOrder == -1) - column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending); - else - column->SortDirection = (ImU8)((column->SortDirection == ImGuiSortDirection_Ascending) ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending); - if (column->SortOrder == -1 || !add_to_existing_sort_orders) - column->SortOrder = add_to_existing_sort_orders ? sort_order_max + 1 : 0; - } - else if (!add_to_existing_sort_orders) - { - column->SortOrder = -1; - } - TableFixColumnSortDirection(column); + ImGuiTableColumn* other_column = &table->Columns[other_column_n]; + if (other_column != column && !append_to_sort_specs) + other_column->SortOrder = -1; + TableFixColumnSortDirection(other_column); } table->IsSettingsDirty = true; table->IsSortSpecsDirty = true; From 25b5cc2f9597c268f0029a9d6f85acbd3825a65d Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 28 Sep 2020 17:30:39 +0200 Subject: [PATCH 469/959] Tables: Fixes to support any number of frozen rows (over modifications to clipper code in master) + make clipper run eval after clipect update --- imgui.cpp | 21 ++++++++++++++++----- imgui.h | 1 + imgui_tables.cpp | 4 ++++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 823fe725..4b85256d 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -2237,6 +2237,7 @@ void ImGuiListClipper::Begin(int items_count, float items_height) StartPosY = window->DC.CursorPos.y; ItemsHeight = items_height; ItemsCount = items_count; + ItemsFrozen = 0; StepNo = 0; DisplayStart = -1; DisplayEnd = 0; @@ -2249,7 +2250,7 @@ void ImGuiListClipper::End() // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX && DisplayStart >= 0) - SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); + SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight); ItemsCount = -1; StepNo = 3; } @@ -2273,12 +2274,22 @@ bool ImGuiListClipper::Step() // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) if (StepNo == 0) { + // While we are in frozen row state, keep displaying items one by one, unclipped + // FIXME: Could be stored as a table-agnostic state. + if (table != NULL && !table->IsFreezeRowsPassed) + { + DisplayStart = ItemsFrozen; + DisplayEnd = ItemsFrozen + 1; + ItemsFrozen++; + return true; + } + StartPosY = window->DC.CursorPos.y; if (ItemsHeight <= 0.0f) { // Submit the first item so we can measure its height (generally it is 0..1) - DisplayStart = 0; - DisplayEnd = 1; + DisplayStart = ItemsFrozen; + DisplayEnd = ItemsFrozen + 1; StepNo = 1; return true; } @@ -2319,7 +2330,7 @@ bool ImGuiListClipper::Step() // Seek cursor if (DisplayStart > already_submitted) - SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); + SetCursorPosYAndSetupForPrevLine(StartPosY + (DisplayStart - ItemsFrozen) * ItemsHeight, ItemsHeight); StepNo = 3; return true; @@ -2331,7 +2342,7 @@ bool ImGuiListClipper::Step() { // Seek cursor if (ItemsCount < INT_MAX) - SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; return false; } diff --git a/imgui.h b/imgui.h index bee32fc3..beb4182f 100644 --- a/imgui.h +++ b/imgui.h @@ -2092,6 +2092,7 @@ struct ImGuiListClipper // [Internal] int ItemsCount; int StepNo; + int ItemsFrozen; float ItemsHeight; float StartPosY; diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 372b1edf..3e431597 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1774,6 +1774,10 @@ void ImGui::TableEndRow(ImGuiTable* table) column->DrawChannelCurrent = column->DrawChannelRowsAfterFreeze; column->ClipRect.Min.y = r.Min.y; } + + // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y + SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect); + table->DrawSplitter.SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent); } if (!(table->RowFlags & ImGuiTableRowFlags_Headers)) From 248960d64c9b219bf1f43bd61875a092981b1556 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2020 22:37:59 +0200 Subject: [PATCH 470/959] Tables: Fix ImGuiTableColumnFlags_WidthAlwaysAutoResize columns when clipped (which would be default behavior without _Resizable and when clipping/scrolling) --- imgui_tables.cpp | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 3e431597..b4425db8 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -646,21 +646,19 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) if (column->Flags & (ImGuiTableColumnFlags_WidthAlwaysAutoResize | ImGuiTableColumnFlags_WidthFixed)) { - // Latch initial size for fixed columns + // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!) count_fixed += 1; - const bool auto_fit = (column->AutoFitQueue != 0x00) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize); - if (auto_fit) - { + if ((column->AutoFitQueue != 0x00) || ((column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) && !column->IsClipped)) column->WidthRequest = column_width_ideal; - // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets - // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very - // large height (= first frame scrollbar display very off + clipper would skip lots of items). - // This is merely making the side-effect less extreme, but doesn't properly fixes it. - // FIXME: Move this to ->WidthGiven to avoid temporary lossyless? - if (column->AutoFitQueue > 0x01 && table->IsInitializing) - column->WidthRequest = ImMax(column->WidthRequest, min_column_width * 4.0f); - } + // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets + // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very + // large height (= first frame scrollbar display very off + clipper would skip lots of items). + // This is merely making the side-effect less extreme, but doesn't properly fixes it. + // FIXME: Move this to ->WidthGiven to avoid temporary lossyless? + if (column->AutoFitQueue > 0x01 && table->IsInitializing) + column->WidthRequest = ImMax(column->WidthRequest, min_column_width * 4.0f); + sum_width_fixed_requests += column->WidthRequest; } else @@ -2159,7 +2157,7 @@ void ImGui::TableHeadersRow() // Emit a column header (text + optional sort order) // We cpu-clip text here so that all columns headers can be merged into a same draw call. // Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() -// FIXME-TABLE: Should hold a selection state. +// FIXME-TABLE: Could hold a selection state. // FIXME-TABLE: Style confusion between CellPadding.y and FramePadding.y void ImGui::TableHeader(const char* label) { From b1ebf964f59e97874b06c8fef4ee47e312a310d6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 30 Sep 2020 23:42:37 +0200 Subject: [PATCH 471/959] Tables: Moved TableSetColumnIndex() next to TableNextCell() since they are so similar + made NextCell() crash proof. --- imgui_tables.cpp | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/imgui_tables.cpp b/imgui_tables.cpp index b4425db8..d8681d4b 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1850,6 +1850,8 @@ bool ImGui::TableNextCell() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; + if (!table) + return false; if (table->CurrentColumn != -1 && table->CurrentColumn + 1 < table->ColumnsCount) { @@ -1869,6 +1871,28 @@ bool ImGui::TableNextCell() return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; } +bool ImGui::TableSetColumnIndex(int column_n) +{ + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (!table) + return false; + + if (table->CurrentColumn != column_n) + { + if (table->CurrentColumn != -1) + TableEndCell(table); + IM_ASSERT(column_n >= 0 && table->ColumnsCount); + TableBeginCell(table, column_n); + } + + // FIXME-TABLE: Need to clarify if we want to allow IsItemHovered() here + //g.CurrentWindow->DC.LastItemStatusFlags = (column_n == table->HoveredColumn) ? ImGuiItemStatusFlags_HoveredRect : ImGuiItemStatusFlags_None; + + // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping. + return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; +} + int ImGui::TableGetColumnCount() { ImGuiContext& g = *GImGui; @@ -1908,28 +1932,6 @@ int ImGui::TableGetColumnIndex() return table->CurrentColumn; } -bool ImGui::TableSetColumnIndex(int column_idx) -{ - ImGuiContext& g = *GImGui; - ImGuiTable* table = g.CurrentTable; - if (!table) - return false; - - if (table->CurrentColumn != column_idx) - { - if (table->CurrentColumn != -1) - TableEndCell(table); - IM_ASSERT(column_idx >= 0 && table->ColumnsCount); - TableBeginCell(table, column_idx); - } - - // FIXME-TABLE: Need to clarify if we want to allow IsItemHovered() here - //g.CurrentWindow->DC.LastItemStatusFlags = (column_n == table->HoveredColumn) ? ImGuiItemStatusFlags_HoveredRect : ImGuiItemStatusFlags_None; - - // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping. - return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_idx)) != 0; -} - // Return the cell rectangle based on currently known height. // Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations. // The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it. From 6182973bdeb7acb38c71cb64a58afc3b750a539a Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Oct 2020 14:03:25 +0200 Subject: [PATCH 472/959] Tables: (Breaking) Rename TableNextCell() to TableNextColumn(), made TableNextRow() NOT enter into first column. --- imgui.h | 30 ++++++++++++++-------- imgui_demo.cpp | 65 ++++++++++++++++++++++++++---------------------- imgui_tables.cpp | 26 +++++++++++-------- 3 files changed, 69 insertions(+), 52 deletions(-) diff --git a/imgui.h b/imgui.h index beb4182f..c7516b01 100644 --- a/imgui.h +++ b/imgui.h @@ -653,7 +653,7 @@ namespace ImGui IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open. // Tables - // [ALPHA API] API will evolve! (see: FIXME-TABLE) + // [ALPHA API] API may evolve! // - Full-featured replacement for old Columns API // - See Demo->Tables for details. // - See ImGuiTableFlags_ and ImGuiTableColumnsFlags_ enums for a description of available flags. @@ -662,28 +662,36 @@ namespace ImGui // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows // - 4. Optionally call TableHeadersRow() to submit a header row (names will be pulled from data submitted to TableSetupColumns) - // - 4. Populate contents - // - In most situations you can use TableNextRow() + TableSetColumnIndex() to start appending into a column. - // - If you are using tables as a sort of grid, where every columns is holding the same type of contents, - // you may prefer using TableNextCell() instead of TableNextRow() + TableSetColumnIndex(). - // - Submit your content with regular ImGui function. + // - 5. Populate contents + // - In most situations you can use TableNextRow() + TableSetColumnIndex(xx) to start appending into a column. + // - If you are using tables as a sort of grid, where every columns is holding the same type of contents, + // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex(). + // TableNextColumn() will automatically wrap-around into the next row if needed. + // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! + // - Summary of possible call flow: + // ---------------------------------------------------------------------------------------------------------- + // TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK + // TableNextRow() -> TableNextColumn() Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK + // TableNextColumn() Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! + // TableNextRow() Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! + // ---------------------------------------------------------------------------------------------------------- // - 5. Call EndTable() #define IMGUI_HAS_TABLE 1 IMGUI_API bool BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row. - IMGUI_API bool TableNextCell(); // append into the next column (next column, or next row if currently in last column). Return true if column is visible. + IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true if column is visible. IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true if column is visible. IMGUI_API int TableGetColumnIndex(); // return current column index. // Tables: Headers & Columns declaration - // - Use TableSetupScrollFreeze() to lock columns (from the right) or rows (from the top) so they stay visible when scrolled. // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. // Important: this will not display anything! The name passed to TableSetupColumn() is used by TableHeadersRow() and context-menus. // - Use TableHeadersRow() to create a row and automatically submit a TableHeader() for each column. // Headers are required to perform some interactions: reordering, sorting, context menu (FIXME-TABLE: context menu should work without!) // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in some advanced cases (e.g. adding custom widgets in header row). - IMGUI_API void TableSetupScrollFreeze(int columns, int rows); + // - Use TableSetupScrollFreeze() to lock columns (from the right) or rows (from the top) so they stay visible when scrolled. IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = -1.0f, ImU32 user_id = 0); + IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used) // Tables: Miscellaneous functions @@ -694,13 +702,13 @@ namespace ImGui // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable) IMGUI_API const char* TableGetColumnName(int column_n = -1); // return NULL if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. - IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextCell() and TableSetColumnIndex(). Pass -1 to use current column. + IMGUI_API bool TableGetColumnIsVisible(int column_n = -1); // return true if column is visible. Same value is also returned by TableNextColumn() and TableSetColumnIndex(). Pass -1 to use current column. IMGUI_API bool TableGetColumnIsSorted(int column_n = -1); // return true if column is included in the sort specs. Rarely used, can be useful to tell if a data change should trigger resort. Equivalent to test ImGuiTableSortSpecs's ->ColumnsMask & (1 << column_n). Pass -1 to use current column. IMGUI_API int TableGetHoveredColumn(); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting). IMGUI_API void TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. - // Columns (Legacy API, prefer using Tables) + // Legacy Columns API (2020: prefer using Tables!) // - You can also use SameLine(pos_x) to mimic simplified columns. IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished diff --git a/imgui_demo.cpp b/imgui_demo.cpp index f95bbffe..bcca3c74 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3348,31 +3348,30 @@ static void ShowDemoWindowTables() // This essentially the same as above, except instead of using a for loop we call TableSetColumnIndex() manually. // Sometimes this makes more sense. - HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, manually."); + HelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually."); if (ImGui::BeginTable("##table2", 3)) { for (int row = 0; row < 4; row++) { ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); + ImGui::TableNextColumn(); ImGui::Text("Row %d", row); - ImGui::TableSetColumnIndex(1); + ImGui::TableNextColumn(); ImGui::Text("Some contents"); - ImGui::TableSetColumnIndex(2); + ImGui::TableNextColumn(); ImGui::Text("123.456"); } ImGui::EndTable(); } - // Another subtle variant, we call TableNextCell() _before_ each cell. At the end of a row, TableNextCell() will create a new row. - // Note that we don't call TableNextRow() here! - // If we want to call TableNextRow(), then we don't need to call TableNextCell() for the first cell. - HelpMarker("Only using TableNextCell(), which tends to be convenient for tables where every cells contains the same type of contents.\nThis is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition."); + // Another subtle variant, we call TableNextColumn() _before_ each cell. At the end of a row, TableNextColumn() will create a new row. + // Note that we never TableNextRow() here! + HelpMarker("Only using TableNextColumn(), which tends to be convenient for tables where every cells contains the same type of contents.\nThis is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition."); if (ImGui::BeginTable("##table4", 3)) { for (int item = 0; item < 14; item++) { - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::Text("Item %d", item); } ImGui::EndTable(); @@ -3690,7 +3689,7 @@ static void ShowDemoWindowTables() ImGui::TableNextRow(); for (int column = 0; column < 7; column++) { - // Both TableNextCell() and TableSetColumnIndex() return false when a column is not visible, which can be used for clipping. + // Both TableNextColumn() and TableSetColumnIndex() return false when a column is not visible, which can be used for clipping. if (!ImGui::TableSetColumnIndex(column)) continue; if (column == 0) @@ -3718,7 +3717,7 @@ static void ShowDemoWindowTables() for (int column = 0; column < column_count; column++) { // Make the UI compact because there are so many fields - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGuiStyle& style = ImGui::GetStyle(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, 2)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, 2)); @@ -3780,7 +3779,8 @@ static void ShowDemoWindowTables() ImGui::TableSetupColumn("A1"); ImGui::TableHeadersRow(); - ImGui::TableNextRow(); ImGui::Text("A0 Cell 0"); + ImGui::TableNextColumn(); + ImGui::Text("A0 Cell 0"); { float rows_height = ImGui::GetTextLineHeightWithSpacing() * 2; if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeightV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) @@ -3790,20 +3790,22 @@ static void ShowDemoWindowTables() ImGui::TableHeadersRow(); ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::TableNextColumn(); ImGui::Text("B0 Cell 0"); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::Text("B0 Cell 1"); ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height); + ImGui::TableNextColumn(); ImGui::Text("B1 Cell 0"); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::Text("B1 Cell 1"); ImGui::EndTable(); } } - ImGui::TableNextCell(); ImGui::Text("A0 Cell 1"); - ImGui::TableNextRow(); ImGui::Text("A1 Cell 0"); - ImGui::TableNextCell(); ImGui::Text("A1 Cell 1"); + ImGui::TableNextColumn(); ImGui::Text("A0 Cell 1"); + ImGui::TableNextColumn(); ImGui::Text("A1 Cell 0"); + ImGui::TableNextColumn(); ImGui::Text("A1 Cell 1"); ImGui::EndTable(); } ImGui::TreePop(); @@ -3915,6 +3917,7 @@ static void ShowDemoWindowTables() { float min_row_height = (float)(int)(ImGui::GetFontSize() * 0.30f * row); ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); + ImGui::TableNextColumn(); ImGui::Text("min_row_height = %.2f", min_row_height); } ImGui::EndTable(); @@ -4003,13 +4006,14 @@ static void ShowDemoWindowTables() static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes) { ImGui::TableNextRow(); + ImGui::TableNextColumn(); const bool is_folder = (node->ChildCount > 0); if (is_folder) { bool open = ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::TextDisabled("--"); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::TextUnformatted(node->Type); if (open) { @@ -4021,9 +4025,9 @@ static void ShowDemoWindowTables() else { ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::Text("%d", node->Size); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::TextUnformatted(node->Type); } } @@ -4228,13 +4232,13 @@ static void ShowDemoWindowTables() MyItem* item = &items[row_n]; ImGui::PushID(item->ID); ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); + ImGui::TableNextColumn(); ImGui::Text("%04d", item->ID); - ImGui::TableSetColumnIndex(1); + ImGui::TableNextColumn(); ImGui::TextUnformatted(item->Name); - ImGui::TableSetColumnIndex(2); + ImGui::TableNextColumn(); ImGui::SmallButton("None"); - ImGui::TableSetColumnIndex(3); + ImGui::TableNextColumn(); ImGui::Text("%d", item->Quantity); ImGui::PopID(); } @@ -4431,6 +4435,7 @@ static void ShowDemoWindowTables() const bool item_is_selected = selection.contains(item->ID); ImGui::PushID(item->ID); ImGui::TableNextRow(ImGuiTableRowFlags_None, row_min_height); + ImGui::TableNextColumn(); // For the demo purpose we can select among different type of items submitted in the first column char label[32]; @@ -4462,14 +4467,14 @@ static void ShowDemoWindowTables() } } - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::TextUnformatted(item->Name); // Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity, // and we are currently sorting on the column showing the Quantity. // To avoid triggering a sort while holding the button, we only trigger it when the button has been released. // You will probably need a more advanced system in your code if you want to automatically sort when a specific entry changes. - if (ImGui::TableNextCell()) + if (ImGui::TableNextColumn()) { if (ImGui::SmallButton("Chop")) { item->Quantity += 1; } if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } @@ -4478,16 +4483,16 @@ static void ShowDemoWindowTables() if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; } } - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::Text("%d", item->Quantity); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); if (show_wrapped_text) ImGui::TextWrapped("Lorem ipsum dolor sit amet"); else ImGui::Text("Lorem ipsum dolor sit amet"); - ImGui::TableNextCell(); + ImGui::TableNextColumn(); ImGui::Text("1234"); ImGui::PopID(); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index d8681d4b..df7d9dda 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -79,7 +79,7 @@ // | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction // | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu // - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) -// - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableHeadersRow() +// - TableNextRow() / TableNextColumn() user begin into the first row, also automatically called by TableHeadersRow() // | TableEndCell() - close existing cell if not the first time // | TableBeginCell() - enter into current cell // - [...] user emit contents @@ -345,7 +345,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG } table->RefScale = new_ref_scale_unit; - // Disable output until user calls TableNextRow() or TableNextCell() leading to the TableUpdateLayout() call.. + // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call.. // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. inner_window->SkipItems = true; @@ -988,7 +988,7 @@ void ImGui::EndTable() // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?"); - // If the user never got to call TableNextRow() or TableNextCell(), we call layout ourselves to ensure all our + // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc. if (!table->IsLayoutLocked) TableUpdateLayout(table); @@ -1610,7 +1610,8 @@ void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height) table->RowPosY2 += table->CellPaddingY * 2.0f; table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height); - TableBeginCell(table, 0); + // Disable output until user calls TableNextColumn() + table->InnerWindow->SkipItems = true; } // [Internal] @@ -1654,7 +1655,8 @@ void ImGui::TableEndRow(ImGuiTable* table) IM_ASSERT(window == table->InnerWindow); IM_ASSERT(table->IsInsideRow); - TableEndCell(table); + if (table->CurrentColumn != -1) + TableEndCell(table); // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. @@ -1783,7 +1785,7 @@ void ImGui::TableEndRow(ImGuiTable* table) table->IsInsideRow = false; } -// [Internal] Called by TableNextCell()! +// [Internal] Called by TableNextColumn()! // This is called very frequently, so we need to be mindful of unnecessary overhead. // FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. void ImGui::TableBeginCell(ImGuiTable* table, int column_n) @@ -1824,7 +1826,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n) } } -// [Internal] Called by TableNextRow()/TableNextCell()! +// [Internal] Called by TableNextRow()/TableNextColumn()! void ImGui::TableEndCell(ImGuiTable* table) { ImGuiTableColumn* column = &table->Columns[table->CurrentColumn]; @@ -1846,28 +1848,30 @@ void ImGui::TableEndCell(ImGuiTable* table) // Append into the next cell // FIXME-TABLE: Wrapping to next row should be optional? -bool ImGui::TableNextCell() +bool ImGui::TableNextColumn() { ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; if (!table) return false; - if (table->CurrentColumn != -1 && table->CurrentColumn + 1 < table->ColumnsCount) + if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount) { - TableEndCell(table); + if (table->CurrentColumn != -1) + TableEndCell(table); TableBeginCell(table, table->CurrentColumn + 1); } else { TableNextRow(); + TableBeginCell(table, 0); } - int column_n = table->CurrentColumn; // FIXME-TABLE: Need to clarify if we want to allow IsItemHovered() here //g.CurrentWindow->DC.LastItemStatusFlags = (column_n == table->HoveredColumn) ? ImGuiItemStatusFlags_HoveredRect : ImGuiItemStatusFlags_None; // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping. + int column_n = table->CurrentColumn; return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0; } From e66b28693ad94f59f9da09a19ede4d3d1e5a3280 Mon Sep 17 00:00:00 2001 From: ocornut Date: Thu, 1 Oct 2020 19:54:10 +0200 Subject: [PATCH 473/959] Tables: Added ImGuiTableFlags_ContextMenuInBody flag. Worked to get TableOpenContextMenu() in public API but kept it internal. --- imgui.h | 29 +++++++++++---------- imgui_demo.cpp | 68 +++++++++++++++++++++++++++++++++++++----------- imgui_internal.h | 2 +- imgui_tables.cpp | 19 +++++++++++--- 4 files changed, 85 insertions(+), 33 deletions(-) diff --git a/imgui.h b/imgui.h index c7516b01..8f4ba992 100644 --- a/imgui.h +++ b/imgui.h @@ -1056,28 +1056,29 @@ enum ImGuiTableFlags_ ImGuiTableFlags_Sortable = 1 << 3, // Allow sorting on one column (sort_specs_count will always be == 1). Call TableGetSortSpecs() to obtain sort specs. ImGuiTableFlags_MultiSortable = 1 << 4, // Allow sorting on multiple columns by holding Shift (sort_specs_count may be > 1). Call TableGetSortSpecs() to obtain sort specs. ImGuiTableFlags_NoSavedSettings = 1 << 5, // Disable persisting columns order, width and sort settings in the .ini file. + ImGuiTableFlags_ContextMenuInBody = 1 << 6, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). // Decoration - ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent to calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) - ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. - ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. - ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. - ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_RowBg = 1 << 7, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent to calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) + ImGuiTableFlags_BordersInnerH = 1 << 8, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersOuterH = 1 << 9, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersInnerV = 1 << 10, // Draw vertical borders between columns. + ImGuiTableFlags_BordersOuterV = 1 << 11, // Draw vertical borders on the left and right sides. ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. - ImGuiTableFlags_BordersFullHeightV = 1 << 11, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. + ImGuiTableFlags_BordersFullHeightV = 1 << 12, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. // Padding, Sizing - ImGuiTableFlags_SizingPolicyFixedX = 1 << 12, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. - ImGuiTableFlags_SizingPolicyStretchX = 1 << 13, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. - ImGuiTableFlags_NoHeadersWidth = 1 << 14, // Disable header width contribution to automatic width calculation. - ImGuiTableFlags_NoHostExtendY = 1 << 15, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) - ImGuiTableFlags_NoKeepColumnsVisible = 1 << 16, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. - ImGuiTableFlags_NoClip = 1 << 17, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options. + ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. + ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. + ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. + ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 17, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. + ImGuiTableFlags_NoClip = 1 << 18, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options. // Scrolling - ImGuiTableFlags_ScrollX = 1 << 20, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - ImGuiTableFlags_ScrollY = 1 << 21, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + ImGuiTableFlags_ScrollX = 1 << 19, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 20, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, // [Internal] Combinations and masks diff --git a/imgui_demo.cpp b/imgui_demo.cpp index bcca3c74..3961148f 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -4104,54 +4104,91 @@ static void ShowDemoWindowTables() ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Context menus")) { - HelpMarker("By default, TableHeadersRow()/TableHeader() will open a context-menu on right-click."); - ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders; + HelpMarker("By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\nUsing ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body."); + static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody; + ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", (unsigned int*)&flags1, ImGuiTableFlags_ContextMenuInBody); + + // Context Menus: first example + // [1.1] Right-click on the TableHeadersRow() line to open the default table context menu. + // [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set) const int COLUMNS_COUNT = 3; - if (ImGui::BeginTable("##table1", COLUMNS_COUNT, flags)) + if (ImGui::BeginTable("##table1", COLUMNS_COUNT, flags1)) { ImGui::TableSetupColumn("One"); ImGui::TableSetupColumn("Two"); ImGui::TableSetupColumn("Three"); - // Context Menu 1: right-click on header (including empty section after the third column!) should open Default Table Popup + // [1.1]] Right-click on the TableHeadersRow() line to open the default table context menu. ImGui::TableHeadersRow(); + + // Submit dummy contents for (int row = 0; row < 4; row++) { ImGui::TableNextRow(); for (int column = 0; column < COLUMNS_COUNT; column++) { ImGui::TableSetColumnIndex(column); - ImGui::PushID(row * COLUMNS_COUNT + column); + ImGui::Text("Cell %d,%d", 0, row); + } + } + ImGui::EndTable(); + } + + // Context Menus: second example + // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + // [2.2] Right-click on the ".." to open a custom popup + // [2.3] Right-click in columns to open another custom popup + HelpMarker("Demonstrate mixing table context menu (over header), item context button (over button) and custom per-colum context menu (over column body)."); + ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders; + if (ImGui::BeginTable("##table2", COLUMNS_COUNT, flags2)) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + + // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + ImGui::TableHeadersRow(); + for (int row = 0; row < 4; row++) + { + ImGui::TableNextRow(); + for (int column = 0; column < COLUMNS_COUNT; column++) + { + // Submit dummy contents + ImGui::TableSetColumnIndex(column); ImGui::Text("Cell %d,%d", column, row); ImGui::SameLine(); - // Context Menu 2: right-click on buttons open Custom Button Popup + // [2.2] Right-click on the ".." to open a custom popup + ImGui::PushID(row * COLUMNS_COUNT + column); ImGui::SmallButton(".."); if (ImGui::BeginPopupContextItem()) { - ImGui::Text("This is the popup for Button() On Cell %d,%d", column, row); - ImGui::Selectable("Close"); + ImGui::Text("This is the popup for Button(\"..\") in Cell %d,%d", column, row); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } ImGui::PopID(); } } - // Context Menu 3: Right-click anywhere in columns opens a custom popup - // We use the ImGuiPopupFlags_NoOpenOverExistingPopup flag to avoid displaying over either the standard TableHeader context-menu or the Button context-menu. + // [2.3] Right-click anywhere in columns to open another custom popup + // (instead of testing for !IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup + // to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping) const int hovered_column = ImGui::TableGetHoveredColumn(); for (int column = 0; column < COLUMNS_COUNT + 1; column++) { ImGui::PushID(column); - if (hovered_column == column && ImGui::IsMouseReleased(1)) - ImGui::OpenPopup("MyPopup", ImGuiPopupFlags_NoOpenOverExistingPopup); + if (hovered_column == column && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(1)) + ImGui::OpenPopup("MyPopup"); if (ImGui::BeginPopup("MyPopup")) { if (column == COLUMNS_COUNT) - ImGui::Text("This is the popup for unused space after the last column."); + ImGui::Text("This is a custom popup for unused space after the last column."); else - ImGui::Text("This is the popup for Column '%s'", ImGui::TableGetColumnName(column)); - ImGui::Selectable("Close"); + ImGui::Text("This is a custom popup for Column %d", column); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } ImGui::PopID(); @@ -4289,6 +4326,7 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", (unsigned int*)&flags, ImGuiTableFlags_Sortable); ImGui::CheckboxFlags("ImGuiTableFlags_MultiSortable", (unsigned int*)&flags, ImGuiTableFlags_MultiSortable); ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", (unsigned int*)&flags, ImGuiTableFlags_NoSavedSettings); + ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", (unsigned int*)&flags, ImGuiTableFlags_ContextMenuInBody); ImGui::Unindent(); ImGui::BulletText("Decoration:"); diff --git a/imgui_internal.h b/imgui_internal.h index df026c06..1bf8a164 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -2276,7 +2276,7 @@ namespace ImGui IMGUI_API void TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column, float width); IMGUI_API void TableDrawBorders(ImGuiTable* table); IMGUI_API void TableDrawContextMenu(ImGuiTable* table); - IMGUI_API void TableOpenContextMenu(ImGuiTable* table, int column_n); + IMGUI_API void TableOpenContextMenu(int column_n = -1); IMGUI_API void TableReorderDrawChannelsForMerge(ImGuiTable* table); IMGUI_API void TableSetColumnSortDirection(ImGuiTable* table, int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs); IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index df7d9dda..46ada6f3 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1002,6 +1002,11 @@ void ImGui::EndTable() if (table->IsInsideRow) TableEndRow(table); + // Context menu in columns body + if (flags & ImGuiTableFlags_ContextMenuInBody) + if (table->HoveredColumnBody != -1 && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Right)) + TableOpenContextMenu((int)table->HoveredColumnBody); + // Finalize table height inner_window->SkipItems = table->HostSkipItems; inner_window->DC.CursorMaxPos = table->HostCursorMaxPos; @@ -2040,6 +2045,7 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table) } // Sorting + // (modify TableOpenContextMenu() to add _Sortable flag if enabling this) #if 0 if ((table->Flags & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0) { @@ -2082,8 +2088,14 @@ void ImGui::TableDrawContextMenu(ImGuiTable* table) } // Use -1 to open menu not specific to a given column. -void ImGui::TableOpenContextMenu(ImGuiTable* table, int column_n) +void ImGui::TableOpenContextMenu(int column_n) { + ImGuiContext& g = *GImGui; + ImGuiTable* table = g.CurrentTable; + if (column_n == -1 && table->CurrentColumn != -1) // When called within a column automatically use this one (for consistency) + column_n = table->CurrentColumn; + if (column_n == table->ColumnsCount) // To facilitate using with TableGetHoveredColumn() + column_n = -1; IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount); if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) { @@ -2157,7 +2169,7 @@ void ImGui::TableHeadersRow() ImVec2 mouse_pos = ImGui::GetMousePos(); if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count) if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height) - TableOpenContextMenu(table, -1); // Will open a non-column-specific popup. + TableOpenContextMenu(-1); // Will open a non-column-specific popup. } // Emit a column header (text + optional sort order) @@ -2297,7 +2309,7 @@ void ImGui::TableHeader(const char* label) // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden if (IsMouseReleased(1) && IsItemHovered()) - TableOpenContextMenu(table, column_n); + TableOpenContextMenu(column_n); } // Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert @@ -2359,6 +2371,7 @@ bool ImGui::TableGetColumnIsSorted(int column_n) return (column->SortOrder != -1); } +// Return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. int ImGui::TableGetHoveredColumn() { ImGuiContext& g = *GImGui; From 2ee20fdb7c72aa6e886211eb850857c35be3f772 Mon Sep 17 00:00:00 2001 From: ocornut Date: Mon, 5 Oct 2020 15:20:28 +0200 Subject: [PATCH 474/959] Tables: Frozen rows/columns in nav menu layer, fixed conflict between column id and holding child id. --- imgui_internal.h | 3 ++- imgui_tables.cpp | 40 ++++++++++++++++++++++++---------------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/imgui_internal.h b/imgui_internal.h index 1bf8a164..ea45d384 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1916,6 +1916,7 @@ struct ImGuiTableColumn bool IsVisibleNextFrame; bool IsClipped; // Set when not overlapping the host window clipping rectangle. bool SkipItems; + ImGuiNavLayer NavLayerCurrent; ImS8 DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) ImS8 IndexWithinVisibleSet; // Index within visible set (<= IndexToDisplayOrder) ImS8 DrawChannelCurrent; // Index within DrawSplitter.Channels[] @@ -2039,7 +2040,7 @@ struct ImGuiTable 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) bool IsResetDisplayOrderRequest; - bool IsFreezeRowsPassed; // Set when we got past the frozen row (the first one). + bool IsFreezeRowsPassed; // Set when we got past the frozen row. bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis ImGuiTable() diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 46ada6f3..7143b9f0 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -235,12 +235,13 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX) SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f)); - // Create scrolling region (without border = zero window padding) + // Create scrolling region (without border and zero window padding) ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None; BeginChildEx(name, instance_id, table->OuterRect.GetSize(), false, child_flags); table->InnerWindow = g.CurrentWindow; table->WorkRect = table->InnerWindow->WorkRect; table->OuterRect = table->InnerWindow->Rect(); + IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f); } // Push a standardized ID for both child and not-child using tables, equivalent to BeginTable() doing PushID(label) matching @@ -479,7 +480,7 @@ void ImGui::TableSetupScrollFreeze(int columns, int rows) ImGuiContext& g = *GImGui; ImGuiTable* table = g.CurrentTable; IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!"); - IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!"); + IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!"); IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS); IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit @@ -487,7 +488,7 @@ void ImGui::TableSetupScrollFreeze(int columns, int rows) table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0; table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImS8)rows : 0; table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0; - table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); + table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b } void ImGui::TableUpdateDrawChannels(ImGuiTable* table) @@ -778,6 +779,8 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) const int column_n = table->DisplayOrderToIndex[order_n]; ImGuiTableColumn* column = &table->Columns[column_n]; + column->NavLayerCurrent = (table->FreezeRowsCount > 0 || column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main; + if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == visible_n) offset_x += work_rect.Min.x - table->OuterRect.Min.x; @@ -1671,12 +1674,12 @@ void ImGui::TableEndRow(ImGuiTable* table) const float bg_y1 = table->RowPosY1; const float bg_y2 = table->RowPosY2; - const bool unfreeze_rows = (table->CurrentRow + 1 == table->FreezeRowsCount && table->FreezeRowsCount > 0); - + const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount); + const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest); if (table->CurrentRow == 0) table->LastFirstRowHeight = bg_y2 - bg_y1; - const bool is_visible = table->CurrentRow >= 0 && bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y; + const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y); if (is_visible) { // Decide of background color for the row @@ -1710,7 +1713,7 @@ void ImGui::TableEndRow(ImGuiTable* table) } const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0; - const bool draw_strong_bottom_border = unfreeze_rows;// || (table->RowFlags & ImGuiTableRowFlags_Headers); + const bool draw_strong_bottom_border = unfreeze_rows_actual;// || (table->RowFlags & ImGuiTableRowFlags_Headers); if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color) { // In theory we could call SetWindowClipRectBeforeChannelChange() but since we know TableEndRow() is @@ -1757,18 +1760,22 @@ void ImGui::TableEndRow(ImGuiTable* table) // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and // get the new cursor position. - if (unfreeze_rows) + if (unfreeze_rows_request) + for (int column_n = 0; column_n < table->ColumnsCount; column_n++) + { + ImGuiTableColumn* column = &table->Columns[column_n]; + column->NavLayerCurrent = (column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main; + } + if (unfreeze_rows_actual) { IM_ASSERT(table->IsFreezeRowsPassed == false); table->IsFreezeRowsPassed = true; table->DrawSplitter.SetCurrentChannel(window->DrawList, 0); - ImRect r; - r.Min.x = table->InnerClipRect.Min.x; - r.Min.y = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y); - r.Max.x = table->InnerClipRect.Max.x; - r.Max.y = window->InnerClipRect.Max.y; - table->BackgroundClipRect = r; + // BackgroundClipRect starts as table->InnerClipRect, reduce it now + float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y); + table->BackgroundClipRect.Min.y = y0; + table->BackgroundClipRect.Max.y = window->InnerClipRect.Max.y; float row_height = table->RowPosY2 - table->RowPosY1; table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y; @@ -1777,7 +1784,7 @@ void ImGui::TableEndRow(ImGuiTable* table) { ImGuiTableColumn* column = &table->Columns[column_n]; column->DrawChannelCurrent = column->DrawChannelRowsAfterFreeze; - column->ClipRect.Min.y = r.Min.y; + column->ClipRect.Min.y = table->BackgroundClipRect.Min.y; } // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y @@ -1810,6 +1817,7 @@ void ImGui::TableBeginCell(ImGuiTable* table, int column_n) window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT window->DC.CurrLineTextBaseOffset = table->RowTextBaseline; window->DC.LastItemId = 0; + window->DC.NavLayerCurrent = column->NavLayerCurrent; window->WorkRect.Min.y = window->DC.CursorPos.y; window->WorkRect.Min.x = column->MinX + table->CellPaddingX1; @@ -1964,7 +1972,7 @@ const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n) ImGuiID ImGui::TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no) { IM_ASSERT(column_n < table->ColumnsCount); - ImGuiID id = table->ID + (instance_no * table->ColumnsCount) + column_n; + ImGuiID id = table->ID + 1 + (instance_no * table->ColumnsCount) + column_n; return id; } From 172704c079233839a805a805cda6808e44e012e6 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 6 Oct 2020 15:08:27 +0200 Subject: [PATCH 475/959] Tables: Add demo code. Remove dead code + seemingly duplicate border in TableDrawBorders(). --- imgui.h | 2 +- imgui_demo.cpp | 37 +++++++++++++++++++++++++++++-------- imgui_tables.cpp | 22 ++++------------------ 3 files changed, 34 insertions(+), 27 deletions(-) diff --git a/imgui.h b/imgui.h index 8f4ba992..18efa03b 100644 --- a/imgui.h +++ b/imgui.h @@ -1069,7 +1069,7 @@ enum ImGuiTableFlags_ ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. ImGuiTableFlags_BordersFullHeightV = 1 << 12, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. - // Padding, Sizing + // Sizing, Padding ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 3961148f..9a9cbed4 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3385,8 +3385,12 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Borders, background")) { // Expose a few Borders related flags interactively + enum ContentsType { CT_Text, CT_FillButton }; static ImGuiTableFlags flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; + static bool display_headers = false; static bool display_width = false; + static int contents_type = CT_Text; + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&flags, ImGuiTableFlags_Borders); ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterH"); @@ -3402,15 +3406,30 @@ static void ShowDemoWindowTables() ImGui::Indent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterV); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersFullHeightV", (unsigned int*)&flags, ImGuiTableFlags_BordersFullHeightV); ImGui::SameLine(); HelpMarker("Makes a difference when headers are enabled"); ImGui::Unindent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", (unsigned int*)&flags, ImGuiTableFlags_BordersInner); ImGui::Unindent(); - ImGui::Checkbox("Debug Display width", &display_width); + ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:"); + ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text); + ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); + ImGui::Checkbox("Display headers", &display_headers); + ImGui::Checkbox("Display debug width", &display_width); if (ImGui::BeginTable("##table1", 3, flags)) { + // Display headers so we can inspect their interaction with borders. + // (Headers are not the main purpose of this section of the demo, so we are not elaborating on them too much. See other sections for details) + if (display_headers) + { + ImGui::TableSetupColumn("One"); + ImGui::TableSetupColumn("Two"); + ImGui::TableSetupColumn("Three"); + ImGui::TableHeadersRow(); + } + for (int row = 0; row < 5; row++) { ImGui::TableNextRow(); @@ -3420,7 +3439,7 @@ static void ShowDemoWindowTables() char buf[32]; if (display_width) { - // [DEBUG] Draw limits + // [DEBUG] Draw limits FIXME-TABLE: Move to Advanced section ImVec2 p = ImGui::GetCursorScreenPos(); float contents_x1 = p.x; float contents_x2 = ImGui::GetWindowPos().x + ImGui::GetContentRegionMax().x; @@ -3437,7 +3456,11 @@ static void ShowDemoWindowTables() { sprintf(buf, "Hello %d,%d", row, column); } - ImGui::TextUnformatted(buf); + + if (contents_type == CT_Text) + ImGui::TextUnformatted(buf); + else if (contents_type) + ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f)); } } ImGui::EndTable(); @@ -4305,7 +4328,6 @@ static void ShowDemoWindowTables() static float row_min_height = 0.0f; // Auto static float inner_width_with_scroll = 0.0f; // Auto-extend static bool outer_size_enabled = true; - static bool lock_first_column_visibility = false; static bool show_headers = true; static bool show_wrapped_text = false; //static ImGuiTextFilter filter; @@ -4370,6 +4392,8 @@ static void ShowDemoWindowTables() ImGui::BulletText("Other:"); ImGui::Indent(); + ImGui::Checkbox("show_headers", &show_headers); + ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); ImGui::DragFloat2("##OuterSize", &outer_size_value.x); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::Checkbox("outer_size", &outer_size_enabled); @@ -4384,9 +4408,6 @@ static void ShowDemoWindowTables() ImGui::DragInt("items_count", &items_count, 0.1f, 0, 5000); ImGui::Combo("contents_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names)); //filter.Draw("filter"); - ImGui::Checkbox("show_headers", &show_headers); - ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); - ImGui::Checkbox("lock_first_column_visibility", &lock_first_column_visibility); ImGui::Unindent(); ImGui::PopItemWidth(); @@ -4424,7 +4445,7 @@ static void ShowDemoWindowTables() // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); - ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | (lock_first_column_visibility ? ImGuiTableColumnFlags_NoHide : 0), -1.0f, MyItemColumnID_ID); + ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoHide, -1.0f, MyItemColumnID_ID); ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Name); ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, -1.0f, MyItemColumnID_Action); ImGui::TableSetupColumn("Quantity Long Label", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 1.0f, MyItemColumnID_Quantity);// , ImGuiTableColumnFlags_None | ImGuiTableColumnFlags_WidthAlwaysAutoResize); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 7143b9f0..e7cc2b58 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1147,7 +1147,8 @@ void ImGui::TableDrawBorders(ImGuiTable* table) float draw_y2_base = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight; float draw_y2_full = table->OuterRect.Max.y; ImU32 border_base_col; - if (!table->IsUsingHeaders || (table->Flags & ImGuiTableFlags_BordersFullHeightV)) + const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersFullHeightV); + if (borders_full_height) { draw_y2_base = draw_y2_full; border_base_col = table->BorderColorLight; @@ -1157,9 +1158,6 @@ void ImGui::TableDrawBorders(ImGuiTable* table) border_base_col = table->BorderColorStrong; } - if ((table->Flags & ImGuiTableFlags_BordersOuterV) && (table->InnerWindow == table->OuterWindow)) - inner_drawlist->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, border_size); - if (table->Flags & ImGuiTableFlags_BordersInnerV) { for (int order_n = 0; order_n < table->ColumnsCount; order_n++) @@ -1696,24 +1694,12 @@ void ImGui::TableEndRow(ImGuiTable* table) ImU32 border_col = 0; const float border_size = TABLE_BORDER_SIZE; if (table->CurrentRow != 0 || table->InnerWindow == table->OuterWindow) - { if (table->Flags & ImGuiTableFlags_BordersInnerH) - { - //if (table->CurrentRow == 0 && table->InnerWindow == table->OuterWindow) - // border_col = table->BorderOuterColor; - //else - if (table->CurrentRow > 0)// && !(table->LastRowFlags & ImGuiTableRowFlags_Headers)) + if (table->CurrentRow > 0) border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight; - } - else - { - //if (table->RowFlags & ImGuiTableRowFlags_Headers) - // border_col = table->BorderOuterColor; - } - } const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0; - const bool draw_strong_bottom_border = unfreeze_rows_actual;// || (table->RowFlags & ImGuiTableRowFlags_Headers); + const bool draw_strong_bottom_border = unfreeze_rows_actual; if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color) { // In theory we could call SetWindowClipRectBeforeChannelChange() but since we know TableEndRow() is From 02b27b75a40067d1671c37a57423efd2e63cd5b9 Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 6 Oct 2020 17:53:59 +0200 Subject: [PATCH 476/959] Tables: Added ImGuiTableFlags_NoBordersInBody, ImGuiTableFlags_NoBordersInBodyUntilResize, removed ImGuiTableFlags_BordersFullHeightV. --- imgui.h | 19 +++++++------- imgui_demo.cpp | 21 +++++++++------ imgui_tables.cpp | 67 ++++++++++++++++++++++++++---------------------- 3 files changed, 59 insertions(+), 48 deletions(-) diff --git a/imgui.h b/imgui.h index 18efa03b..02879546 100644 --- a/imgui.h +++ b/imgui.h @@ -1068,17 +1068,18 @@ enum ImGuiTableFlags_ ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. - ImGuiTableFlags_BordersFullHeightV = 1 << 12, // Borders covers all rows even when Headers are being used. Allow resizing from any rows. + ImGuiTableFlags_NoBordersInBody = 1 << 12, // Disable vertical borders in columns Body (borders will always appears in Headers). + ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 13, // Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers). // Sizing, Padding - ImGuiTableFlags_SizingPolicyFixedX = 1 << 13, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. - ImGuiTableFlags_SizingPolicyStretchX = 1 << 14, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. - ImGuiTableFlags_NoHeadersWidth = 1 << 15, // Disable header width contribution to automatic width calculation. - ImGuiTableFlags_NoHostExtendY = 1 << 16, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) - ImGuiTableFlags_NoKeepColumnsVisible = 1 << 17, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. - ImGuiTableFlags_NoClip = 1 << 18, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options. + ImGuiTableFlags_SizingPolicyFixedX = 1 << 14, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. + ImGuiTableFlags_SizingPolicyStretchX = 1 << 15, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. + ImGuiTableFlags_NoHeadersWidth = 1 << 16, // Disable header width contribution to automatic width calculation. + ImGuiTableFlags_NoHostExtendY = 1 << 17, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. + ImGuiTableFlags_NoClip = 1 << 19, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options. // Scrolling - ImGuiTableFlags_ScrollX = 1 << 19, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. - ImGuiTableFlags_ScrollY = 1 << 20, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + ImGuiTableFlags_ScrollX = 1 << 20, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 21, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. ImGuiTableFlags_Scroll = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY, // [Internal] Combinations and masks diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 9a9cbed4..daa3ad46 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3406,12 +3406,14 @@ static void ShowDemoWindowTables() ImGui::Indent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterV); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersFullHeightV", (unsigned int*)&flags, ImGuiTableFlags_BordersFullHeightV); ImGui::SameLine(); HelpMarker("Makes a difference when headers are enabled"); ImGui::Unindent(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", (unsigned int*)&flags, ImGuiTableFlags_BordersInner); ImGui::Unindent(); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)"); + ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:"); ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text); ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); @@ -3575,10 +3577,12 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Reorderable, hideable, with headers")) { HelpMarker("Click and drag column headers to reorder columns.\n\nYou can also right-click on a header to open a context menu."); - static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV; + static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody; ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", (unsigned int*)&flags, ImGuiTableFlags_Reorderable); ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", (unsigned int*)&flags, ImGuiTableFlags_Hideable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBody); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBodyUntilResize); if (ImGui::BeginTable("##table1", 3, flags)) { @@ -3796,7 +3800,7 @@ static void ShowDemoWindowTables() { HelpMarker("This demonstrate embedding a table into another table cell."); - if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeightV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + if (ImGui::BeginTable("recurse1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("A0"); ImGui::TableSetupColumn("A1"); @@ -3806,7 +3810,7 @@ static void ShowDemoWindowTables() ImGui::Text("A0 Cell 0"); { float rows_height = ImGui::GetTextLineHeightWithSpacing() * 2; - if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_BordersFullHeightV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) + if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("B0"); ImGui::TableSetupColumn("B1"); @@ -4007,7 +4011,7 @@ static void ShowDemoWindowTables() ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Tree view")) { - static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg; + static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; //ImGui::CheckboxFlags("ImGuiTableFlags_Scroll", (unsigned int*)&flags, ImGuiTableFlags_Scroll); if (ImGui::BeginTable("##3ways", 3, flags)) @@ -4254,7 +4258,7 @@ static void ShowDemoWindowTables() static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_MultiSortable - | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV + | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_ScrollY; if (ImGui::BeginTable("##table", 4, flags, ImVec2(0, 250), 0.0f)) { @@ -4313,7 +4317,7 @@ static void ShowDemoWindowTables() { static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_MultiSortable - | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders + | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_SizingPolicyFixedX ; @@ -4360,7 +4364,8 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerH); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersFullHeightV", (unsigned int*)&flags, ImGuiTableFlags_BordersFullHeightV); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)"); ImGui::Unindent(); ImGui::BulletText("Padding, Sizing:"); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index e7cc2b58..c607a8b0 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -118,6 +118,10 @@ inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags) if ((flags & ImGuiTableFlags_NoHostExtendY) && (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0) flags &= ~ImGuiTableFlags_NoHostExtendY; + // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody + if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize) + flags &= ~ImGuiTableFlags_NoBordersInBody; + return flags; } @@ -938,11 +942,10 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). // Actual columns highlight/render will be performed in EndTable() and not be affected. - const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersFullHeightV); const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS; const float hit_y1 = table->OuterRect.Min.y; - const float hit_y2_full = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight); - const float hit_y2 = borders_full_height ? hit_y2_full : (hit_y1 + table->LastFirstRowHeight); + const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight); + const float hit_y2_head = hit_y1 + table->LastFirstRowHeight; for (int order_n = 0; order_n < table->ColumnsCount; order_n++) { @@ -954,8 +957,13 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) continue; + // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() + const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body; + if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false) + continue; + ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent); - ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, hit_y2); + ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit); //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)); KeepAliveID(column_id); @@ -1144,19 +1152,8 @@ void ImGui::TableDrawBorders(ImGuiTable* table) // Draw inner border and resizing feedback const float border_size = TABLE_BORDER_SIZE; const float draw_y1 = table->OuterRect.Min.y; - float draw_y2_base = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight; - float draw_y2_full = table->OuterRect.Max.y; - ImU32 border_base_col; - const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersFullHeightV); - if (borders_full_height) - { - draw_y2_base = draw_y2_full; - border_base_col = table->BorderColorLight; - } - else - { - border_base_col = table->BorderColorStrong; - } + const float draw_y2_body = table->OuterRect.Max.y; + const float draw_y2_head = table->IsUsingHeaders ? ((table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight) : draw_y1; if (table->Flags & ImGuiTableFlags_BordersInnerV) { @@ -1170,23 +1167,31 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const bool is_hovered = (table->HoveredColumnBorder == column_n); const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; - bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered); + + if (column->MaxX > table->InnerClipRect.Max.x && !is_resized && is_hovered) + continue; if (column->NextVisibleColumn == -1 && !is_resizable) - draw_right_border = false; - if (draw_right_border && column->MaxX > column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + continue; + if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + continue; + + // Draw in outer window so right-most column won't be clipped + // Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling. + ImU32 col; + float draw_y2; + if (is_hovered || is_resized || (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1)) { - // Draw in outer window so right-most column won't be clipped - // Always draw full height border when: - // - not using headers - // - user specify ImGuiTableFlags_BordersFullHeight - // - being interacted with - // - on the delimitation of frozen column scrolling - const ImU32 col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : border_base_col; - float draw_y2 = draw_y2_base; - if (is_hovered || is_resized || (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1)) - draw_y2 = draw_y2_full; - inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size); + draw_y2 = draw_y2_body; + col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : table->BorderColorStrong; } + else + { + draw_y2 = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? draw_y2_head : draw_y2_body; + col = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? table->BorderColorStrong : table->BorderColorLight; + } + + if (draw_y2 > draw_y1) + inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size); } } From 77e561aaf3e556fe72a60fc4cd4bfebcf54e1f13 Mon Sep 17 00:00:00 2001 From: ocornut Date: Wed, 7 Oct 2020 16:33:33 +0200 Subject: [PATCH 477/959] Tables: Made demo options consistently compact, replaced constants with font-based sizes, added comments on memory allocations. --- imgui_demo.cpp | 263 ++++++++++++++++++++++++++++------------------- imgui_tables.cpp | 10 +- 2 files changed, 165 insertions(+), 108 deletions(-) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index daa3ad46..5a8230ef 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -3287,12 +3287,29 @@ struct MyItem const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL; } +// Make the UI compact because there are so many fields +static void PushStyleCompact() +{ + ImGuiStyle& style = ImGui::GetStyle(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0.70f))); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0.70f))); +} + +static void PopStyleCompact() +{ + ImGui::PopStyleVar(2); +} + static void ShowDemoWindowTables() { //ImGui::SetNextItemOpen(true, ImGuiCond_Once); if (!ImGui::CollapsingHeader("Tables & Columns")) return; + // Using those as a base value to create width/height that are factor of the size of our font + const float TEXT_BASE_WIDTH = ImGui::CalcTextSize("A").x; + const float TEXT_BASE_HEIGHT = ImGui::GetTextLineHeightWithSpacing(); + ImGui::PushID("Tables"); int open_action = -1; @@ -3327,7 +3344,7 @@ static void ShowDemoWindowTables() ImGui::SetNextItemOpen(open_action != 0); if (ImGui::TreeNode("Basic")) { - // Here we will showcase 4 different ways to output a table. They are very simple variations of a same thing! + // Here we will showcase three different ways to output a table. They are very simple variations of a same thing! // Basic use of tables using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. // In many situations, this is the most flexible and easy to use pattern. @@ -3366,7 +3383,9 @@ static void ShowDemoWindowTables() // Another subtle variant, we call TableNextColumn() _before_ each cell. At the end of a row, TableNextColumn() will create a new row. // Note that we never TableNextRow() here! - HelpMarker("Only using TableNextColumn(), which tends to be convenient for tables where every cells contains the same type of contents.\nThis is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition."); + HelpMarker( + "Only using TableNextColumn(), which tends to be convenient for tables where every cells contains the same type of contents.\n" + "This is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition."); if (ImGui::BeginTable("##table4", 3)) { for (int item = 0; item < 14; item++) @@ -3391,6 +3410,7 @@ static void ShowDemoWindowTables() static bool display_width = false; static int contents_type = CT_Text; + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&flags, ImGuiTableFlags_Borders); ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterH"); @@ -3419,6 +3439,7 @@ static void ShowDemoWindowTables() ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); ImGui::Checkbox("Display headers", &display_headers); ImGui::Checkbox("Display debug width", &display_width); + PopStyleCompact(); if (ImGui::BeginTable("##table1", 3, flags)) { @@ -3477,9 +3498,11 @@ static void ShowDemoWindowTables() // By default, if we don't enable ScrollX the sizing policy for each columns is "Stretch" // Each columns maintain a sizing weight, and they will occupy all available width. static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV; + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); ImGui::SameLine(); HelpMarker("Using the _Resizable flag automatically enables the _BordersV flag as well."); + PopStyleCompact(); if (ImGui::BeginTable("##table1", 3, flags)) { @@ -3530,9 +3553,8 @@ static void ShowDemoWindowTables() { HelpMarker("Using columns flag to alter resizing policy on a per-column basis."); static ImGuiTableFlags flags = ImGuiTableFlags_SizingPolicyFixedX | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; - //ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); // FIXME-TABLE: Explain or fix the effect of enable Scroll on outer_size - if (ImGui::BeginTable("##table1", 3, flags, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 6))) + if (ImGui::BeginTable("##table1", 3, flags)) { ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);// | ImGuiTableColumnFlags_NoResize); ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); @@ -3549,7 +3571,7 @@ static void ShowDemoWindowTables() } ImGui::EndTable(); } - if (ImGui::BeginTable("##table2", 6, flags, ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 6))) + if (ImGui::BeginTable("##table2", 6, flags)) { ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed); ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed); @@ -3578,11 +3600,13 @@ static void ShowDemoWindowTables() { HelpMarker("Click and drag column headers to reorder columns.\n\nYou can also right-click on a header to open a context menu."); static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody; + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", (unsigned int*)&flags, ImGuiTableFlags_Reorderable); ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", (unsigned int*)&flags, ImGuiTableFlags_Hideable); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBody); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBodyUntilResize); + PopStyleCompact(); if (ImGui::BeginTable("##table1", 3, flags)) { @@ -3629,13 +3653,16 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Explicit widths")) { static ImGuiTableFlags flags = ImGuiTableFlags_None; + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", (unsigned int*)&flags, ImGuiTableFlags_NoKeepColumnsVisible); + PopStyleCompact(); + if (ImGui::BeginTable("##table1", 3, flags)) { // We could also set ImGuiTableFlags_SizingPolicyFixedX on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f); - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 200.0f); - ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 30.0f); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f); for (int row = 0; row < 5; row++) { ImGui::TableNextRow(); @@ -3655,10 +3682,15 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Vertical scrolling, with clipping")) { HelpMarker("Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\nWe also demonstrate using ImGuiListClipper to virtualize the submission of many items."); - ImVec2 size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 7); static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; + + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); + PopStyleCompact(); + // When using ScrollX or ScrollY we need to specify a size for our table container! + // Otherwise by default the table will fit all available space, like a BeginChild() call. + ImVec2 size = ImVec2(0, TEXT_BASE_HEIGHT * 8); if (ImGui::BeginTable("##table1", 3, flags, size)) { ImGui::TableSetupScrollFreeze(0, 1); // Make top row always visible @@ -3690,16 +3722,21 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Horizontal scrolling")) { HelpMarker("When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingPolicyFixedX, as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\nAlso note that as of the current version, you will almost always want to enable ScrollY along with ScrollX, because the container window won't automatically extend vertically to fix contents (this may be improved in future versions)."); - ImVec2 size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 10); static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable; static int freeze_cols = 1; static int freeze_rows = 1; + + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + PopStyleCompact(); + // When using ScrollX or ScrollY we need to specify a size for our table container! + // Otherwise by default the table will fit all available space, like a BeginChild() call. + ImVec2 size = ImVec2(0, TEXT_BASE_HEIGHT * 8); if (ImGui::BeginTable("##table1", 7, flags, size)) { ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows); @@ -3741,13 +3778,10 @@ static void ShowDemoWindowTables() if (ImGui::BeginTable("##flags", column_count, ImGuiTableFlags_None)) { + PushStyleCompact(); for (int column = 0; column < column_count; column++) { - // Make the UI compact because there are so many fields ImGui::TableNextColumn(); - ImGuiStyle& style = ImGui::GetStyle(); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, 2)); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, 2)); ImGui::PushID(column); ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation ImGui::Text("Flags for '%s'", column_names[column]); @@ -3765,8 +3799,8 @@ static void ShowDemoWindowTables() ImGui::CheckboxFlags("_IndentEnable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentEnable); ImGui::SameLine(); HelpMarker("Default for column 0"); ImGui::CheckboxFlags("_IndentDisable", (unsigned int*)&column_flags[column], ImGuiTableColumnFlags_IndentDisable); ImGui::SameLine(); HelpMarker("Default for column >0"); ImGui::PopID(); - ImGui::PopStyleVar(2); } + PopStyleCompact(); ImGui::EndTable(); } @@ -3777,9 +3811,10 @@ static void ShowDemoWindowTables() for (int column = 0; column < column_count; column++) ImGui::TableSetupColumn(column_names[column], column_flags[column]); ImGui::TableHeadersRow(); + float indent_step = (float)((int)TEXT_BASE_WIDTH / 2); for (int row = 0; row < 8; row++) { - ImGui::Indent(2.0f); // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags. + ImGui::Indent(indent_step); // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags. ImGui::TableNextRow(); for (int column = 0; column < column_count; column++) { @@ -3787,7 +3822,7 @@ static void ShowDemoWindowTables() ImGui::Text("%s %s", (column == 0) ? "Indented" : "Hello", ImGui::TableGetColumnName(column)); } } - ImGui::Unindent(2.0f * 8.0f); + ImGui::Unindent(indent_step * 8.0f); ImGui::EndTable(); } @@ -3809,7 +3844,7 @@ static void ShowDemoWindowTables() ImGui::TableNextColumn(); ImGui::Text("A0 Cell 0"); { - float rows_height = ImGui::GetTextLineHeightWithSpacing() * 2; + float rows_height = TEXT_BASE_HEIGHT * 2; if (ImGui::BeginTable("recurse2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable)) { ImGui::TableSetupColumn("B0"); @@ -3844,11 +3879,12 @@ static void ShowDemoWindowTables() { HelpMarker("This section allows you to interact and see the effect of StretchX vs FixedX sizing policies depending on whether Scroll is enabled and the contents of your columns."); enum ContentsType { CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText }; + static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; static int contents_type = CT_FillButton; - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); - ImGui::Combo("Contents", &contents_type, "Short Text\0Long Text\0Button\0Fill Button\0InputText\0"); - static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg; + PushStyleCompact(); + ImGui::SetNextItemWidth(TEXT_BASE_WIDTH * 22); + ImGui::Combo("Contents", &contents_type, "Short Text\0Long Text\0Button\0Fill Button\0InputText\0"); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); @@ -3863,6 +3899,7 @@ static void ShowDemoWindowTables() ImGui::SameLine(); HelpMarker("Default if _ScrollX if enabled. Makes columns use _WidthFixed by default, or _WidthAlwaysAutoResize if _Resizable is not set."); ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", (unsigned int*)&flags, ImGuiTableFlags_NoClip); + PopStyleCompact(); if (ImGui::BeginTable("##3ways", 3, flags, ImVec2(0, 100))) { @@ -3896,16 +3933,17 @@ static void ShowDemoWindowTables() { // FIXME-TABLE: Vertical border not overridden the same way as horizontal one HelpMarker("Setting style.CellPadding to (0,0)."); - static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; + static bool no_widget_frame = false; + + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", (unsigned int*)&flags, ImGuiTableFlags_BordersOuter); ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); - - static bool no_widget_frame = false; ImGui::Checkbox("no_widget_frame", &no_widget_frame); + PopStyleCompact(); ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0, 0)); if (ImGui::BeginTable("##3ways", 3, flags)) @@ -3942,7 +3980,7 @@ static void ShowDemoWindowTables() { for (int row = 0; row < 10; row++) { - float min_row_height = (float)(int)(ImGui::GetFontSize() * 0.30f * row); + float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row); ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height); ImGui::TableNextColumn(); ImGui::Text("min_row_height = %.2f", min_row_height); @@ -3957,19 +3995,21 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Background color")) { static ImGuiTableFlags table_flags = ImGuiTableFlags_RowBg; - ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&table_flags, ImGuiTableFlags_Borders); - ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&table_flags, ImGuiTableFlags_RowBg); - ImGui::SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style."); - static int row_bg_type = 1; static int row_bg_target = 1; static int cell_bg_type = 1; + + PushStyleCompact(); + ImGui::CheckboxFlags("ImGuiTableFlags_Borders", (unsigned int*)&table_flags, ImGuiTableFlags_Borders); + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&table_flags, ImGuiTableFlags_RowBg); + ImGui::SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style."); ImGui::Combo("row bg type", (int*)&row_bg_type, "None\0Red\0Gradient\0"); ImGui::Combo("row bg target", (int*)&row_bg_target, "RowBg0\0RowBg1\0"); ImGui::SameLine(); HelpMarker("Target RowBg0 to override the alternating odd/even colors,\nTarget RowBg1 to blend with them."); ImGui::Combo("cell bg type", (int*)&cell_bg_type, "None\0Blue\0"); ImGui::SameLine(); HelpMarker("We are colorizing cells to B1->C2 here."); IM_ASSERT(row_bg_type >= 0 && row_bg_type <= 2); IM_ASSERT(row_bg_target >= 0 && row_bg_target <= 1); IM_ASSERT(cell_bg_type >= 0 && cell_bg_type <= 1); + PopStyleCompact(); if (ImGui::BeginTable("##Table", 5, table_flags)) { @@ -4012,14 +4052,16 @@ static void ShowDemoWindowTables() if (ImGui::TreeNode("Tree view")) { static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody; + //PushStyleCompact(); //ImGui::CheckboxFlags("ImGuiTableFlags_Scroll", (unsigned int*)&flags, ImGuiTableFlags_Scroll); + //PopStyleCompact(); if (ImGui::BeginTable("##3ways", 3, flags)) { // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide); - ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 6); - ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, ImGui::GetFontSize() * 10); + ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f); + ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 18.0f); ImGui::TableHeadersRow(); // Simple storage to output a dummy file-system. @@ -4133,7 +4175,10 @@ static void ShowDemoWindowTables() { HelpMarker("By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\nUsing ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body."); static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody; + + PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", (unsigned int*)&flags1, ImGuiTableFlags_ContextMenuInBody); + PopStyleCompact(); // Context Menus: first example // [1.1] Right-click on the TableHeadersRow() line to open the default table context menu. @@ -4256,11 +4301,11 @@ static void ShowDemoWindowTables() } } - static ImGuiTableFlags flags = + ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_MultiSortable | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_ScrollY; - if (ImGui::BeginTable("##table", 4, flags, ImVec2(0, 250), 0.0f)) + if (ImGui::BeginTable("##table", 4, flags, ImVec2(0, TEXT_BASE_HEIGHT * 15), 0.0f)) { // Declare columns // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. @@ -4328,95 +4373,99 @@ static void ShowDemoWindowTables() static int freeze_cols = 1; static int freeze_rows = 1; static int items_count = IM_ARRAYSIZE(template_items_names); - static ImVec2 outer_size_value = ImVec2(0, 250); + static ImVec2 outer_size_value = ImVec2(0, TEXT_BASE_HEIGHT * 15); static float row_min_height = 0.0f; // Auto static float inner_width_with_scroll = 0.0f; // Auto-extend static bool outer_size_enabled = true; static bool show_headers = true; static bool show_wrapped_text = false; //static ImGuiTextFilter filter; - //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which affects sizing - if (ImGui::TreeNodeEx("Options")) + //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affects column sizing + if (ImGui::TreeNode("Options")) { // Make the UI compact because there are so many fields - ImGuiStyle& style = ImGui::GetStyle(); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, 1)); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, 2)); - ImGui::PushItemWidth(200); + PushStyleCompact(); + ImGui::PushItemWidth(TEXT_BASE_WIDTH * 28.0f); - ImGui::BulletText("Features:"); - ImGui::Indent(); - ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); - ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", (unsigned int*)&flags, ImGuiTableFlags_Reorderable); - ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", (unsigned int*)&flags, ImGuiTableFlags_Hideable); - ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", (unsigned int*)&flags, ImGuiTableFlags_Sortable); - ImGui::CheckboxFlags("ImGuiTableFlags_MultiSortable", (unsigned int*)&flags, ImGuiTableFlags_MultiSortable); - ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", (unsigned int*)&flags, ImGuiTableFlags_NoSavedSettings); - ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", (unsigned int*)&flags, ImGuiTableFlags_ContextMenuInBody); - ImGui::Unindent(); - - ImGui::BulletText("Decoration:"); - ImGui::Indent(); - ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterH); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerH); - ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers"); - ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)"); - ImGui::Unindent(); + if (ImGui::TreeNodeEx("Features:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", (unsigned int*)&flags, ImGuiTableFlags_Resizable); + ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", (unsigned int*)&flags, ImGuiTableFlags_Reorderable); + ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", (unsigned int*)&flags, ImGuiTableFlags_Hideable); + ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", (unsigned int*)&flags, ImGuiTableFlags_Sortable); + ImGui::CheckboxFlags("ImGuiTableFlags_MultiSortable", (unsigned int*)&flags, ImGuiTableFlags_MultiSortable); + ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", (unsigned int*)&flags, ImGuiTableFlags_NoSavedSettings); + ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", (unsigned int*)&flags, ImGuiTableFlags_ContextMenuInBody); + ImGui::TreePop(); + } - ImGui::BulletText("Padding, Sizing:"); - ImGui::Indent(); - if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) - flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyStretchX); // Can't specify both sizing polices so we clear the other - ImGui::SameLine(); HelpMarker("[Default if ScrollX is off]\nFit all columns within available width (or specified inner_width). Fixed and Stretch columns allowed."); - if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyFixedX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyFixedX)) - flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyFixedX); // Can't specify both sizing polices so we clear the other - ImGui::SameLine(); HelpMarker("[Default if ScrollX is on]\nEnlarge as needed: enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rectangle. Only Fixed columns allowed. Stretched columns will calculate their width assuming no scrolling."); - ImGui::CheckboxFlags("ImGuiTableFlags_NoHeadersWidth", (unsigned int*)&flags, ImGuiTableFlags_NoHeadersWidth); - ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", (unsigned int*)&flags, ImGuiTableFlags_NoHostExtendY); - ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", (unsigned int*)&flags, ImGuiTableFlags_NoKeepColumnsVisible); - ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled."); - ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", (unsigned int*)&flags, ImGuiTableFlags_NoClip); - ImGui::SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options."); - ImGui::Unindent(); + if (ImGui::TreeNodeEx("Decoration:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", (unsigned int*)&flags, ImGuiTableFlags_RowBg); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", (unsigned int*)&flags, ImGuiTableFlags_BordersV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", (unsigned int*)&flags, ImGuiTableFlags_BordersH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", (unsigned int*)&flags, ImGuiTableFlags_BordersOuterH); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", (unsigned int*)&flags, ImGuiTableFlags_BordersInnerH); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appears in Headers"); + ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", (unsigned int*)&flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)"); + ImGui::TreePop(); + } - ImGui::BulletText("Scrolling:"); - ImGui::Indent(); - ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); - ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); - ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); - ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); - ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); - ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + if (ImGui::TreeNodeEx("Sizing, Padding:", ImGuiTreeNodeFlags_DefaultOpen)) + { + if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyStretchX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyStretchX)) + flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyStretchX); // Can't specify both sizing polices so we clear the other + ImGui::SameLine(); HelpMarker("[Default if ScrollX is off]\nFit all columns within available width (or specified inner_width). Fixed and Stretch columns allowed."); + if (ImGui::CheckboxFlags("ImGuiTableFlags_SizingPolicyFixedX", (unsigned int*)&flags, ImGuiTableFlags_SizingPolicyFixedX)) + flags &= ~(ImGuiTableFlags_SizingPolicyMaskX_ ^ ImGuiTableFlags_SizingPolicyFixedX); // Can't specify both sizing polices so we clear the other + ImGui::SameLine(); HelpMarker("[Default if ScrollX is on]\nEnlarge as needed: enable scrollbar if ScrollX is enabled, otherwise extend parent window's contents rectangle. Only Fixed columns allowed. Stretched columns will calculate their width assuming no scrolling."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHeadersWidth", (unsigned int*)&flags, ImGuiTableFlags_NoHeadersWidth); + ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", (unsigned int*)&flags, ImGuiTableFlags_NoHostExtendY); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", (unsigned int*)&flags, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled."); + ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", (unsigned int*)&flags, ImGuiTableFlags_NoClip); + ImGui::SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options."); + ImGui::TreePop(); + } - ImGui::Unindent(); + if (ImGui::TreeNodeEx("Scrolling:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", (unsigned int*)&flags, ImGuiTableFlags_ScrollX); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", (unsigned int*)&flags, ImGuiTableFlags_ScrollY); + ImGui::SameLine(); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight()); + ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput); + ImGui::TreePop(); + } - ImGui::BulletText("Other:"); - ImGui::Indent(); - ImGui::Checkbox("show_headers", &show_headers); - ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); - ImGui::DragFloat2("##OuterSize", &outer_size_value.x); - ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); - ImGui::Checkbox("outer_size", &outer_size_enabled); - ImGui::SameLine(); - HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set), the table is output directly in the parent window. OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendV is set)."); - - // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. - // To facilitate experimentation we expose two values and will select the right one depending on active flags. - ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX); - ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX); - ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); - ImGui::DragInt("items_count", &items_count, 0.1f, 0, 5000); - ImGui::Combo("contents_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names)); - //filter.Draw("filter"); - ImGui::Unindent(); + if (ImGui::TreeNodeEx("Other:", ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::Checkbox("show_headers", &show_headers); + ImGui::Checkbox("show_wrapped_text", &show_wrapped_text); + ImGui::DragFloat2("##OuterSize", &outer_size_value.x); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Checkbox("outer_size", &outer_size_enabled); + ImGui::SameLine(); + HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set), the table is output directly in the parent window. OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendV is set)."); + + // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. + // To facilitate experimentation we expose two values and will select the right one depending on active flags. + ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX); + ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX); + ImGui::SameLine(); HelpMarker("Specify height of the Selectable item."); + ImGui::DragInt("items_count", &items_count, 0.1f, 0, 9999); + ImGui::Combo("contents_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names)); + //filter.Draw("filter"); + ImGui::TreePop(); + } ImGui::PopItemWidth(); - ImGui::PopStyleVar(2); + PopStyleCompact(); ImGui::Spacing(); ImGui::TreePop(); } diff --git a/imgui_tables.cpp b/imgui_tables.cpp index c607a8b0..d7f99957 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -312,6 +312,14 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->RawData.resize(0); if (table->RawData.Size == 0) { + // For reference, the total _allocation count_ for a table is: + // + 0 (for ImGuiTable instance, we sharing allocation in g.Tables pool) + // + 1 (for table->RawData allocated below) + // + 1 (for table->Splitter._Channels) + // + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels) + // Where active_channels_count is variable but often == columns_count or columns_count + 1, see TableUpdateDrawChannels() for details. + // Unused channels don't perform their +2 allocations. + // Allocate single buffer for our arrays ImSpanAllocator<3> span_allocator; span_allocator.ReserveBytes(0, columns_count * sizeof(ImGuiTableColumn)); @@ -957,7 +965,7 @@ void ImGui::TableUpdateBorders(ImGuiTable* table) if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) continue; - // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() + // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body; if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false) continue; From ac5b1648e68fdb266b3b7c7591e627a4ecfd293a Mon Sep 17 00:00:00 2001 From: ocornut Date: Tue, 20 Oct 2020 19:36:06 +0200 Subject: [PATCH 478/959] Tables: Various internal renaming + merge StartXHeaders/StartXRows into StartX. --- imgui.cpp | 26 +++++++++++----------- imgui.h | 10 ++++----- imgui_internal.h | 21 +++++++++--------- imgui_tables.cpp | 56 +++++++++++++++++++++++------------------------- 4 files changed, 55 insertions(+), 58 deletions(-) diff --git a/imgui.cpp b/imgui.cpp index 4b85256d..fdabfd10 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -10501,8 +10501,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Debugging enums enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" }; - enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type - const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; + enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type + const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" }; if (cfg->ShowWindowsRectsType < 0) cfg->ShowWindowsRectsType = WRT_WorkRect; if (cfg->ShowTablesRectsType < 0) @@ -10512,17 +10512,17 @@ void ImGui::ShowMetricsWindow(bool* p_open) { static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n) { - if (rect_type == TRT_OuterRect) { return table->OuterRect; } - else if (rect_type == TRT_WorkRect) { return table->WorkRect; } - else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; } - else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; } - else if (rect_type == TRT_BackgroundClipRect) { return table->BackgroundClipRect; } - else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); } - else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; } - else if (rect_type == TRT_ColumnsContentHeadersUsed) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate - else if (rect_type == TRT_ColumnsContentHeadersIdeal) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // " - else if (rect_type == TRT_ColumnsContentRowsFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthRowsFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // " - else if (rect_type == TRT_ColumnsContentRowsUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->MinX + c->ContentWidthRowsUnfrozen, table->InnerClipRect.Max.y); } // " + if (rect_type == TRT_OuterRect) { return table->OuterRect; } + else if (rect_type == TRT_WorkRect) { return table->WorkRect; } + else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; } + else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; } + else if (rect_type == TRT_BackgroundClipRect) { return table->BackgroundClipRect; } + else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); } + else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; } + else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate + else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } + else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MinX + c->ContentWidthFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } + else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->MinX + c->ContentWidthUnfrozen, table->InnerClipRect.Max.y); } IM_ASSERT(0); return ImRect(); } diff --git a/imgui.h b/imgui.h index 02879546..97ddc231 100644 --- a/imgui.h +++ b/imgui.h @@ -654,9 +654,9 @@ namespace ImGui // Tables // [ALPHA API] API may evolve! - // - Full-featured replacement for old Columns API + // - Full-featured replacement for old Columns API. // - See Demo->Tables for details. - // - See ImGuiTableFlags_ and ImGuiTableColumnsFlags_ enums for a description of available flags. + // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags. // The typical call flow is: // - 1. Call BeginTable() // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults @@ -684,7 +684,7 @@ namespace ImGui IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true if column is visible. IMGUI_API int TableGetColumnIndex(); // return current column index. // Tables: Headers & Columns declaration - // - Use TableSetupColumn() to specify label, resizing policy, default width, id, various other flags etc. + // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc. // Important: this will not display anything! The name passed to TableSetupColumn() is used by TableHeadersRow() and context-menus. // - Use TableHeadersRow() to create a row and automatically submit a TableHeader() for each column. // Headers are required to perform some interactions: reordering, sorting, context menu (FIXME-TABLE: context menu should work without!) @@ -1070,13 +1070,13 @@ enum ImGuiTableFlags_ ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. ImGuiTableFlags_NoBordersInBody = 1 << 12, // Disable vertical borders in columns Body (borders will always appears in Headers). ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 13, // Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers). - // Sizing, Padding + // Sizing ImGuiTableFlags_SizingPolicyFixedX = 1 << 14, // Default if ScrollX is on. Columns will default to use _WidthFixed or _WidthAlwaysAutoResize policy. Read description above for more details. ImGuiTableFlags_SizingPolicyStretchX = 1 << 15, // Default if ScrollX is off. Columns will default to use _WidthStretch policy. Read description above for more details. ImGuiTableFlags_NoHeadersWidth = 1 << 16, // Disable header width contribution to automatic width calculation. ImGuiTableFlags_NoHostExtendY = 1 << 17, // (FIXME-TABLE: Reword as SizingPolicy?) Disable extending past the limit set by outer_size.y, only meaningful when neither of ScrollX|ScrollY are set (data below the limit will be clipped and not visible) ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // (FIXME-TABLE) Disable code that keeps column always minimally visible when table width gets too small and horizontal scrolling is off. - ImGuiTableFlags_NoClip = 1 << 19, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options. + ImGuiTableFlags_NoClip = 1 << 19, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). // Scrolling ImGuiTableFlags_ScrollX = 1 << 20, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Because this create a child window, ScrollY is currently generally recommended when using ScrollX. ImGuiTableFlags_ScrollY = 1 << 21, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. diff --git a/imgui_internal.h b/imgui_internal.h index ea45d384..dc81fdfa 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1901,15 +1901,14 @@ struct ImGuiTableColumn float WidthStretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from WidthStretchWeight in TableUpdateLayout() float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be >WidthRequest to honor minimum width, may be