diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index b089bfb4..eea8eaa3 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'
@@ -157,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:
@@ -233,6 +256,46 @@ 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_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
@@ -269,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
@@ -319,45 +389,12 @@ 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: |
- source emsdk-master/emsdk_env.sh
+ pushd emsdk-master
+ 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/CHANGELOG.txt b/docs/CHANGELOG.txt
index 8161ae77..df364f32 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?
@@ -100,11 +101,143 @@ Other changes:
-----------------------------------------------------------------------
- VERSION 1.77 WIP (In Progress)
+ VERSION 1.79 WIP (In Progress)
+-----------------------------------------------------------------------
+
+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)
+- 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.)
+- 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]
+
+
+-----------------------------------------------------------------------
+ VERSION 1.78 (Released 2020-08-18)
-----------------------------------------------------------------------
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 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 (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.
+ - Code will assert at runtime for IM_ASSERT(power == 1.0f) with the following assert description:
+ "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 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.
+- 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:
+
+- 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.
+- 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()
+ 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
+ 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
+ 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.
+- 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.
+ - 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() 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.
+- 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]
+- CI: Emscripten has stopped their support for their fastcomp backend, switching to latest sdk [@Xipiryon]
+
+
+-----------------------------------------------------------------------
+ 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 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
+ of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
+ Kept inline redirection function (will obsolete).
+- Removed obsoleted CalcItemRectClosestPoint() entry point (has been asserting since December 2017).
+
Other Changes:
- TreeNode: Fixed bug where BeginDragDropSource() failed when the _OpenOnDoubleClick flag is
@@ -112,7 +245,70 @@ 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)
+- 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().
+- 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)
+- 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(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.
+ 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]
+- 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
+ a callback draw command would incorrectly override the callback draw command.
+- 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 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,
+ 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]
+- 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]
+- 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]
-----------------------------------------------------------------------
@@ -523,7 +719,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]
@@ -590,11 +786,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
@@ -606,7 +802,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)
@@ -683,7 +879,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]
@@ -791,7 +987,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:
@@ -1283,7 +1479,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 6c140760..2745b122 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -15,18 +15,21 @@ 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) |
| **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)** |
+| **[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) |
| [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) |
@@ -77,12 +80,24 @@ 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)
----
# 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.
@@ -96,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.)
@@ -134,20 +149,23 @@ 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)
---
### 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)
@@ -155,7 +173,9 @@ and **NOT** as
# 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: 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?
A primer on labels and the ID Stack...
@@ -277,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)
@@ -432,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)
@@ -441,10 +462,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()
@@ -454,12 +498,12 @@ 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 "\\":
-```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
@@ -473,9 +517,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 +527,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
new file mode 100644
index 00000000..158e08ab
--- /dev/null
+++ b/docs/FONTS.md
@@ -0,0 +1,389 @@
+## Dear ImGui: Using Fonts
+
+(You may browse this document at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer.)
+
+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.
+
+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!)
+
+**Use the Discord server**: http://discord.dearimgui.org and not the GitHub issue tracker for basic font loading questions.
+
+## 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)
+- [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
+
+- 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.
+
+- 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`:
+
+![imgui_capture_0008](https://user-images.githubusercontent.com/8225057/84162822-1a731f00-aa71-11ea-9b6b-89c2332aa161.png)
+
+- Make sure your font ranges data are persistent (available during the calls to `GetTexDataAsAlpha8()`/`GetTexDataAsRGBA32()/`Build()`.
+
+- 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
+```
+
+##### [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:**
+```cpp
+ImGuiIO& io = ImGui::GetIO();
+io.Fonts->AddFontDefault();
+```
+
+
+**Load .TTF/.OTF file with:**
+```cpp
+ImGuiIO& io = ImGui::GetIO();
+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();
+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();
+```
+
+
+**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);
+```
+
+
+**Combine multiple 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()); // Merge into first font
+io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); // Merge into first font
+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());
+
+// 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());
+```
+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);
+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.
+- 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 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).
+
+##### [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.
+
+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.
+
+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);
+```
+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.
+
+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/](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.
+
+##### [Return to Index](#index)
+
+## Using 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)
+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.
+- 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:
+```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);
+ }
+ }
+}
+```
+
+##### [Return to Index](#index)
+
+## Using Font Data Embedded In Source Code
+
+- 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:
+```cpp
+ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);
+```
+or
+```cpp
+ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
+```
+
+##### [Return to Index](#index)
+
+## About filenames
+
+**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 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
+ http://www.proggyfonts.net/
+
+ProggyTiny.ttf
+ Copyright (c) 2004, 2005 Tristan Grimmer
+ MIT License
+ recommended loading setting: Size = 10.0, DisplayOffset.Y = +1
+ http://www.proggyfonts.net/
+
+Karla-Regular.ttf
+ Copyright (c) 2012, Jonathan Pinhorn
+ SIL OPEN FONT LICENSE Version 1.1
+```
+
+##### [Return to Index](#index)
+
+## 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
+
+#### 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 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
+- 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.)
+
+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).
+
+##### [Return to Index](#index)
diff --git a/docs/FONTS.txt b/docs/FONTS.txt
deleted file mode 100644
index e3690f14..00000000
--- a/docs/FONTS.txt
+++ /dev/null
@@ -1,376 +0,0 @@
-dear imgui
-FONTS DOCUMENTATION
-
-Also read https://www.dearimgui.org/faq for more fonts related infos.
-
-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.
-
-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.
-
-
----------------------------------------
- INDEX:
----------------------------------------
-
-- 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
-
-
----------------------------------------
- README FIRST / FAQ
----------------------------------------
-
-- 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.
-- 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.
-
-
----------------------------------------
- FONTS LOADING INSTRUCTIONS
----------------------------------------
-
-Load default font:
-
- ImGuiIO& io = ImGui::GetIO();
- io.Fonts->AddFontDefault();
-
-Load .TTF/.OTF file with:
-
- ImGuiIO& io = ImGui::GetIO();
- io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
-
-Load multiple fonts:
-
- 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();
-
-For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally):
-
- ImFontConfig config;
- config.OversampleH = 2;
- config.OversampleV = 1;
- config.GlyphExtraSpacing.x = 1.0f;
- ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config);
-
-Combine two fonts into one:
-
- // 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();
-
-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:
-
- // 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());
-
-See "BUILDING CUSTOM GLYPH RANGES" section to create your own ranges.
-Offset font vertically by altering the io.Font->DisplayOffset value:
-
- ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
- font->DisplayOffset.y = 1; // Render 1 pixel down
-
-
----------------------------------------
- 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.
-
-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:
-
- // 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.
-
-
----------------------------------------
- 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.
-
- 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.
-
-
----------------------------------------
- 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.
-
-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);
- }
- }
- }
-
-
----------------------------------------
- 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.
-
-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, ...);
-
-
----------------------------------------
- CREDITS/LICENSES FOR FONTS INCLUDED IN REPOSITORY
----------------------------------------
-
-Some fonts are available in the misc/fonts/ folder:
-
-Roboto-Medium.ttf
-
- Apache License 2.0
- by Christian Robertson
- 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
- http://www.proggyfonts.net/
-
-ProggyTiny.ttf
- Copyright (c) 2004, 2005 Tristan Grimmer
- MIT License
- recommended loading setting: Size = 10.0, DisplayOffset.Y = +1
- http://www.proggyfonts.net/
-
-Karla-Regular.ttf
- Copyright (c) 2012, Jonathan Pinhorn
- SIL OPEN FONT LICENSE Version 1.1
-
-
----------------------------------------
- FONTS 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
-
-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
-
-MONOSPACE FONTS (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 .inl file to use directly in dear imgui.
-
-MONOSPACE 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 user interface and 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).
diff --git a/docs/README.md b/docs/README.md
index 72ebea3d..58fb208e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,11 +1,12 @@
-dear imgui
+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.)
+
+(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).
@@ -86,7 +87,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._
@@ -96,10 +97,10 @@ 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:
-- [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).
+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).
-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
@@ -113,8 +114,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.
@@ -122,11 +123,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), 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.
### Gallery
@@ -144,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.
@@ -154,13 +155,13 @@ 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?**
-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.
+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?**
@@ -174,14 +175,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!
+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 +195,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), [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,15 +209,18 @@ 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).
+
+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.
+"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).
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/docs/TODO.txt b/docs/TODO.txt
index 04f2f980..52c531f1 100644
--- a/docs/TODO.txt
+++ b/docs/TODO.txt
@@ -26,8 +26,8 @@ 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/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,7 +35,8 @@ 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).
+ - 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.
@@ -55,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.
@@ -79,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)
@@ -112,7 +115,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?
@@ -135,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.
@@ -156,6 +159,7 @@ 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)
@@ -190,13 +194,15 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
- docking: C- nav: CTRL+TAB highlighting tabs shows the mismatch between focus-stack and tab-order (not visible in VS because it doesn't highlight the tabs)
- docking: C- after a dock/undock, the Scrollbar Status update in Begin() should use an updated e.g. size_y_for_scrollbars to avoid a 1 frame scrollbar flicker.
+ - 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: 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()?
- 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)
@@ -208,9 +214,9 @@ 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: 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)
@@ -231,12 +237,14 @@ 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
- - popups: reopening context menu at new position should be the behavior by default? (equivalent to internal OpenPopupEx() with reopen_existing=true) (~#1497)
+ - 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: 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.
- tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred direction" and may teleport when moving mouse.
@@ -259,13 +267,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)
@@ -312,6 +322,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)
@@ -337,7 +348,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?
@@ -406,7 +418,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)
@@ -424,6 +435,8 @@ 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)
- backends: opengl: rename imgui_impl_opengl2 to impl_opengl_legacy and imgui_impl_opengl3 to imgui_impl_opengl? (#1900)
@@ -434,7 +447,9 @@ 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)
+ - 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)
- 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 c8801b16..a1376fa3 100644
--- a/examples/README.txt
+++ b/examples/README.txt
@@ -1,5 +1,5 @@
-----------------------------------------------------------------------
- dear imgui, v1.77 WIP
+ dear imgui, v1.79 WIP
-----------------------------------------------------------------------
examples/README.txt
(This is the README file for the examples/ folder. See docs/ for more documentation)
@@ -33,29 +33,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.
---------------------------------------
@@ -162,12 +167,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.
@@ -206,7 +211,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
@@ -255,7 +260,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_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/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp
index 001a4399..a9026c2e 100644
--- a/examples/example_allegro5/main.cpp
+++ b/examples/example_allegro5/main.cpp
@@ -41,7 +41,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_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 308a0630..33f75b8e 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
diff --git a/examples/example_emscripten/README.md b/examples/example_emscripten/README.md
index dcb7c1a7..42bab014 100644
--- a/examples/example_emscripten/README.md
+++ b/examples/example_emscripten/README.md
@@ -1,12 +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.
-- 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:
+## 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.
+- 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:
-`#EMS += -s BINARYEN_TRAP_MODE=clamp`
+- 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`
diff --git a/examples/example_emscripten/main.cpp b/examples/example_emscripten/main.cpp
index 7ee4640d..742d9be3 100644
--- a/examples/example_emscripten/main.cpp
+++ b/examples/example_emscripten/main.cpp
@@ -82,7 +82,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 051d4281..46c651cc 100644
--- a/examples/example_glfw_opengl2/main.cpp
+++ b/examples/example_glfw_opengl2/main.cpp
@@ -71,7 +71,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/Makefile b/examples/example_glfw_opengl3/Makefile
index 7696eaae..0e7faa12 100644
--- a/examples/example_glfw_opengl3/Makefile
+++ b/examples/example_glfw_opengl3/Makefile
@@ -35,18 +35,25 @@ 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
# 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)
-# 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_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp
index 19d00af9..c9e94c7e 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; // 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();
@@ -131,7 +135,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 da23d247..080caad9 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()
@@ -247,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;
@@ -285,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);
@@ -309,7 +310,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd)
}
}
-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 = {};
@@ -320,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
}
@@ -329,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
@@ -364,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);
@@ -412,7 +411,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);
@@ -467,11 +466,12 @@ 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);
- 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;
}
@@ -519,8 +519,11 @@ int main(int, char**)
// Rendering
ImGui::Render();
+ ImDrawData* main_draw_data = ImGui::GetDrawData();
+ const bool main_is_minimized = (main_draw_data->DisplaySize.x <= 0.0f || main_draw_data->DisplaySize.y <= 0.0f);
memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float));
- FrameRender(wd);
+ if (!main_is_minimized)
+ FrameRender(wd, main_draw_data);
// Update and Render additional Platform Windows
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
@@ -529,7 +532,9 @@ int main(int, char**)
ImGui::RenderPlatformWindowsDefault();
}
- FramePresent(wd);
+ // Present Main Platform Window
+ if (!main_is_minimized)
+ FramePresent(wd);
}
// Cleanup
diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp
index b790c8c0..73a57216 100644
--- a/examples/example_glut_opengl2/main.cpp
+++ b/examples/example_glut_opengl2/main.cpp
@@ -126,7 +126,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 0cd99162..7260cda0 100644
--- a/examples/example_marmalade/main.cpp
+++ b/examples/example_marmalade/main.cpp
@@ -35,7 +35,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_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/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/example_sdl_directx11/main.cpp b/examples/example_sdl_directx11/main.cpp
index 5bb47755..ab9ca296 100644
--- a/examples/example_sdl_directx11/main.cpp
+++ b/examples/example_sdl_directx11/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 \\ !
//io.Fonts->AddFontDefault();
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
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_opengl2/main.cpp b/examples/example_sdl_opengl2/main.cpp
index aa765634..12c389a7 100644
--- a/examples/example_sdl_opengl2/main.cpp
+++ b/examples/example_sdl_opengl2/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_opengl3/Makefile b/examples/example_sdl_opengl3/Makefile
index ada77197..e8009a4c 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++
@@ -35,18 +35,25 @@ 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
# 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)
-# 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/main.cpp b/examples/example_sdl_opengl3/main.cpp
index b898b4a0..44068a79 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; // 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();
@@ -126,7 +130,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 7d84f34a..0024594a 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()
@@ -239,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;
@@ -277,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);
@@ -301,7 +302,7 @@ static void FrameRender(ImGui_ImplVulkanH_Window* wd)
}
}
-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 = {};
@@ -312,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
}
@@ -396,7 +403,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);
@@ -456,19 +463,14 @@ 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))
- {
- 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);
- 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;
}
@@ -516,8 +518,11 @@ int main(int, char**)
// Rendering
ImGui::Render();
+ ImDrawData* main_draw_data = ImGui::GetDrawData();
+ const bool main_is_minimized = (main_draw_data->DisplaySize.x <= 0.0f || main_draw_data->DisplaySize.y <= 0.0f);
memcpy(&wd->ClearValue.color.float32[0], &clear_color, 4 * sizeof(float));
- FrameRender(wd);
+ if (!main_is_minimized)
+ FrameRender(wd, main_draw_data);
// Update and Render additional Platform Windows
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
@@ -526,7 +531,9 @@ int main(int, char**)
ImGui::RenderPlatformWindowsDefault();
}
- FramePresent(wd);
+ // Present Main Platform Window
+ if (!main_is_minimized)
+ FramePresent(wd);
}
// Cleanup
diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp
index 284bf787..c475b80f 100644
--- a/examples/example_win32_directx10/main.cpp
+++ b/examples/example_win32_directx10/main.cpp
@@ -28,6 +28,7 @@ int main(int, char**)
ImGui_ImplWin32_EnableDpiAwareness();
// 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);
@@ -76,7 +77,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 d3828ff9..1062d6fd 100644
--- a/examples/example_win32_directx11/main.cpp
+++ b/examples/example_win32_directx11/main.cpp
@@ -28,6 +28,7 @@ int main(int, char**)
ImGui_ImplWin32_EnableDpiAwareness();
// 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);
@@ -83,7 +84,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 35f57285..96b534b7 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);
@@ -108,7 +109,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 d96e5c48..665cff00 100644
--- a/examples/example_win32_directx9/main.cpp
+++ b/examples/example_win32_directx9/main.cpp
@@ -26,6 +26,7 @@ int main(int, char**)
ImGui_ImplWin32_EnableDpiAwareness();
// 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);
@@ -74,7 +75,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/imgui_impl_allegro5.cpp b/examples/imgui_impl_allegro5.cpp
index 76f74a3f..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().
@@ -174,7 +175,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 +183,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 +191,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 +212,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 +323,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();
@@ -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;
@@ -357,7 +358,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:
@@ -402,7 +404,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;
@@ -412,7 +414,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 95dc6fd2..6d69a4a3 100644
--- a/examples/imgui_impl_dx10.cpp
+++ b/examples/imgui_impl_dx10.cpp
@@ -43,11 +43,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;
@@ -295,7 +293,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;
@@ -350,46 +348,53 @@ 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;\
}";
- 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[] =
{
- { "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, 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
{
@@ -421,11 +426,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
@@ -488,11 +497,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 ffd05625..7d4750ad 100644
--- a/examples/imgui_impl_dx11.cpp
+++ b/examples/imgui_impl_dx11.cpp
@@ -44,11 +44,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;
@@ -307,7 +305,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;
@@ -362,46 +360,53 @@ 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;\
}";
- 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[] =
{
- { "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, 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
{
@@ -433,11 +438,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
@@ -500,11 +509,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 446546fb..690f3a8b 100644
--- a/examples/imgui_impl_dx12.cpp
+++ b/examples/imgui_impl_dx12.cpp
@@ -40,8 +40,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;
@@ -51,7 +49,8 @@ static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {};
static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL;
static UINT g_numFramesInFlight = 0;
-struct FrameResources
+// Buffers used during the rendering of a frame
+struct ImGui_ImplDX12_RenderBuffers
{
ID3D12Resource* IndexBuffer;
ID3D12Resource* VertexBuffer;
@@ -59,28 +58,32 @@ struct FrameResources
int VertexBufferSize;
};
-struct FrameContext
+// Buffers used for secondary viewports created by the multi-viewports systems
+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* 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.
+// 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,6 +137,13 @@ static void SafeRelease(T*& res)
res = NULL;
}
+static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers)
+{
+ SafeRelease(render_buffers->IndexBuffer);
+ SafeRelease(render_buffers->VertexBuffer);
+ render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0;
+}
+
struct VERTEX_CONSTANT_BUFFER
{
float mvp[4][4];
@@ -144,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).
@@ -209,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)
@@ -434,7 +443,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));
@@ -546,6 +555,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 =
@@ -576,13 +588,13 @@ 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[] = {
+ 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 },
@@ -608,10 +620,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
@@ -656,7 +670,10 @@ bool ImGui_ImplDX12_CreateDeviceObjects()
desc.BackFace = desc.FrontFace;
}
- if (g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)) != S_OK)
+ 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();
@@ -669,8 +686,6 @@ void ImGui_ImplDX12_InvalidateDeviceObjects()
if (!g_pd3dDevice)
return;
- SafeRelease(g_pVertexShaderBlob);
- SafeRelease(g_pPixelShaderBlob);
SafeRelease(g_pRootSignature);
SafeRelease(g_pPipelineState);
SafeRelease(g_pFontTextureResource);
@@ -695,6 +710,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)();
@@ -708,6 +725,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_DestroyRenderBuffers(&data->FrameRenderBuffers[i]);
+ IM_DELETE(data);
+ main_viewport->RendererUserData = NULL;
+ }
+
+ // Clean up windows and device objects
ImGui_ImplDX12_ShutdownPlatformInterface();
ImGui_ImplDX12_InvalidateDeviceObjects();
@@ -716,11 +745,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()
@@ -837,9 +861,20 @@ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport)
}
for (UINT i = 0; i < g_numFramesInFlight; i++)
+ ImGui_ImplDX12_DestroyRenderBuffers(&data->FrameRenderBuffers[i]);
+}
+
+static void ImGui_WaitForPendingOperations(ImGuiViewportDataDx12* data)
+{
+ HRESULT hr = S_FALSE;
+ if (data && data->CommandQueue && data->Fence && data->FenceEvent)
{
- SafeRelease(data->Resources[i].IndexBuffer);
- SafeRelease(data->Resources[i].VertexBuffer);
+ 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);
}
}
@@ -848,17 +883,7 @@ 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);
@@ -872,8 +897,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_DestroyRenderBuffers(&data->FrameRenderBuffers[i]);
}
IM_DELETE(data);
}
@@ -884,6 +908,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);
@@ -904,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);
diff --git a/examples/imgui_impl_dx9.cpp b/examples/imgui_impl_dx9.cpp
index 27435cbc..f8abc61a 100644
--- a/examples/imgui_impl_dx9.cpp
+++ b/examples/imgui_impl_dx9.cpp
@@ -207,7 +207,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;
@@ -269,7 +269,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
@@ -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()
diff --git a/examples/imgui_impl_glfw.cpp b/examples/imgui_impl_glfw.cpp
index f1d38701..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
@@ -74,7 +82,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;
static bool g_WantUpdateMonitors = true;
@@ -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_GLFW_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_GLFW_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
}
@@ -470,7 +482,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();
@@ -586,7 +598,7 @@ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport)
{
if (data->WindowOwned)
{
-#if GLFW_HAS_GLFW_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 defined(_WIN32) && GLFW_HAS_GLFW_HOVERED
+#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_GLFW_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
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 e97d9add..c12755d9 100644
--- a/examples/imgui_impl_metal.h
+++ b/examples/imgui_impl_metal.h
@@ -18,7 +18,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_opengl3.cpp b/examples/imgui_impl_opengl3.cpp
index 2ac4e3e5..a3cf8a97 100644
--- a/examples/imgui_impl_opengl3.cpp
+++ b/examples/imgui_impl_opengl3.cpp
@@ -15,6 +15,9 @@
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2020-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
+// 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.
// 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
// 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
@@ -24,7 +27,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.
@@ -79,27 +82,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)
@@ -121,13 +104,19 @@
#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.
+#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;
@@ -148,8 +137,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;
// Forward Declarations
@@ -164,7 +153,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
@@ -186,6 +175,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";
@@ -194,7 +186,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.
@@ -207,6 +199,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)
@@ -217,7 +211,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;
@@ -254,6 +248,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);
@@ -261,6 +263,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 },
@@ -305,14 +308,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);
@@ -329,12 +332,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)
@@ -355,8 +352,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++)
{
@@ -382,10 +379,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);
@@ -665,9 +659,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);
diff --git a/examples/imgui_impl_opengl3.h b/examples/imgui_impl_opengl3.h
index 1d5a485e..5000b931 100644
--- a/examples/imgui_impl_opengl3.h
+++ b/examples/imgui_impl_opengl3.h
@@ -13,7 +13,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.
@@ -37,36 +37,52 @@ 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_GLAD2) \
&& !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_GLAD2
+#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
diff --git a/examples/imgui_impl_osx.h b/examples/imgui_impl_osx.h
index b9deb4a4..8aa0d7a2 100644
--- a/examples/imgui_impl_osx.h
+++ b/examples/imgui_impl_osx.h
@@ -16,5 +16,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_osx.mm b/examples/imgui_impl_osx.mm
index 7af4458f..f84efbb5 100644
--- a/examples/imgui_impl_osx.mm
+++ b/examples/imgui_impl_osx.mm
@@ -15,6 +15,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).
@@ -28,6 +29,8 @@
static CFAbsoluteTime g_Time = 0.0;
static NSCursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {};
static bool g_MouseCursorHidden = false;
+static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {};
+static bool g_MouseDown[ImGuiMouseButton_COUNT] = {};
// Undocumented methods for creating cursors.
@interface NSCursor()
@@ -122,9 +125,17 @@ void ImGui_ImplOSX_Shutdown()
{
}
-static void ImGui_ImplOSX_UpdateMouseCursor()
+static void ImGui_ImplOSX_UpdateMouseCursorAndButtons()
{
+ // Update buttons
ImGuiIO& io = ImGui::GetIO();
+ 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];
+ g_MouseJustPressed[i] = false;
+ }
+
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return;
@@ -168,7 +179,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)
@@ -198,16 +209,16 @@ 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_MouseDown))
+ g_MouseDown[button] = g_MouseJustPressed[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;
}
diff --git a/examples/imgui_impl_sdl.cpp b/examples/imgui_impl_sdl.cpp
index b0c84d77..e1cfa7ff 100644
--- a/examples/imgui_impl_sdl.cpp
+++ b/examples/imgui_impl_sdl.cpp
@@ -20,6 +20,7 @@
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2020-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
+// 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.
@@ -452,6 +453,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)
diff --git a/examples/imgui_impl_vulkan.cpp b/examples/imgui_impl_vulkan.cpp
index 3d0ad9a1..2b8af9d2 100644
--- a/examples/imgui_impl_vulkan.cpp
+++ b/examples/imgui_impl_vulkan.cpp
@@ -23,6 +23,8 @@
// 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.
// 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
@@ -234,7 +236,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<TotalVtxCount > 0)
{
VkBuffer vertex_buffers[1] = { rb->VertexBuffer };
VkDeviceSize vertex_offset[1] = { 0 };
@@ -329,7 +332,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;
@@ -349,21 +352,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 (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);
@@ -457,7 +459,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
- size_t upload_size = width*height*4*sizeof(char);
+ size_t upload_size = width * height * 4 * sizeof(char);
VkResult err;
@@ -1034,6 +1036,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);
@@ -1190,7 +1193,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);
@@ -1306,7 +1310,7 @@ static void ImGui_ImplVulkan_CreateWindow(ImGuiViewport* viewport)
// Create SwapChain, RenderPass, Framebuffer, etc.
wd->ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true;
- ImGui_ImplVulkanH_CreateWindow(v->Instance, v->PhysicalDevice, v->Device, wd, v->QueueFamily, v->Allocator, (int)viewport->Size.x, (int)viewport->Size.y, v->MinImageCount);
+ ImGui_ImplVulkanH_CreateOrResizeWindow(v->Instance, v->PhysicalDevice, v->Device, wd, v->QueueFamily, v->Allocator, (int)viewport->Size.x, (int)viewport->Size.y, v->MinImageCount);
data->WindowOwned = true;
}
@@ -1331,7 +1335,7 @@ static void ImGui_ImplVulkan_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
return;
ImGui_ImplVulkan_InitInfo* v = &g_VulkanInitInfo;
data->Window.ClearEnable = (viewport->Flags & ImGuiViewportFlags_NoRendererClear) ? false : true;
- ImGui_ImplVulkanH_CreateWindow(v->Instance, v->PhysicalDevice, v->Device, &data->Window, v->QueueFamily, v->Allocator, (int)size.x, (int)size.y, v->MinImageCount);
+ ImGui_ImplVulkanH_CreateOrResizeWindow(v->Instance, v->PhysicalDevice, v->Device, &data->Window, v->QueueFamily, v->Allocator, (int)size.x, (int)size.y, v->MinImageCount);
}
static void ImGui_ImplVulkan_RenderWindow(ImGuiViewport* viewport, void*)
diff --git a/examples/imgui_impl_vulkan.h b/examples/imgui_impl_vulkan.h
index e9db7727..eb3229e1 100644
--- a/examples/imgui_impl_vulkan.h
+++ b/examples/imgui_impl_vulkan.h
@@ -73,7 +73,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);
diff --git a/examples/imgui_impl_win32.cpp b/examples/imgui_impl_win32.cpp
index c37114cc..878efeeb 100644
--- a/examples/imgui_impl_win32.cpp
+++ b/examples/imgui_impl_win32.cpp
@@ -71,9 +71,9 @@ static void ImGui_ImplWin32_UpdateMonitors();
// 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
@@ -306,7 +306,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;
@@ -445,7 +445,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);
@@ -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
@@ -491,7 +494,9 @@ void ImGui_ImplWin32_EnableDpiAwareness()
return;
}
}
- SetProcessDPIAware();
+#if _WIN32_WINNT >= 0x0600
+ ::SetProcessDPIAware();
+#endif
}
#if defined(_MSC_VER) && !defined(NOGDI)
@@ -501,7 +506,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"))
diff --git a/imgui.cpp b/imgui.cpp
index 970fc9cc..c0279359 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,10 +1,10 @@
-// dear imgui, v1.77 WIP
+// dear imgui, v1.79 WIP
// (main code and documentation)
// 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:
@@ -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.
@@ -171,7 +171,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.
@@ -375,14 +375,27 @@ CODE
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
(Docking/Viewport Branch)
- - 2019/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
+ - 2020/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
- reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
- likewise io.MousePos and GetMousePos() will use OS coordinates.
If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
- - 2019/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api.
-
-
+ - 2020/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api.
+
+
+ - 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 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 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.
+ - 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.
@@ -424,7 +437,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).
@@ -515,7 +528,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.
@@ -608,7 +621,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
@@ -630,143 +646,32 @@ 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
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: 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: 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)
@@ -775,11 +680,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 and docs/FONTS.txt
+ >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
Q&A: Concerns
=============
@@ -870,21 +776,21 @@ 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'
-#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.
+#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 "-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 "-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 "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#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
@@ -910,27 +816,29 @@ 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.
// 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
//-------------------------------------------------------------------------
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, ImVec2 size, ImGuiWindowFlags flags);
-static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
+static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
+static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector* out_sorted_windows, ImGuiWindow* window);
// Settings
+static void WindowSettingsHandler_ClearAll(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
@@ -946,6 +854,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();
@@ -964,7 +873,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);
@@ -1031,7 +940,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
@@ -1052,16 +961,19 @@ 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.
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.
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.
+ 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.
@@ -1089,7 +1001,10 @@ 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);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
@@ -1105,7 +1020,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";
@@ -1172,17 +1087,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;
}
@@ -1207,7 +1126,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);
}
}
@@ -1252,7 +1171,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);
@@ -1266,12 +1185,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);
}
@@ -1725,7 +1644,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);
@@ -1772,7 +1691,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;
}
@@ -1792,8 +1711,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)
@@ -1809,13 +1728,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);
@@ -1851,7 +1770,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,
@@ -1902,7 +1821,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);
@@ -2119,7 +2038,7 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector 0)
- SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
+ SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
@@ -2332,7 +2251,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;
}
@@ -2366,7 +2285,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;
@@ -2796,7 +2715,7 @@ void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border,
const float border_size = g.Style.FrameBorderSize;
if (border && 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);
}
}
@@ -2808,7 +2727,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);
}
}
@@ -2831,11 +2750,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();
}
@@ -3036,7 +2955,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();
@@ -3071,6 +2990,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)
@@ -3088,7 +3008,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)
@@ -3190,7 +3110,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->ID || window->DC.LastItemId == window->MoveId) && window->WriteAccessed)
return false;
@@ -3211,22 +3131,30 @@ 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;
+ }
- SetHoveredID(id);
+ // 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();
+ // [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;
}
@@ -3242,6 +3170,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)
{
@@ -3291,11 +3228,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);
}
@@ -3422,7 +3369,7 @@ static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist
// Our ImDrawList system requires that there is always a command
if (viewport->LastFrameDrawLists[drawlist_no] != g.FrameCount)
{
- draw_list->Clear();
+ draw_list->_ResetForNewFrame();
draw_list->PushTextureID(g.IO.Fonts->TexID);
draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
viewport->LastFrameDrawLists[drawlist_no] = g.FrameCount;
@@ -3466,7 +3413,8 @@ void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
- g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
+ g.ActiveIdNoClearOnFocusLoss = true;
+ g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
@@ -3499,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
@@ -3583,16 +3525,26 @@ void ImGui::UpdateMouseMovingWindowEndFrame()
// (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
if (g.IO.MouseClicked[0])
{
+ // 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.HoveredWindow ? g.HoveredWindow->RootWindowDockStop : NULL;
- if (root_window != NULL)
+ 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)
{
StartMouseMovingWindow(g.HoveredWindow);
+
+ // Cancel moving if clicked outside of title bar
if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
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 (note that we know HoveredId == 0 already)
+ if (g.HoveredIdDisabled)
+ 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);
@@ -3680,7 +3632,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
{
@@ -3837,18 +3789,18 @@ 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();
IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
- // 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.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
+ if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
+ 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;
@@ -3856,7 +3808,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])
@@ -3868,13 +3820,16 @@ 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)
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)
@@ -3945,6 +3900,8 @@ 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_NoBakedLines))
+ g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
if (g.Style.AntiAliasedFill)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
@@ -3974,6 +3931,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)
@@ -4082,7 +4040,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);
@@ -4126,8 +4084,10 @@ void ImGui::Initialize(ImGuiContext* context)
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window");
+ ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
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);
}
@@ -4156,7 +4116,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
@@ -4195,9 +4154,13 @@ void ImGui::Shutdown(ImGuiContext* context)
SetCurrentContext(backup_context);
// Shutdown extensions
- IM_ASSERT(g.DockContext != NULL);
DockContextShutdown(&g);
+ // 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]);
@@ -4277,18 +4240,12 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im
static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* draw_list)
{
- if (draw_list->CmdBuffer.empty())
+ // 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& last_cmd = draw_list->CmdBuffer.back();
- if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
- {
- draw_list->CmdBuffer.pop_back();
- if (draw_list->CmdBuffer.empty())
- 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);
@@ -4357,6 +4314,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;
@@ -4364,7 +4328,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++)
@@ -4374,7 +4338,12 @@ static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVectorViewport)
continue;
- if (g.NavWindowingList && viewport == g.NavWindowingList->Viewport)
+ if (g.NavWindowingListWindow && viewport == g.NavWindowingListWindow->Viewport)
continue;
if (g.NavWindowingTargetAnim && viewport == g.NavWindowingTargetAnim->Viewport)
continue;
@@ -4421,14 +4390,17 @@ 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();
// Docking: draw modal whitening background on other nodes of a same dock tree
+ // For CTRL+TAB within a docking node we need to render the dimming background in 8 steps
+ // (Because the root node renders the background in one shot, in order to avoid flickering when a child dock node is not submitted)
if (window->RootWindowDockStop->DockIsActive)
if (window->RootWindow != window->RootWindowDockStop)
RenderRectFilledWithHole(draw_list, window->RootWindow->Rect(), window->RootWindowDockStop->Rect(), GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio), g.Style.WindowRounding);
@@ -4478,9 +4450,8 @@ void ImGui::EndFrame()
// Draw modal whitening background on _other_ viewports than the one the modal is one
EndFrameDrawDimmedBackgrounds();
- // Show CTRL+TAB list window
- if (g.NavWindowingTarget != NULL)
- NavUpdateWindowingOverlay();
+ // Update navigation: CTRL+Tab, wrap-around requests
+ NavEndFrame();
SetCurrentViewport(NULL, NULL);
@@ -4494,7 +4465,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("...");
@@ -4512,7 +4483,7 @@ void ImGui::EndFrame()
UpdateViewportsEndFrame();
// 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++)
@@ -4559,7 +4530,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];
@@ -4631,7 +4602,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()
@@ -4670,12 +4641,13 @@ 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)
{
- // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
- ImRect hole_bb((float)(window->HitTestHoleOffset.x), (float)(window->HitTestHoleOffset.y),
- (float)(window->HitTestHoleOffset.x + window->HitTestHoleSize.x), (float)(window->HitTestHoleOffset.y + window->HitTestHoleSize.y));
- if (hole_bb.Contains(g.IO.MousePos - window->Pos))
+ 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;
}
@@ -4823,6 +4795,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)
{
@@ -4853,7 +4826,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;
}
@@ -5055,7 +5028,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|ImGuiWindowFlags_NoDocking;
+ flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
@@ -5095,7 +5068,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;
@@ -5145,7 +5118,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
{
@@ -5196,7 +5169,24 @@ 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)
+{
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
+ window->ViewportPos = main_viewport->Pos;
+ if (settings->ViewportId)
+ {
+ window->ViewportId = settings->ViewportId;
+ window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
+ }
+ window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.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;
+ window->DockId = settings->DockId;
+ window->DockOrder = settings->DockOrder;
+}
+
+static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
@@ -5209,6 +5199,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
// 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))
@@ -5217,23 +5208,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);
- if (settings->ViewportId)
- {
- window->ViewportId = settings->ViewportId;
- window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
- }
- else
- {
- window->ViewportPos = main_viewport->Pos;
- }
- window->Pos = ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y);
- window->Collapsed = settings->Collapsed;
- if (settings->Size.x > 0 && settings->Size.y > 0)
- size = ImVec2(settings->Size.x, settings->Size.y);
- window->DockId = settings->DockId;
- window->DockOrder = settings->DockOrder;
- }
- window->Size = window->SizeFull = ImFloor(size);
+ ApplyWindowSettings(window, settings);
+ }
window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
@@ -5398,20 +5374,35 @@ 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
+{
+ 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();
- 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 (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
IM_ASSERT(0);
return ImRect();
}
@@ -5429,7 +5420,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;
@@ -5453,9 +5444,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;
@@ -5490,6 +5482,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.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);
}
if (resize_grip_n == 0 || held || hovered)
@@ -5515,12 +5510,13 @@ 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 ? 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);
}
}
PopID();
- if (clip_with_viewport_rect)
- PopClipRect();
// Restore nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
@@ -5538,6 +5534,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 = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
@@ -5562,11 +5559,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& visibility_rect)
{
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, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
@@ -5580,23 +5579,10 @@ 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);
- 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) && !window->DockIsActive)
@@ -5857,10 +5843,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)
@@ -6010,8 +5993,9 @@ 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();
// Restore buffer capacity when woken from a compacted state, to avoid
if (window->MemoryCompacted)
@@ -6022,7 +6006,7 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
bool window_title_visible_elsewhere = false;
if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
window_title_visible_elsewhere = true;
- else if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
+ else 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)
{
@@ -6156,7 +6140,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;
}
@@ -6228,7 +6212,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;
@@ -6258,20 +6243,27 @@ 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;
}
+ // 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)
{
@@ -6283,18 +6275,25 @@ 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);
}
}
}
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.
if (window->ViewportOwned || window->DockIsActive)
window->WindowRounding = 0.0f;
else
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))
@@ -6314,7 +6313,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;
@@ -6408,19 +6407,20 @@ 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
// Setup draw list and outer clipping rectangle
- window->DrawList->Clear();
+ 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);
// Draw modal or window list full viewport dimming background (for other viewports we'll render them in EndFrame)
+ ImGuiWindow* window_window_list = g.NavWindowingListWindow;
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
- const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && ((window == g.NavWindowingTargetAnim->RootWindow) || (g.NavWindowingList && (window == g.NavWindowingList) && g.NavWindowingList->Viewport != g.NavWindowingTargetAnim->Viewport));
+ const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && ((window == g.NavWindowingTargetAnim->RootWindow) || (window == window_window_list && window_window_list->Viewport != g.NavWindowingTargetAnim->Viewport));
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
@@ -6489,6 +6489,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.
@@ -6598,17 +6599,9 @@ 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.
if (window->DockIsActive)
- {
- window->DC.LastItemId = window->ID;
- window->DC.LastItemStatusFlags = window->DockTabItemStatusFlags;
- window->DC.LastItemRect = window->DockTabItemRect;
- }
+ SetLastItemData(window, window->ID, window->DockTabItemStatusFlags, window->DockTabItemRect);
else
- {
- 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))
@@ -6737,7 +6730,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)
@@ -6783,24 +6776,29 @@ void ImGui::FocusWindow(ImGuiWindow* window)
// Close popups if any
ClosePopupsOverWindow(window, false);
+ // Move the root window to the top of the pile
+ IM_ASSERT(window == NULL || window->RootWindow != NULL);
+ ImGuiWindow* focus_front_window = window ? window->RootWindowDockStop : NULL;
+ ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
+ 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)
+ if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
+ ClearActiveID();
+
// Passing NULL allow to disable keyboard focus
if (!window)
return;
window->LastFrameJustFocused = g.FrameCount;
// Select in dock node
- if (window->DockNode && window->DockNode->TabBar)
- window->DockNode->TabBar->SelectedTabId = window->DockNode->TabBar->NextSelectedTabId = window->ID;
-
- // Move the root window to the top of the pile
- IM_ASSERT(window->RootWindow != NULL);
- ImGuiWindow* focus_front_window = window->RootWindowDockStop;
- ImGuiWindow* display_front_window = window->RootWindow;
-
- // 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 (dock_node && dock_node->TabBar)
+ dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->ID;
// Bring to front
BringWindowToFocusFront(focus_front_window);
@@ -6849,6 +6847,7 @@ void ImGui::SetCurrentFont(ImFont* font)
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
+ g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
@@ -7011,7 +7010,7 @@ bool ImGui::IsWindowDocked()
}
// 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)
{
@@ -7128,7 +7127,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);
@@ -7302,6 +7301,7 @@ ImVec2 ImGui::GetFontTexUvWhitePixel()
void ImGui::SetWindowFontScale(float scale)
{
+ IM_ASSERT(scale > 0.0f);
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
@@ -7314,6 +7314,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;
@@ -7540,9 +7541,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);
}
}
@@ -7552,7 +7552,8 @@ 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()
+ // 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);
@@ -7706,6 +7707,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;
@@ -7854,10 +7856,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;
@@ -8073,30 +8075,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));
@@ -8120,7 +8112,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)
@@ -8128,7 +8120,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;
}
@@ -8189,10 +8181,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;
@@ -8200,10 +8192,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;
}
@@ -8220,15 +8210,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.
@@ -8236,9 +8245,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);
}
//-----------------------------------------------------------------------------
@@ -8278,7 +8294,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_NoDocking;
+ ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
Begin(window_name, NULL, flags | extra_flags);
}
@@ -8307,43 +8323,77 @@ void ImGui::SetTooltip(const char* fmt, ...)
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
-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;
+ 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;
+ }
+ }
}
-bool ImGui::IsPopupOpen(const char* str_id)
+bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
- return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
+ 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()
{
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;
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;
- int current_stack_size = g.BeginPopupStack.Size;
+ 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;
@@ -8370,8 +8420,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().
@@ -8381,13 +8431,14 @@ void ImGui::OpenPopupEx(ImGuiID id)
}
}
+// 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.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.
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
@@ -8402,13 +8453,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;
}
}
@@ -8424,6 +8482,8 @@ void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_
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
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
@@ -8475,10 +8535,11 @@ void ImGui::CloseCurrentPopup()
window->DC.NavHideHighlightOneFrame = true;
}
+// Attention! BeginPopup() adds default flags which BeginPopupEx()!
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;
@@ -8517,21 +8578,22 @@ 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;
}
- // 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)
{
@@ -8551,9 +8613,10 @@ 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 layed out
+ // Child-popups don't need to be laid out
IM_ASSERT(g.WithinEndChild == false);
if (window->Flags & ImGuiWindowFlags_ChildWindow)
g.WithinEndChild = true;
@@ -8561,53 +8624,63 @@ void ImGui::EndPopup()
g.WithinEndChild = false;
}
-bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiMouseButton mouse_button)
+// 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;
+ 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;
}
// 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.
-bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiMouseButton mouse_button)
+// - 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.
+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);
- return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ 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 = GImGui->CurrentWindow->GetID(str_id);
+ 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);
- return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ 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 = GImGui->CurrentWindow->GetID(str_id);
+ ImGuiID id = window->GetID(str_id);
+ int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
- OpenPopupEx(id);
- return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
+ if (GetTopMostPopupModal() == NULL)
+ OpenPopupEx(id, popup_flags);
+ 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.)
@@ -8843,7 +8916,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)
@@ -8884,7 +8957,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.
@@ -8898,7 +8971,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;
@@ -8974,7 +9047,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
@@ -9047,36 +9120,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).
@@ -9211,6 +9259,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
@@ -9437,7 +9487,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));
@@ -9459,7 +9509,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;
@@ -9471,8 +9521,8 @@ 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);
- g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : 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) : ImRect(0, 0, 0, 0);
g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x);
g.NavScoringRect.Max.x = g.NavScoringRect.Min.x;
@@ -9624,10 +9674,72 @@ 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;
- 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;
@@ -9751,10 +9863,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);
}
}
@@ -9831,8 +9944,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");
ImGuiViewportP* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ (ImGuiViewportP*)GetMainViewport();
SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(viewport->Pos + viewport->Size * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
@@ -9852,6 +9965,7 @@ void ImGui::NavUpdateWindowingOverlay()
PopStyleVar();
}
+
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
@@ -10041,7 +10155,8 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
return false;
ImGuiWindow* window = g.CurrentWindow;
- if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->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))
@@ -10069,7 +10184,8 @@ bool ImGui::BeginDragDropTarget()
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
- if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->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;
@@ -10122,7 +10238,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();
}
@@ -10368,6 +10484,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()
@@ -10450,16 +10579,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;
@@ -10470,21 +10589,48 @@ ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
return NULL;
}
+void ImGui::ClearIniSettings()
+{
+ ImGuiContext& g = *GImGui;
+ g.SettingsIniData.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)
+{
+ 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)
{
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..
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;
+
+ // 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;
@@ -10522,9 +10668,15 @@ 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;
- DockContextOnLoadSettings(&g);
+
+ // [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)
@@ -10560,11 +10712,21 @@ 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();
+}
+
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;
}
@@ -10574,14 +10736,27 @@ static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*,
int x, y;
int i;
ImU32 u1;
- 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, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
- else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2) { settings->ViewportPos = ImVec2ih((short)x, (short)y); }
- else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
- else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
- else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
- else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
+ 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, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
+ else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
+ else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
+ else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
+ else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
+ else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
+}
+
+// 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)
@@ -11488,8 +11663,6 @@ void ImGui::DestroyPlatformWindows()
// - ImGuiDockContext
//-----------------------------------------------------------------------------
-static float IMGUI_DOCK_SPLITTER_SIZE = 2.0f;
-
enum ImGuiDockRequestType
{
ImGuiDockRequestType_None = 0,
@@ -11533,7 +11706,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)
@@ -11552,15 +11725,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
//-----------------------------------------------------------------------------
@@ -11577,7 +11741,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
@@ -11605,7 +11768,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
@@ -11613,13 +11775,15 @@ 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
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);
static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
@@ -11637,7 +11801,6 @@ namespace ImGui
//-----------------------------------------------------------------------------
// - DockContextInitialize()
// - DockContextShutdown()
-// - DockContextOnLoadSettings()
// - DockContextClearNodes()
// - DockContextRebuildNodes()
// - DockContextUpdateUndocking()
@@ -11656,54 +11819,46 @@ 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;
ini_handler.TypeName = "Docking";
ini_handler.TypeHash = ImHashStr("Docking");
+ 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);
}
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::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)
+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);
}
-// 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");
- 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);
}
@@ -11711,7 +11866,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)
@@ -11755,10 +11910,20 @@ 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;
+ // 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->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
for (int n = 0; n < dc->Requests.Size; n++)
if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
@@ -11775,7 +11940,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)
@@ -11799,14 +11964,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);
@@ -11853,16 +12018,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)
@@ -11871,9 +12036,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)
@@ -11893,9 +12058,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;
@@ -11987,7 +12152,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)
@@ -11995,7 +12160,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)
@@ -12003,12 +12168,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;
@@ -12610,11 +12775,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.
@@ -13131,7 +13295,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;
}
}
@@ -13390,22 +13554,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);
@@ -13529,7 +13698,7 @@ static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDock
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);
+ TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload->Name, 0, 0, false);
if (!tab_bar_rect.Contains(tab_bb))
overlay_draw_lists[overlay_n]->PopClipRect();
}
@@ -13596,7 +13765,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;
@@ -13653,12 +13822,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);
}
}
@@ -13684,7 +13853,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);
@@ -13694,22 +13863,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->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)
+ else if (child_1->WantLockSizeOnce && !child_0->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);
}
+ 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)
@@ -13729,8 +13903,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)
@@ -13773,7 +13950,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);
@@ -13874,13 +14053,12 @@ 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 = 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);
@@ -13889,20 +14067,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;
}
@@ -14020,6 +14189,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);
@@ -14035,10 +14205,22 @@ 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;
End();
+ ItemSize(size);
g.WithinEndChild = false;
}
@@ -14154,10 +14336,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);
@@ -14165,10 +14352,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.
@@ -14188,10 +14372,11 @@ 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;
- ImGuiDockContext* dc = ctx->DockContext;
+ ImGuiDockContext* dc = &ctx->DockContext;
ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
if (root_id && root_node == NULL)
@@ -14255,12 +14440,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))
{
@@ -14283,8 +14468,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);
}
}
@@ -14693,6 +14878,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;
@@ -14709,14 +14895,27 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
{
// Select target node
+ // (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;
- bool allow_null_target_node = false;
if (window->DockNodeAsHost)
- node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
- else if (window->DockNode) // && window->DockIsActive)
- node = window->DockNode;
+ {
+ // 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.
+ // 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
- allow_null_target_node = true; // Dock into a regular window
+ {
+ if (window->DockNode)
+ node = window->DockNode;
+ else
+ 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()));
const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
@@ -14724,7 +14923,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;
@@ -14758,6 +14957,7 @@ void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
// - DockSettingsRenameNodeReferences()
// - DockSettingsRemoveNodeReferences()
// - DockSettingsFindNodeSettings()
+// - DockSettingsHandler_ApplyAll()
// - DockSettingsHandler_ReadOpen()
// - DockSettingsHandler_ReadLine()
// - DockSettingsHandler_DockNodeToSettings()
@@ -14801,13 +15001,32 @@ 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->NodesSettings.clear();
+ DockContextClearNodes(ctx, 0, true);
+}
+
+// Recreate nodes based on settings data
+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->NodesSettings.Data, dc->NodesSettings.Size);
+ DockContextBuildAddWindowsToNodes(ctx, 0);
+}
+
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
if (strcmp(name, "Data") != 0)
@@ -14850,11 +15069,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)
@@ -14871,7 +15089,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])
@@ -14881,29 +15099,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)
@@ -15178,8 +15396,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;
@@ -15225,10 +15443,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
@@ -15257,13 +15474,14 @@ 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);
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;
}
@@ -15290,12 +15508,12 @@ 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)",
- pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId,
+ 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);
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;
@@ -15314,14 +15532,14 @@ 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.
+ 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++)
{
@@ -15359,7 +15577,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");
@@ -15375,14 +15594,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.");
@@ -15422,6 +15645,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 NodeViewport(ImGuiViewportP* viewport)
{
ImGui::SetNextItemOpen(true, ImGuiCond_Once);
@@ -15448,11 +15677,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);
@@ -15462,12 +15697,18 @@ 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" : "",
+ is_alive ? " IsAlive" : "", is_active ? " 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);
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);
@@ -15492,7 +15733,8 @@ 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*");
if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
{
p += ImFormatString(p, buf_end - p, " { ");
@@ -15500,7 +15742,10 @@ void ImGui::ShowMetricsWindow(bool* p_open)
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) ? " ... }" : " } ");
}
- 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++)
{
@@ -15528,7 +15773,6 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
};
-
// Tools
if (ImGui::TreeNode("Tools"))
{
@@ -15617,44 +15861,78 @@ 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
- if (ImGui::TreeNode("Docking"))
+ if (ImGui::TreeNode("Dock nodes"))
{
- ImGuiDockContext* dc = g.DockContext;
+ 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 (!root_nodes_only || node->IsRootNode())
+ Funcs::NodeDockNode(node, "Node");
+ ImGui::TreePop();
+ }
+#endif // #ifdef IMGUI_HAS_DOCK
- if (ImGui::TreeNode("Dock nodes"))
+ // 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 (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))
{
- 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");
+ for (int n = 0; n < g.SettingsHandlers.Size; n++)
+ ImGui::BulletText("%s", 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("Settings"))
+#ifdef IMGUI_HAS_TABLE
+ if (ImGui::TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
{
- if (ImGui::SmallButton("Refresh"))
- SaveIniSettingsToMemory();
- ImGui::SameLine();
- if (ImGui::SmallButton("Save to disk"))
- SaveIniSettingsToDisk(g.IO.IniFilename);
- ImGui::Separator();
- ImGui::Text("Docked Windows:");
+ for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
+ Funcs::NodeTableSettings(settings);
+ ImGui::TreePop();
+ }
+#endif // #ifdef IMGUI_HAS_TABLE
+
+#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::Separator();
- ImGui::Text("Dock Nodes:");
- for (int n = 0; n < dc->SettingsNodes.Size; n++)
+ ImGui::Text("In SettingsNodes:");
+ for (int n = 0; n < dc->NodesSettings.Size; n++)
{
- ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n];
+ ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
const char* selected_tab_name = NULL;
if (settings->SelectedWindowId)
{
@@ -15667,30 +15945,51 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
ImGui::TreePop();
}
+#endif // #ifdef IMGUI_HAS_DOCK
+
+ 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::TreePop();
+ }
ImGui::TreePop();
}
-#endif // #define IMGUI_HAS_DOCK
// Misc Details
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("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();
+
+ 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::Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
+ ImGui::Unindent();
+
ImGui::TreePop();
}
@@ -15728,34 +16027,27 @@ 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)
- {
- for (int n = 0; n < g.DockContext->Nodes.Data.Size; n++)
- if (ImGuiDockNode* node = (ImGuiDockNode*)g.DockContext->Nodes.Data[n].val_p)
- {
- ImGuiDockNode* root_node = DockNodeGetRootNode(node);
- if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(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 // #define IMGUI_HAS_DOCK
+#endif // #ifdef IMGUI_HAS_DOCK
ImGui::End();
}
diff --git a/imgui.h b/imgui.h
index c939a529..796c5ef9 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,10 +1,10 @@
-// dear imgui, v1.77 WIP
+// dear imgui, v1.79 WIP
// (headers)
// 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:
@@ -60,8 +60,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 17601
+#define IMGUI_VERSION "1.79 WIP"
+#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 IMGUI_HAS_VIEWPORT 1 // Viewport WIP branch
#define IMGUI_HAS_DOCK 1 // Docking WIP branch
@@ -88,8 +88,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
@@ -158,8 +158,9 @@ 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 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()
@@ -169,7 +170,9 @@ 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 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()
@@ -181,7 +184,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
@@ -277,9 +280,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,
@@ -294,8 +298,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
@@ -313,7 +317,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()
@@ -322,7 +326,7 @@ namespace ImGui
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 SetNextWindowViewport(ImGuiID viewport_id); // set next window viewport
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().
@@ -342,8 +346,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.
@@ -383,7 +387,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.
@@ -445,18 +449,18 @@ 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 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
+ 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 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 ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1, 0), const char* overlay = NULL);
+ IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
// 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.
@@ -467,50 +471,56 @@ 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.
+ // - 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.
- // - 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);
- 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);
-
- // 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.
- 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);
+ // - 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.
+ 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.
// - 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);
@@ -531,7 +541,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
@@ -557,14 +567,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!
@@ -602,24 +612,41 @@ 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. (*)
- // - 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().
- // - 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.
- 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 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 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.
+ // - 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. 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).
+ // - 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.
+ // - 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.
+ // - 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.
@@ -669,6 +696,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!
@@ -750,7 +778,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?
@@ -870,6 +898,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
@@ -897,6 +926,27 @@ enum ImGuiTreeNodeFlags_
ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog
};
+// 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.
+// - 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_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
+};
+
// Flags for ImGui::Selectable()
enum ImGuiSelectableFlags_
{
@@ -945,7 +995,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()
@@ -1256,6 +1307,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_
{
@@ -1288,13 +1352,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
@@ -1302,6 +1366,18 @@ enum ImGuiColorEditFlags_
#endif
};
+// 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_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_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.
// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience.
enum ImGuiMouseButton_
@@ -1339,8 +1415,9 @@ 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_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed)
+ 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)
};
@@ -1349,16 +1426,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); } }
//-----------------------------------------------------------------------------
@@ -1408,7 +1485,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
@@ -1418,10 +1495,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; }
@@ -1441,7 +1518,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.
@@ -1462,16 +1539,19 @@ 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.
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 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). We apply per-monitor DPI scaling over this scale. 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. 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];
@@ -1564,8 +1644,8 @@ 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.)
- 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.
+ 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.
ImGuiID MouseHoveredViewport; // (Optional) When using multiple viewports: viewport the OS mouse cursor is hovering _IGNORING_ viewports with the ImGuiViewportFlags_NoInputs flag, and _REGARDLESS_ of whether another viewport is focused. Set io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport if you can provide this info. If you don't imgui will infer the value using the rectangles and last focused time of the viewports it knows about (ignoring other OS windows).
@@ -1624,6 +1704,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.
@@ -1637,9 +1718,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
@@ -1666,7 +1748,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().
@@ -1683,7 +1767,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
@@ -1693,9 +1777,9 @@ 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.
+ 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; }
};
@@ -1711,7 +1795,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.
@@ -1730,6 +1814,23 @@ struct ImGuiPayload
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
namespace ImGui
{
+ // 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 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); }
+ 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);
+ 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)); }
// OBSOLETED in 1.72 (from July 2019)
static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); }
// OBSOLETED in 1.71 (from June 2019)
@@ -1750,7 +1851,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;
@@ -1886,7 +1986,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
{
@@ -1937,8 +2037,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); }
@@ -1946,7 +2046,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); }
};
//-----------------------------------------------------------------------------
@@ -1954,6 +2054,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_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]
// 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:
@@ -1972,19 +2077,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; // 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.
-
- ImDrawCmd() { ElemCount = 0; TextureId = (ImTextureID)NULL; VtxOffset = IdxOffset = 0; UserCallback = NULL; UserCallbackData = NULL; }
+ 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. 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() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed
};
// Vertex index, default to 16-bit
@@ -2048,12 +2155,15 @@ enum ImDrawCornerFlags_
ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience
};
+// 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, // 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_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.
};
// Draw command list
@@ -2075,18 +2185,19 @@ 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
- ImDrawListSplitter _Splitter; // [Internal] for channels api
+ 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; _OwnerName = NULL; Clear(); }
- ~ImDrawList() { ClearFreeMemory(); }
+ 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)
IMGUI_API void PushClipRectFullScreen();
IMGUI_API void PopClipRect();
@@ -2098,6 +2209,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);
@@ -2108,8 +2220,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);
@@ -2129,7 +2241,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);
@@ -2146,26 +2258,31 @@ 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
- // NB: all primitives needs to be reserved via PrimReserve() beforehand!
- IMGUI_API void Clear();
- IMGUI_API void ClearFreeMemory();
+ // 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); }
- IMGUI_API void UpdateClipRect();
- IMGUI_API void UpdateTextureID();
+ 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 _OnChangedClipRect();
+ IMGUI_API void _OnChangedTextureID();
+ IMGUI_API void _OnChangedVtxOffset();
};
// All draw data to render a Dear ImGui frame
@@ -2252,21 +2369,23 @@ 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; }
};
+// 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)
+ 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:
@@ -2336,10 +2455,11 @@ 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.
- 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.
- const ImFontAtlasCustomRect*GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
+ // Read docs/FONTS.md for more details about using colorful icons.
+ // Note: this API may be redesigned later in order to support multi-monitor varying DPI settings.
+ IMGUI_API int AddCustomRectRegular(int width, int height);
+ IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0));
+ ImFontAtlasCustomRect* GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; }
// [Internal]
IMGUI_API void CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const;
@@ -2365,8 +2485,12 @@ 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
+ 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 PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+
@@ -2399,7 +2523,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();
@@ -2421,7 +2545,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);
@@ -2546,7 +2670,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; }
};
@@ -2597,7 +2721,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 ef33ffba..07902c10 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,41 +1,42 @@
-// dear imgui, v1.77 WIP
+// dear imgui, v1.79 WIP
// (demo code)
// 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.
/*
@@ -79,41 +80,44 @@ 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 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.
-#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 //
+#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: 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
#define IM_NEWLINE "\n"
#endif
+// Helpers
#if defined(_MSC_VER) && !defined(snprintf)
#define snprintf _snprintf
#endif
@@ -121,6 +125,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
//-----------------------------------------------------------------------------
@@ -144,7 +156,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("(?)");
@@ -173,7 +185,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)
@@ -208,7 +222,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();
@@ -216,15 +231,19 @@ 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_main_menu_bar = false;
static bool show_app_dockspace = 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;
@@ -239,6 +258,7 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (show_app_main_menu_bar) ShowExampleAppMainMenuBar();
if (show_app_dockspace) ShowExampleAppDockSpace(&show_app_dockspace); // Process the Docking app first, as explicit DockSpace() nodes needs to be submitted early (read comments near the DockSpace function)
if (show_app_documents) ShowExampleAppDocuments(&show_app_documents); // Process the Document app next, as it may also use a DockSpace()
+
if (show_app_console) ShowExampleAppConsole(&show_app_console);
if (show_app_log) ShowExampleAppLog(&show_app_log);
if (show_app_layout) ShowExampleAppLayout(&show_app_layout);
@@ -255,9 +275,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;
@@ -285,7 +310,8 @@ void ImGui::ShowDemoWindow(bool* p_open)
if (no_docking) window_flags |= ImGuiWindowFlags_NoDocking;
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.
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(ImVec2(main_viewport->GetWorkPos().x + 650, main_viewport->GetWorkPos().y + 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver);
@@ -298,9 +324,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())
@@ -368,13 +398,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::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)
{
@@ -384,7 +416,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::CheckboxFlags("io.ConfigFlags: DockingEnable", (unsigned int *)&io.ConfigFlags, ImGuiConfigFlags_DockingEnable);
@@ -425,22 +457,26 @@ 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::Text("Also see Style->Rendering for rendering options.");
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);
- ImGui::CheckboxFlags("io.BackendFlags: PlatformHasViewports", (unsigned int *)&backend_flags, ImGuiBackendFlags_PlatformHasViewports);
- ImGui::CheckboxFlags("io.BackendFlags: HasMouseHoveredViewport", (unsigned int *)&backend_flags, ImGuiBackendFlags_HasMouseHoveredViewport);
- ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset);
- ImGui::CheckboxFlags("io.BackendFlags: RendererHasViewports", (unsigned int *)&backend_flags, ImGuiBackendFlags_RendererHasViewports);
+ 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: PlatformHasViewports", (unsigned int*)&backend_flags, ImGuiBackendFlags_PlatformHasViewports);
+ ImGui::CheckboxFlags("io.BackendFlags: HasMouseHoveredViewport",(unsigned int*)&backend_flags, ImGuiBackendFlags_HasMouseHoveredViewport);
+ ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int*)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset);
+ ImGui::CheckboxFlags("io.BackendFlags: RendererHasViewports", (unsigned int*)&backend_flags, ImGuiBackendFlags_RendererHasViewports);
ImGui::TreePop();
ImGui::Separator();
}
@@ -455,10 +491,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();
@@ -525,15 +564,17 @@ 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();
}
- // 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();
@@ -571,7 +612,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");
@@ -582,14 +623,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");
@@ -599,7 +654,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);
@@ -608,23 +665,26 @@ 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%%");
- 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);
+ ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic);
static float angle = 0.0f;
ImGui::SliderAngle("slider angle", &angle);
@@ -633,27 +693,31 @@ 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.");
}
{
- 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.\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);
@@ -675,8 +739,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);
@@ -693,25 +757,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 layed 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)
@@ -737,8 +807,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())
@@ -753,10 +823,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)
@@ -808,8 +879,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();
@@ -824,21 +895,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();
}
@@ -846,14 +920,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.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. 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.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";
@@ -869,41 +948,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();
@@ -924,19 +1025,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();
}
@@ -960,9 +1065,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 };
@@ -1006,7 +1113,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");
@@ -1028,13 +1136,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 };
- 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, 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; }
@@ -1049,8 +1161,11 @@ 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");
- 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++)
@@ -1060,7 +1175,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();
}
}
@@ -1100,15 +1215,28 @@ 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::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");
@@ -1117,12 +1245,70 @@ 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,
- // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper using your prefered 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)
@@ -1131,14 +1317,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 typicall 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);
@@ -1147,7 +1333,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);
@@ -1160,7 +1347,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;
@@ -1169,20 +1357,21 @@ 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
- // 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.
+ // 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] = {};
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 data at fixed 60 Hz rate for the demo
{
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
@@ -1194,12 +1383,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); }
@@ -1212,8 +1402,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
@@ -1227,20 +1417,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 = (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);
+ 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;
@@ -1255,7 +1445,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:");
@@ -1265,19 +1457,23 @@ 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:");
- // 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)
{
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;
@@ -1301,9 +1497,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");
@@ -1312,11 +1508,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))
@@ -1335,14 +1533,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);
@@ -1359,7 +1557,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;
@@ -1374,22 +1575,62 @@ 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();
+ }
+
+ if (ImGui::TreeNode("Drag/Slider Flags"))
+ {
+ // 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("ImGuiSliderFlags_Logarithmic", (unsigned int*)&flags, ImGuiSliderFlags_Logarithmic);
+ ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values).");
+ 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("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", 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", flags);
+ ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags);
ImGui::TreePop();
}
@@ -1398,27 +1639,31 @@ 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 %%", 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();
}
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;
@@ -1459,34 +1704,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", 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", ImGuiSliderFlags_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", 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", ImGuiSliderFlags_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");
@@ -1544,7 +1789,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 };
@@ -1553,11 +1798,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);
@@ -1576,7 +1821,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]);
@@ -1593,7 +1838,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();
}
@@ -1607,8 +1852,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 };
@@ -1629,19 +1875,28 @@ 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" };
+ static 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);
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))
{
- 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();
@@ -1678,7 +1933,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++)
{
@@ -1704,11 +1961,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 };
@@ -1727,10 +1991,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"
@@ -1773,7 +2037,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.
@@ -1815,11 +2079,11 @@ 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 (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.
// This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties).
static bool test_window = false;
ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window);
@@ -1846,7 +2110,7 @@ static void ShowDemoWindowWidgets()
static void ShowDemoWindowLayout()
{
- if (!ImGui::CollapsingHeader("Layout"))
+ if (!ImGui::CollapsingHeader("Layout & Scrolling"))
return;
if (ImGui::TreeNode("Child windows"))
@@ -1857,24 +2121,14 @@ 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 | (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++)
- {
ImGui::Text("%04d: scrollable region", i);
- if (goto_line && line == i)
- ImGui::SetScrollHereY();
- }
- if (goto_line && line >= 100)
- ImGui::SetScrollHereY();
ImGui::EndChild();
}
@@ -1882,7 +2136,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())
@@ -1910,20 +2168,27 @@ 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);
+ 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);
}
@@ -1934,6 +2199,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.");
@@ -1955,7 +2223,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);
@@ -2036,7 +2305,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;
@@ -2107,7 +2377,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++)
@@ -2128,7 +2399,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();
@@ -2151,9 +2425,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();
@@ -2174,8 +2448,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();
@@ -2183,7 +2458,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();
@@ -2235,7 +2511,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));
@@ -2248,12 +2524,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"))
+ {
+ // Placeholder tree data
+ for (int i = 0; i < 6; i++)
+ ImGui::BulletText("Item %d..", i);
+ ImGui::TreePop();
+ }
+
+ // 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();
- 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.
+ // 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)
+ {
+ // Placeholder tree data
+ for (int i = 0; i < 6; i++)
+ ImGui::BulletText("Item %d..", i);
+ ImGui::TreePop();
+ }
// Bullet
ImGui::Button("Button##3");
@@ -2281,8 +2574,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);
@@ -2310,8 +2601,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");
@@ -2321,7 +2613,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++)
{
@@ -2346,18 +2638,23 @@ 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"
+ "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++)
{
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++)
{
@@ -2384,16 +2681,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++)
{
@@ -2401,8 +2703,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));
@@ -2416,13 +2718,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();
}
@@ -2511,7 +2821,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();
@@ -2522,16 +2832,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("##dummy", size);
- 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::TextWrapped("(Click and drag to scroll)");
+
+ for (int n = 0; n < 3; n++)
+ {
+ 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::TreePop();
}
}
@@ -2544,10 +2904,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();
@@ -2559,14 +2921,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();
@@ -2637,10 +3001,11 @@ 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 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"))
@@ -2652,16 +3017,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 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 (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())
{
@@ -2678,18 +3046,25 @@ 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?");
+ // Always center this window when appearing
+ 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))
{
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));
@@ -2711,7 +3086,7 @@ static void ShowDemoWindowPopups()
{
if (ImGui::BeginMenu("File"))
{
- if (ImGui::MenuItem("Dummy menu item")) {}
+ if (ImGui::MenuItem("Some menu item")) {}
ImGui::EndMenu();
}
ImGui::EndMenuBar();
@@ -2720,17 +3095,18 @@ 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);
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.
- bool dummy_open = true;
- if (ImGui::BeginPopupModal("Stacked 2", &dummy_open))
+ // 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 unused_open = true;
+ if (ImGui::BeginPopupModal("Stacked 2", &unused_open))
{
ImGui::Text("Hello from Stacked The Second!");
if (ImGui::Button("Close"))
@@ -2750,9 +3126,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"))
@@ -2934,7 +3313,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
@@ -3033,7 +3413,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);
@@ -3043,9 +3423,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())
@@ -3061,13 +3441,13 @@ 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));
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();
@@ -3117,19 +3497,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();
}
@@ -3138,9 +3526,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];
@@ -3179,11 +3571,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);
@@ -3321,7 +3714,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;
@@ -3360,13 +3754,103 @@ 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().");
}
+// [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 and thus cannot easily generate a zero-terminated UTF-8 encoded string.
+ ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
+ ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
+ const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
+ draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
+ if (glyph)
+ 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)
+ // 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;
@@ -3384,14 +3868,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"))
@@ -3400,7 +3884,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();
@@ -3430,6 +3916,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");
@@ -3437,9 +3924,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();
}
@@ -3460,7 +3950,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();
}
@@ -3471,10 +3962,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);
@@ -3487,10 +3981,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.
- // 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];
+ // Tips: in a real user application, you may want to merge and use an icon font into the main font,
+ // so instead of "Save"/"Revert" you'd use icons!
+ // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient!
+ ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; }
+ ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; }
}
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
ImGui::TextUnformatted(name);
@@ -3506,82 +4001,13 @@ 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++)
{
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))
@@ -3592,11 +4018,19 @@ 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
+ 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, 0.3f, 2.0f, "%.2f"); // scale everything
+ ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_ClampOnInput); // Scale everything
ImGui::PopItemWidth();
ImGui::EndTabItem();
@@ -3604,12 +4038,36 @@ 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 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::Checkbox("Anti-aliased fill", &style.AntiAliasedFill);
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();
@@ -3631,7 +4089,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()
{
@@ -3656,10 +4114,11 @@ 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);
+ ImGui::MenuItem("(demo menu)", NULL, false, false);
if (ImGui::MenuItem("New")) {}
if (ImGui::MenuItem("Open", "Ctrl+O")) {}
if (ImGui::BeginMenu("Open Recent"))
@@ -3707,7 +4166,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);
@@ -3738,7 +4197,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];
@@ -3755,10 +4214,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!");
@@ -3771,10 +4232,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()
{
@@ -3797,14 +4258,15 @@ 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();
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())
{
@@ -3813,14 +4275,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("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); }
@@ -3840,26 +4304,39 @@ 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.
- ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing
+ // - 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();
for (int i = 0; i < Items.Size; i++)
@@ -3868,12 +4345,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)
@@ -3889,7 +4370,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);
@@ -3911,9 +4393,10 @@ 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--)
+ for (int i = History.Size - 1; i >= 0; i--)
if (Stricmp(History[i], command_line) == 0)
{
free(History[i]);
@@ -3944,11 +4427,12 @@ 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;
}
- 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);
@@ -3977,24 +4461,25 @@ 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));
+ // 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 (;;)
{
@@ -4012,7 +4497,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);
}
@@ -4073,8 +4558,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()
{
@@ -4127,7 +4612,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();
@@ -4141,8 +4626,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];
@@ -4155,13 +4640,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())
@@ -4198,12 +4687,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++;
}
}
@@ -4233,43 +4724,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();
}
@@ -4278,67 +4773,70 @@ static void ShowExampleAppLayout(bool* p_open)
// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()
//-----------------------------------------------------------------------------
+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.
+ 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 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)
+ {
+ ShowPlaceholderObject("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", &placeholder_members[i], 1.0f);
+ else
+ ImGui::DragFloat("##value", &placeholder_members[i], 0.01f);
+ ImGui::NextColumn();
+ }
+ ImGui::PopID();
+ }
+ ImGui::TreePop();
+ }
+ ImGui::PopID();
+}
+
// 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();
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::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)
+ // Iterate placeholder objects (all the same data)
for (int obj_i = 0; obj_i < 3; obj_i++)
- funcs::ShowDummyObject("Object", obj_i);
+ ShowPlaceholderObject("Object", obj_i);
ImGui::Columns(1);
ImGui::Separator();
@@ -4353,7 +4851,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();
@@ -4364,14 +4862,17 @@ 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();
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");
@@ -4384,7 +4885,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++)
@@ -4394,7 +4895,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();
@@ -4418,7 +4919,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
@@ -4432,12 +4936,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
{
- static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = (data->DesiredSize.x > data->DesiredSize.y ? data->DesiredSize.x : data->DesiredSize.y); }
+ // Helper functions to demonstrate programmatic constraints
+ 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); }
};
+ 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;
@@ -4452,23 +4968,13 @@ 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::IsWindowDocked())
ImGui::Text("Warning: Sizing Constraints won't work if the window is docked!");
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);
@@ -4482,7 +4988,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)
{
// FIXME-VIEWPORT: Select a default viewport
@@ -4500,7 +5007,10 @@ static void ShowExampleAppSimpleOverlay(bool* p_open)
ImGui::SetNextWindowViewport(viewport->ID);
}
ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background
- if (ImGui::Begin("Example: Simple overlay", p_open, (corner != -1 ? ImGuiWindowFlags_NoMove : 0) | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav))
+ ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking | 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();
@@ -4527,7 +5037,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.
@@ -4566,34 +5077,37 @@ 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!
- ImDrawList* draw_list = ImGui::GetWindowDrawList();
+ // 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!
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)
+ // 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 p = ImGui::GetCursorScreenPos();
- 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);
+ ImVec2 p0 = ImGui::GetCursorScreenPos();
+ ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
+ 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 p = ImGui::GetCursorScreenPos();
- 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);
+ ImVec2 p0 = ImGui::GetCursorScreenPos();
+ ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
+ 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);
}
@@ -4613,6 +5127,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;
@@ -4620,38 +5135,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();
}
@@ -4659,51 +5175,97 @@ static void ShowExampleAppCustomRendering(bool* p_open)
if (ImGui::BeginTabItem("Canvas"))
{
static ImVector points;
+ static ImVec2 scrolling(0.0f, 0.0f);
+ static bool opt_enable_grid = true;
+ static bool opt_enable_context_menu = 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 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));
-
- 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);
- if (adding_line)
+
+ 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.
+ // 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;
+ ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.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))
{
- adding_preview = true;
points.push_back(mouse_pos_in_canvas);
- if (!ImGui::IsMouseDown(0))
- adding_line = adding_preview = false;
+ points.push_back(mouse_pos_in_canvas);
+ adding_line = true;
}
- if (ImGui::IsItemHovered())
+ if (adding_line)
{
- if (!adding_line && ImGui::IsMouseClicked(0))
- {
- points.push_back(mouse_pos_in_canvas);
- adding_line = true;
- }
- if (ImGui::IsMouseClicked(1) && !points.empty())
- {
- adding_line = adding_preview = false;
- points.pop_back();
- points.pop_back();
- }
+ points.back() = mouse_pos_in_canvas;
+ if (!ImGui::IsMouseDown(ImGuiMouseButton_Left))
+ adding_line = false;
+ }
+
+ // 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)
+ 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");
+ if (ImGui::BeginPopup("context"))
+ {
+ if (adding_line)
+ points.resize(points.size() - 2);
+ adding_line = false;
+ 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();
+ }
+
+ // Draw grid + all lines in the canvas
+ draw_list->PushClipRect(canvas_p0, canvas_p1, true);
+ 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)
+ 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));
}
- 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.)
- 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);
+ 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();
- if (adding_preview)
- points.pop_back();
+
ImGui::EndTabItem();
}
@@ -4719,7 +5281,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();
@@ -4741,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,
@@ -4759,8 +5321,12 @@ 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
+ // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background
// and handle the pass-thru hole, so we ask Begin() to not render a background.
if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
window_flags |= ImGuiWindowFlags_NoBackground;
@@ -4770,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);
@@ -4791,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();
}
@@ -4832,14 +5403,14 @@ void ShowExampleAppDockSpace(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
-
- MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f,1.0f,1.0f,1.0f))
+ 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))
{
Name = name;
Open = OpenPrev = open;
@@ -4852,7 +5423,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);
@@ -4901,10 +5472,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)
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 20a8a1b2..b6c51c4e 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.77 WIP
+// dear imgui, v1.79 WIP
// (drawing and font code)
/*
@@ -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
@@ -57,22 +57,19 @@ 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 //
-#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.
+#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
+#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 "-Wcomma" // warning: possible misuse of comma operator here
+#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier
+#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 "-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 "-Wunused-function" // warning: 'xxxx' defined but not used
@@ -108,7 +105,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__)
@@ -367,6 +364,7 @@ ImDrawListSharedData::ImDrawListSharedData()
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)
@@ -382,13 +380,20 @@ 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()
{
+ // 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 ? _Data->InitialFlags : ImDrawListFlags_None;
- _VtxCurrentOffset = 0;
+ Flags = _Data->InitialFlags;
+ memset(&_CmdHeader, 0, sizeof(_CmdHeader));
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
@@ -396,13 +401,15 @@ void ImDrawList::Clear()
_TextureIdStack.resize(0);
_Path.resize(0);
_Splitter.Clear();
+ CmdBuffer.push_back(ImDrawCmd());
}
-void ImDrawList::ClearFreeMemory()
+void ImDrawList::_ClearFreeMemory()
{
CmdBuffer.clear();
IdxBuffer.clear();
VtxBuffer.clear();
+ Flags = ImDrawListFlags_None;
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
@@ -422,86 +429,117 @@ 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);
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* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL;
- if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL)
+ ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ IM_ASSERT(curr_cmd->UserCallback == NULL);
+ if (curr_cmd->ElemCount != 0)
{
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)
}
+// 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()
+void ImDrawList::_OnChangedClipRect()
{
// 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, &_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 = 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)
+ ImDrawCmd* prev_cmd = curr_cmd - 1;
+ if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL)
+ {
CmdBuffer.pop_back();
- else
- curr_cmd->ClipRect = curr_clip_rect;
+ return;
+ }
+
+ 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
- const ImTextureID curr_texture_id = GetCurrentTextureId();
- ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL;
- if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL)
+ ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
+ 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 = 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)
+ ImDrawCmd* prev_cmd = curr_cmd - 1;
+ if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL)
+ {
CmdBuffer.pop_back();
- else
- curr_cmd->TextureId = curr_texture_id;
+ return;
+ }
+
+ curr_cmd->TextureId = _CmdHeader.TextureId;
}
-#undef GetCurrentClipRect
-#undef GetCurrentTextureId
+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); // See #3349
+ 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)
{
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;
@@ -511,7 +549,8 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_
cr.w = ImMax(cr.y, cr.w);
_ClipRectStack.push_back(cr);
- UpdateClipRect();
+ _CmdHeader.ClipRect = cr;
+ _OnChangedClipRect();
}
void ImDrawList::PushClipRectFullScreen()
@@ -521,22 +560,23 @@ void ImDrawList::PushClipRectFullScreen()
void ImDrawList::PopClipRect()
{
- IM_ASSERT(_ClipRectStack.Size > 0);
_ClipRectStack.pop_back();
- UpdateClipRect();
+ _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1];
+ _OnChangedClipRect();
}
void ImDrawList::PushTextureID(ImTextureID texture_id)
{
_TextureIdStack.push_back(texture_id);
- UpdateTextureID();
+ _CmdHeader.TextureId = texture_id;
+ _OnChangedTextureID();
}
void ImDrawList::PopTextureID()
{
- IM_ASSERT(_TextureIdStack.Size > 0);
_TextureIdStack.pop_back();
- UpdateTextureID();
+ _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1];
+ _OnChangedTextureID();
}
// Reserve space for a number of vertices and indices.
@@ -548,13 +588,15 @@ 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;
- _VtxCurrentIdx = 0;
- AddDrawCmd();
+ // 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();
}
- 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);
@@ -570,8 +612,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);
}
@@ -621,7 +663,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)
@@ -633,30 +675,42 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
if (points_count < 2)
return;
- const ImVec2 uv = _Data->TexUvWhitePixel;
-
- int count = points_count;
- if (!closed)
- count = points_count-1;
+ 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);
- const bool thick_line = thickness > 1.0f;
if (Flags & ImDrawListFlags_AntiAliasedLines)
{
// Anti-aliased stroke
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;
+ // 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?
+ // - 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_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);
PrimReserve(idx_count, vtx_count);
// Temporary buffer
- ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630
+ // 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 * ((use_texture || !thick_line) ? 3 : 5) * 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;
+ 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);
@@ -664,79 +718,134 @@ 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)
+ // 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 (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.
+ // - 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
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
+ // 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 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 + (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;
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
- ImVec2* out_vtx = &temp_points[i2*2];
+ // 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
- _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_texture)
+ {
+ // 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 (int i = 0; i < points_count; i++)
+ // Add vertexes for each point on the line
+ if (use_texture)
{
- _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 += 3;
+ // 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)
+ {
+ 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++)
+ {
+ _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 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; // 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;
+ }
}
}
else
{
+ // [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
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);
}
+ // 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+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;
@@ -747,8 +856,8 @@ 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
- ImVec2* out_vtx = &temp_points[i2*4];
+ // 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;
out_vtx[1].x = points[i2].x + dm_in_x;
@@ -759,24 +868,24 @@ 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;
}
- // 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;
- _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;
}
}
@@ -784,14 +893,14 @@ 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
+ // [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);
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];
@@ -801,14 +910,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;
}
@@ -828,22 +937,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];
@@ -854,7 +963,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];
@@ -871,8 +980,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;
@@ -880,7 +989,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++)
@@ -890,7 +999,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;
@@ -957,20 +1066,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);
}
}
@@ -1030,9 +1139,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);
}
@@ -1060,8 +1169,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);
@@ -1138,7 +1247,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);
@@ -1168,7 +1277,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);
@@ -1225,9 +1334,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);
@@ -1248,7 +1357,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);
@@ -1264,7 +1373,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);
@@ -1347,27 +1456,20 @@ 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();
+ 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.
+ // 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;
@@ -1377,14 +1479,21 @@ 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 && 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();
@@ -1409,8 +1518,18 @@ 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();
+
+ // 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();
+
+ // 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;
}
@@ -1419,6 +1538,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));
@@ -1426,6 +1546,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();
}
//-----------------------------------------------------------------------------
@@ -1546,11 +1673,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;
-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] =
+// 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 "
@@ -1607,8 +1733,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 = PackIdLines = -1;
}
ImFontAtlas::~ImFontAtlas()
@@ -1636,8 +1761,7 @@ void ImFontAtlas::ClearInputData()
}
ConfigData.clear();
CustomRects.clear();
- for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++)
- CustomRectIds[n] = -1;
+ PackIdMouseCursors = PackIdLines = -1;
}
void ImFontAtlas::ClearTexData()
@@ -1738,15 +1862,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;
@@ -1813,7 +1937,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();
@@ -1832,14 +1956,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);
@@ -1848,13 +1969,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;
@@ -1877,16 +2001,15 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou
if (Flags & ImFontAtlasFlags_NoMouseCursors)
return false;
- 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);
+ 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];
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;
@@ -2101,7 +2224,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).
@@ -2168,8 +2291,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;
@@ -2183,20 +2309,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);
+ 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);
}
}
@@ -2208,17 +2327,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_ID, 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);
-}
-
void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)
{
if (!font_config->MergeMode)
@@ -2226,6 +2334,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;
@@ -2260,53 +2369,113 @@ 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)
{
- 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());
+ 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);
- 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
{
- 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);
}
+static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas)
+{
+ if (atlas->Flags & ImFontAtlasFlags_NoBakedLines)
+ return;
+
+ // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them
+ ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines);
+ IM_ASSERT(r->IsPacked());
+ for (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;
+ unsigned int line_width = n;
+ unsigned int pad_left = (r->Width - line_width) / 2;
+ unsigned int pad_right = r->Width - (pad_left + line_width);
+
+ // Write each slice
+ IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels
+ 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
+ ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale;
+ ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale;
+ float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts
+ atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v);
+ }
+}
+
+// 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 * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H);
+ else
+ atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2);
+ }
+
+ // 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 block
+ // Render into our custom data blocks
+ IM_ASSERT(atlas->TexPixelsAlpha8 != NULL);
ImFontAtlasBuildRenderDefaultTexData(atlas);
+ ImFontAtlasBuildRenderLinesTexData(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.ID >= 0x110000)
+ const ImFontAtlasCustomRect* r = &atlas->CustomRects[i];
+ if (r->Font == NULL || r->GlyphID == 0)
continue;
- IM_ASSERT(r.Font->ContainerAtlas == atlas);
+ // 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.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);
+ atlas->CalcCustomRectUV(r, &uv0, &uv1);
+ r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX);
}
// Build all fonts lookup tables
@@ -2316,7 +2485,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];
@@ -2349,7 +2518,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];
@@ -2665,7 +2834,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)
@@ -2716,8 +2885,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;
@@ -2730,14 +2920,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)
@@ -2856,7 +3045,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)
@@ -2882,7 +3071,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);
@@ -3160,7 +3349,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;
@@ -3248,10 +3437,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();
}
}
@@ -3346,8 +3535,6 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im
draw_list->PathFillConvex(col);
}
-// For CTRL+TAB within a docking node we need to render the dimming background in 8 steps
-// (Because the root node renders the background in one shot, in order to avoid flickering when a child dock node is not submitted)
void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding)
{
const bool fill_L = (inner.Min.x > outer.Min.x);
@@ -3366,7 +3553,7 @@ void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect
// 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)
{
@@ -3532,7 +3719,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= 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
@@ -83,11 +95,12 @@ 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()
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
@@ -106,7 +119,6 @@ typedef int ImGuiDataAuthority; // -> enum ImGuiDataAuthority_ // E
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()
@@ -115,12 +127,20 @@ 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()
+//-----------------------------------------------------------------------------
+// [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
@@ -130,7 +150,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"
@@ -138,20 +158,12 @@ namespace ImStb
} // namespace ImStb
//-----------------------------------------------------------------------------
-// Context pointer
+// [SECTION] Macros
//-----------------------------------------------------------------------------
-#ifndef GImGui
-extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
-#endif
-
// Internal Drag and Drop payload types. String starting with '_' are reserved for Dear ImGui.
#define IMGUI_PAYLOAD_TYPE_WINDOW "_IMWINDOW" // Payload == ImGuiWindow*
-//-----------------------------------------------------------------------------
-// Macros
-//-----------------------------------------------------------------------------
-
// Debug Logging
#ifndef IMGUI_DEBUG_LOG
#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__)
@@ -207,32 +219,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);
@@ -274,21 +304,21 @@ IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, cons
// We are keeping those disabled by default so they don't leak in user space, to allow user enabling implicit cast operators between ImVec2 and their own types (using IM_VEC2_CLASS_EXTRA etc.)
// We unfortunately don't have a unary- operator for ImVec2 because this would needs to be defined inside the class itself.
#ifdef IMGUI_DEFINE_MATH_OPERATORS
-static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); }
-static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); }
-static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); }
-static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); }
-static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); }
-static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); }
+static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); }
+static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); }
+static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); }
+static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }
+static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
+static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); }
static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; }
-static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x+rhs.x, lhs.y+rhs.y, lhs.z+rhs.z, lhs.w+rhs.w); }
-static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); }
-static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x*rhs.x, lhs.y*rhs.y, lhs.z*rhs.z, lhs.w*rhs.w); }
+static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); }
+static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); }
+static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); }
#endif
// Helpers: File System
@@ -301,7 +331,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);
@@ -329,6 +358,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)
@@ -347,9 +382,9 @@ static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t)
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }
static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 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; }
@@ -369,7 +404,62 @@ 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; }
+ ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, 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; }
@@ -446,88 +536,53 @@ struct IMGUI_API ImChunkStream
};
//-----------------------------------------------------------------------------
-// Misc data structures
+// [SECTION] ImDrawList support
//-----------------------------------------------------------------------------
-enum ImGuiButtonFlags_
-{
- 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_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold,
- ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease
-};
+// 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)
-enum ImGuiSliderFlags_
-{
- ImGuiSliderFlags_None = 0,
- ImGuiSliderFlags_Vertical = 1 << 0
-};
+// 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
-enum ImGuiDragFlags_
+// 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
{
- ImGuiDragFlags_None = 0,
- ImGuiDragFlags_Vertical = 1 << 0
-};
+ 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)
-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.
-};
+ // [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* TexUvLines; // UV of anti-aliased lines in the atlas
-// Extend ImGuiSelectableFlags_
-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
+ ImDrawListSharedData();
+ void SetCircleSegmentMaxError(float max_error);
};
-// Extend ImGuiTreeNodeFlags_
-enum ImGuiTreeNodeFlagsPrivate_
+struct ImDrawDataBuilder
{
- ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20
-};
+ ImVector Layers[2]; // Global layers for: regular, tooltip
-enum ImGuiSeparatorFlags_
-{
- ImGuiSeparatorFlags_None = 0,
- ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar
- ImGuiSeparatorFlags_Vertical = 1 << 1,
- ImGuiSeparatorFlags_SpanAllColumns = 1 << 2
+ 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] 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_
@@ -540,6 +595,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
};
@@ -564,6 +620,63 @@ enum ImGuiItemStatusFlags_
#endif
};
+// Extend ImGuiButtonFlags_
+enum ImGuiButtonFlagsPrivate_
+{
+ 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
+};
+
+// Extend ImGuiSliderFlags_
+enum ImGuiSliderFlagsPrivate_
+{
+ ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically?
+ ImGuiSliderFlags_ReadOnly = 1 << 21
+};
+
+// Extend ImGuiSelectableFlags_
+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, // Set Nav/Focus ID on mouse hover (used by MenuItem)
+ ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26 // Disable padding each side with ItemSpacing * 0.5f
+};
+
+// Extend ImGuiTreeNodeFlags_
+enum ImGuiTreeNodeFlagsPrivate_
+{
+ ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20
+};
+
+enum ImGuiSeparatorFlags_
+{
+ ImGuiSeparatorFlags_None = 0,
+ ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar
+ ImGuiSeparatorFlags_Vertical = 1 << 1,
+ ImGuiSeparatorFlags_SpanAllColumns = 1 << 2
+};
+
enum ImGuiTextFlags_
{
ImGuiTextFlags_None = 0,
@@ -677,57 +790,9 @@ 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
+struct ImGuiDataTypeTempStorage
{
- 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; }
+ ImU8 Data[8]; // Can fit any data up to ImGuiDataType_COUNT
};
// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo().
@@ -806,6 +871,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; // "
@@ -825,37 +891,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; // NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions.
- ImVec2ih Size;
- ImVec2ih ViewportPos;
- ImGuiID ViewportId;
- ImGuiID DockId; // ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none.
- ImGuiID ClassId; // ID of window class if specified
- short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible.
- bool Collapsed;
-
- ImGuiWindowSettings() { ID = 0; Pos = Size = ViewportPos = ImVec2ih(0, 0); ViewportId = DockId = ClassId = 0; DockOrder = -1; Collapsed = 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* (*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
{
@@ -870,120 +905,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();
- }
-};
-
-// 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();
-};
-
-// ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!)
-// Note that every instance of ImGuiViewport is in fact a ImGuiViewportP.
-struct ImGuiViewportP : public ImGuiViewport
-{
- int Idx;
- int LastFrameActive; // Last frame number this viewport was activated by a window
- int LastFrameDrawLists[2]; // Last frame number the background (0) and foreground (1) draw lists were used
- int LastFrontMostStampCount; // Last stamp number from when a window hosted by this viewport was made front-most (by comparing this value between two viewport we have an implicit viewport z-order
- ImGuiID LastNameHash;
- ImVec2 LastPos;
- float Alpha; // Window opacity (when dragging dockable windows/viewports we make them transparent)
- float LastAlpha;
- short PlatformMonitor;
- bool PlatformWindowCreated;
- ImGuiWindow* Window; // Set when the viewport is owned by a window (and ImGuiViewportFlags_CanHostOtherWindows is NOT set)
- ImDrawList* DrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays.
- ImDrawData DrawDataP;
- ImDrawDataBuilder DrawDataBuilder;
- ImVec2 LastPlatformPos;
- ImVec2 LastPlatformSize;
- ImVec2 LastRendererSize;
- ImVec2 CurrWorkOffsetMin; // Work area top-left offset being increased during the frame
- ImVec2 CurrWorkOffsetMax; // Work area bottom-right offset being decreased during the frame
-
- ImGuiViewportP() { Idx = -1; LastFrameActive = LastFrameDrawLists[0] = LastFrameDrawLists[1] = LastFrontMostStampCount = -1; LastNameHash = 0; Alpha = LastAlpha = 1.0f; PlatformMonitor = -1; PlatformWindowCreated = false; Window = NULL; DrawLists[0] = DrawLists[1] = NULL; LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); }
- ~ImGuiViewportP() { if (DrawLists[0]) IM_DELETE(DrawLists[0]); if (DrawLists[1]) IM_DELETE(DrawLists[1]); }
- ImRect GetMainRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }
- ImRect GetWorkRect() const { return ImRect(Pos.x + WorkOffsetMin.x, Pos.y + WorkOffsetMin.y, Pos.x + Size.x + WorkOffsetMax.x, Pos.y + Size.y + WorkOffsetMax.y); }
- void ClearRequestFlags() { PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; }
-};
-
struct ImGuiNavMoveResult
{
ImGuiWindow* Window; // Best candidate window
@@ -1061,29 +982,95 @@ 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; }
+};
+
//-----------------------------------------------------------------------------
-// Tabs
+// [SECTION] Columns support
//-----------------------------------------------------------------------------
-struct ImGuiShrinkWidthItem
+enum ImGuiColumnsFlags_
{
- int Index;
- float Width;
+ // 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 ImGuiPtrOrIndex
+struct ImGuiColumnData
{
- 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.
+ float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
+ float OffsetNormBeforeResize;
+ ImGuiColumnsFlags Flags; // Not exposed
+ ImRect ClipRect;
- ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; }
- ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; }
+ 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 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;
+ 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] Multi-select support
+//-----------------------------------------------------------------------------
+
+#ifdef IMGUI_HAS_MULTI_SELECT
+//
+#endif // #ifdef IMGUI_HAS_MULTI_SELECT
+
//-----------------------------------------------------------------------------
-// Docking
+// [SECTION] Docking support
//-----------------------------------------------------------------------------
+#ifdef IMGUI_HAS_DOCK
+
// Extend ImGuiDockNodeFlags_
enum ImGuiDockNodeFlagsPrivate_
{
@@ -1095,10 +1082,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
@@ -1174,8 +1168,97 @@ 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
+
+//-----------------------------------------------------------------------------
+// [SECTION] Viewport support
+//-----------------------------------------------------------------------------
+
+#ifdef IMGUI_HAS_VIEWPORT
+
+// ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!)
+// Note that every instance of ImGuiViewport is in fact a ImGuiViewportP.
+struct ImGuiViewportP : public ImGuiViewport
+{
+ int Idx;
+ int LastFrameActive; // Last frame number this viewport was activated by a window
+ int LastFrameDrawLists[2]; // Last frame number the background (0) and foreground (1) draw lists were used
+ int LastFrontMostStampCount; // Last stamp number from when a window hosted by this viewport was made front-most (by comparing this value between two viewport we have an implicit viewport z-order
+ ImGuiID LastNameHash;
+ ImVec2 LastPos;
+ float Alpha; // Window opacity (when dragging dockable windows/viewports we make them transparent)
+ float LastAlpha;
+ short PlatformMonitor;
+ bool PlatformWindowCreated;
+ ImGuiWindow* Window; // Set when the viewport is owned by a window (and ImGuiViewportFlags_CanHostOtherWindows is NOT set)
+ ImDrawList* DrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays.
+ ImDrawData DrawDataP;
+ ImDrawDataBuilder DrawDataBuilder;
+ ImVec2 LastPlatformPos;
+ ImVec2 LastPlatformSize;
+ ImVec2 LastRendererSize;
+ ImVec2 CurrWorkOffsetMin; // Work area top-left offset being increased during the frame
+ ImVec2 CurrWorkOffsetMax; // Work area bottom-right offset being decreased during the frame
+
+ ImGuiViewportP() { Idx = -1; LastFrameActive = LastFrameDrawLists[0] = LastFrameDrawLists[1] = LastFrontMostStampCount = -1; LastNameHash = 0; Alpha = LastAlpha = 1.0f; PlatformMonitor = -1; PlatformWindowCreated = false; Window = NULL; DrawLists[0] = DrawLists[1] = NULL; LastPlatformPos = LastPlatformSize = LastRendererSize = ImVec2(FLT_MAX, FLT_MAX); }
+ ~ImGuiViewportP() { if (DrawLists[0]) IM_DELETE(DrawLists[0]); if (DrawLists[1]) IM_DELETE(DrawLists[1]); }
+ ImRect GetMainRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }
+ ImRect GetWorkRect() const { return ImRect(Pos.x + WorkOffsetMin.x, Pos.y + WorkOffsetMin.y, Pos.x + Size.x + WorkOffsetMax.x, Pos.y + Size.y + WorkOffsetMax.y); }
+ void ClearRequestFlags() { PlatformRequestClose = PlatformRequestMove = PlatformRequestResize = false; }
+};
+
+#endif // #ifdef IMGUI_HAS_VIEWPORT
+
//-----------------------------------------------------------------------------
-// Main Dear ImGui context
+// [SECTION] Settings support
+//-----------------------------------------------------------------------------
+
+// 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; // NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions.
+ ImVec2ih Size;
+ ImVec2ih ViewportPos;
+ ImGuiID ViewportId;
+ ImGuiID DockId; // ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none.
+ ImGuiID ClassId; // ID of window class if specified
+ short DockOrder; // Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible.
+ 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 = ViewportPos = ImVec2ih(0, 0); ViewportId = DockId = ClassId = 0; DockOrder = -1; 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 (*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;
+
+ ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }
+};
+
+//-----------------------------------------------------------------------------
+// [SECTION] ImGuiContext (main imgui context)
//-----------------------------------------------------------------------------
struct ImGuiContext
@@ -1211,18 +1294,20 @@ 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.
+ 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;
float WheelingWindowTimer;
// 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
@@ -1230,6 +1315,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;
@@ -1270,7 +1356,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
@@ -1281,19 +1367,19 @@ 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.
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;
@@ -1304,11 +1390,13 @@ 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, 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;
@@ -1361,6 +1449,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
@@ -1376,7 +1466,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;
@@ -1386,8 +1476,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;
@@ -1397,7 +1487,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
@@ -1407,7 +1497,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)
{
@@ -1430,26 +1520,28 @@ struct ImGuiContext
HoveredWindow = NULL;
HoveredRootWindow = NULL;
HoveredWindowUnderMovingWindow = NULL;
+ HoveredDockNode = NULL;
MovingWindow = NULL;
WheelingWindow = NULL;
WheelingWindowTimer = 0.0f;
- HoveredId = 0;
+ HoveredId = HoveredIdPreviousFrame = 0;
HoveredIdAllowOverlap = false;
- HoveredIdPreviousFrame = 0;
+ HoveredIdDisabled = false;
HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
ActiveId = 0;
ActiveIdIsAlive = 0;
ActiveIdTimer = 0.0f;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
+ ActiveIdNoClearOnFocusLoss = false;
ActiveIdHasBeenPressedBefore = false;
ActiveIdHasBeenEditedBefore = false;
ActiveIdHasBeenEditedThisFrame = false;
ActiveIdUsingNavDirMask = 0x00;
ActiveIdUsingNavInputMask = 0x00;
ActiveIdUsingKeyInputMask = 0x00;
- ActiveIdClickOffset = ImVec2(-1,-1);
+ ActiveIdClickOffset = ImVec2(-1, -1);
ActiveIdWindow = NULL;
ActiveIdSource = ImGuiInputSource_None;
ActiveIdMouseButton = 0;
@@ -1489,8 +1581,10 @@ struct ImGuiContext
NavMoveRequestForward = ImGuiNavForward_None;
NavMoveRequestKeyMods = ImGuiKeyModFlags_None;
NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None;
+ NavWrapRequestWindow = NULL;
+ NavWrapRequestFlags = ImGuiNavMoveFlags_None;
- NavWindowingTarget = NavWindowingTargetAnim = NavWindowingList = NULL;
+ NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;
NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
NavWindowingToggleLayer = false;
@@ -1521,6 +1615,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;
@@ -1530,8 +1626,6 @@ struct ImGuiContext
PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX);
PlatformImePosViewport = 0;
- DockContext = NULL;
-
SettingsLoaded = false;
SettingsDirtyTimer = 0.0f;
@@ -1555,7 +1649,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.
@@ -1668,7 +1762,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")
@@ -1687,7 +1781,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)
@@ -1706,7 +1800,7 @@ struct IMGUI_API ImGuiWindow
ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use.
ImGuiCond SetWindowDockAllowFlags; // store acceptable condition flags for SetNextWindowDock() 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.
@@ -1716,10 +1810,12 @@ 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, HitTestHoleOffset;
+ 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.
int LastFrameJustFocused; // Last frame number the window was made Focused.
@@ -1734,7 +1830,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* RootWindowDockStop; // Point to ourself or first ancestor that is not a child window. Doesn't cross through dock nodes. We use this so IsWindowFocused() can behave consistently regardless of docking state.
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.
@@ -1743,8 +1839,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;
// Docking
@@ -1771,29 +1867,29 @@ 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 * FontDpiScale; 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 * FontDpiScale; 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.
-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; }
};
//-----------------------------------------------------------------------------
-// Tab bar, tab item
+// [SECTION] Tab bar, Tab item support
//-----------------------------------------------------------------------------
// Extend ImGuiTabBarFlags_
@@ -1820,12 +1916,13 @@ struct ImGuiTabItem
ImGuiWindow* Window; // When TabItem is part of a DockNode's TabBar, we hold on to a window.
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; Window = NULL; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; }
+ ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; Window = NULL; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; WantClose = false; }
};
// Storage for a tab bar (sizeof() 92~96 bytes)
@@ -1862,14 +1959,22 @@ struct ImGuiTabBar
{
if (tab->Window)
return tab->Window->Name;
- 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;
}
};
//-----------------------------------------------------------------------------
-// Internal API
-// No guarantee of forward compatibility here.
+// [SECTION] Table support
+//-----------------------------------------------------------------------------
+
+#ifdef IMGUI_HAS_TABLE
+//
+#endif // #ifdef IMGUI_HAS_TABLE
+
+//-----------------------------------------------------------------------------
+// [SECTION] Internal API
+// No guarantee of forward compatibility here!
//-----------------------------------------------------------------------------
namespace ImGui
@@ -1891,6 +1996,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);
@@ -1924,6 +2030,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);
@@ -1938,7 +2045,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; }
@@ -1949,7 +2056,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);
@@ -1957,6 +2064,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);
@@ -1964,27 +2072,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 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); // 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, 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();
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();
@@ -1997,8 +2105,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; }
@@ -2017,7 +2127,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);
@@ -2026,8 +2136,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);
@@ -2048,8 +2159,8 @@ 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 DockBuilderRemoveNodeChildNodes(ImGuiID node_id); // Remove all split/hierarchy. All remaining docked windows will be re-docked to the root.
+ 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);
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.
@@ -2063,7 +2174,8 @@ 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 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);
@@ -2085,14 +2197,14 @@ namespace ImGui
IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window);
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.
// 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);
@@ -2120,12 +2232,13 @@ 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, ImGuiDockNode* dock_node);
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
@@ -2133,8 +2246,8 @@ 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, 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);
IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging
@@ -2143,21 +2256,24 @@ 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 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 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);
// 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
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
@@ -2189,24 +2305,16 @@ 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);
-// 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_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);
diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp
index 4ce46798..a3062041 100644
--- a/imgui_widgets.cpp
+++ b/imgui_widgets.cpp
@@ -1,4 +1,4 @@
-// dear imgui, v1.77 WIP
+// dear imgui, v1.79 WIP
// (widgets code)
/*
@@ -58,19 +58,19 @@ 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 //
-#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("-Wdeprecated-enum-enum-conversion")
-#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
+#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
+#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 "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
@@ -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);
}
@@ -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();
}
@@ -594,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)
{
@@ -614,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)
@@ -626,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();
}
@@ -681,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.
@@ -697,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)
@@ -714,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;
}
@@ -780,8 +784,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;
}
@@ -987,28 +991,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;
@@ -1019,14 +1011,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();
@@ -1066,7 +1077,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)
@@ -1132,7 +1143,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);
}
@@ -1165,7 +1176,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))
@@ -1182,13 +1193,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()
@@ -1199,18 +1210,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);
}
@@ -1232,7 +1243,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)
@@ -1256,7 +1267,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;
@@ -1483,7 +1494,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))
@@ -1491,7 +1502,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);
@@ -1508,7 +1519,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);
@@ -1516,7 +1527,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;
}
@@ -1618,7 +1629,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;
@@ -1676,6 +1687,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa
// - DataTypeFormatString()
// - DataTypeApplyOp()
// - DataTypeApplyOpFromText()
+// - DataTypeClamp()
// - GetMinimumStepAtDecimalPrecision
// - RoundScalarWithFormat<>()
//-------------------------------------------------------------------------
@@ -1753,7 +1765,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)
@@ -1827,11 +1839,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;
@@ -1903,7 +1913,64 @@ 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 int DataTypeCompareT(const T* lhs, const T* rhs)
+{
+ 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; }
+ 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 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);
+ return false;
}
static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
@@ -1966,16 +2033,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, 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_power = (power != 1.0f && is_decimal && is_clamped && (v_max - v_min < FLT_MAX));
- const bool is_locked = (v_min > v_max);
- if (is_locked)
- return false;
+ 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))
@@ -1983,7 +2047,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)
@@ -2003,12 +2067,15 @@ 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;
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;
@@ -2025,13 +2092,19 @@ 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
+ const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense)
+ if (is_logarithmic)
{
- // 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;
+ // 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
+ 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_old_ref_for_accum_remainder = v_old_parametric;
}
else
{
@@ -2039,14 +2112,16 @@ 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 & ImGuiSliderFlags_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;
- if (is_power)
+ if (is_logarithmic)
{
- 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);
+ // 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);
+ g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder);
}
else
{
@@ -2073,8 +2148,11 @@ 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, ImGuiSliderFlags 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 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)
{
@@ -2085,19 +2163,21 @@ 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 & ImGuiSliderFlags_ReadOnly))
+ return false;
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);
@@ -2105,22 +2185,19 @@ 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. 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)
+// 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, ImGuiSliderFlags 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);
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);
@@ -2135,11 +2212,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);
- bool temp_input_start = false;
+ 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]);
const bool double_clicked = (hovered && g.IO.MouseDoubleClicked[0]);
if (focus_requested || clicked || double_clicked || g.NavActivateId == id || g.NavInputId == id)
@@ -2148,15 +2225,20 @@ 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_start = true;
+ temp_input_is_active = true;
FocusableItemUnregister(window);
}
}
}
- if (temp_input_is_active || temp_input_start)
- return TempInputScalar(frame_bb, id, label, data_type, p_data, format);
+
+ 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);
+ 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);
@@ -2164,7 +2246,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, flags);
if (value_changed)
MarkItemEdited(id);
@@ -2180,7 +2262,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, float 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, ImGuiSliderFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
@@ -2197,7 +2279,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 |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags);
PopID();
PopItemWidth();
p_data = (void*)((char*)p_data + type_size);
@@ -2215,27 +2297,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, float power)
+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, power);
+ 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, float power)
+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, power);
+ 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, float power)
+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, power);
+ 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, float power)
+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, power);
+ return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, 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, float power)
+// 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)
@@ -2246,10 +2329,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_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);
+ 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);
- 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);
+
+ 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;
+ 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);
@@ -2260,27 +2350,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)
+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);
+ 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, ImGuiSliderFlags 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, ImGuiSliderFlags 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, ImGuiSliderFlags 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)
+// 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)
@@ -2291,10 +2382,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_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);
+ 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);
- 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);
+
+ 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;
+ 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);
@@ -2305,9 +2403,40 @@ 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. 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)
+{
+ ImGuiSliderFlags drag_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!");
+ IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds
+ 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)
+{
+ ImGuiSliderFlags drag_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!");
+ IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds
+ 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);
+}
+
+#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+
//-------------------------------------------------------------------------
// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
//-------------------------------------------------------------------------
+// - ScaleRatioFromValueT<> [Internal]
+// - ScaleValueFromRatioT<> [Internal]
// - SliderBehaviorT<>() [Internal]
// - SliderBehavior() [Internal]
// - SliderScalar()
@@ -2326,42 +2455,147 @@ 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 (the logical opposite of ScaleValueFromRatioT)
template
-float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos)
+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_power = (power != 1.0f) && (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_power)
+ if (is_logarithmic)
{
- if (v_clamped < 0.0f)
+ 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
{
- 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;
+ 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_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_snap_L;
+ else
+ 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));
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);
- }
+ result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged));
+
+ return flipped ? (1.0f - result) : result;
}
// Linear slider
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.
+// Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT)
+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)
+ return (TYPE)0.0f;
+ const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
+
+ 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_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_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_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)));
+ else
+ result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip));
+ }
+ }
+ 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 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, 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;
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 = (flags & ImGuiSliderFlags_Logarithmic) && is_decimal;
const float grab_padding = 2.0f;
const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;
@@ -2374,19 +2608,14 @@ 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)
+ float logarithmic_zero_epsilon = 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)
{
- // 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;
+ // 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_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f);
}
// Process interacting with the slider
@@ -2412,87 +2641,80 @@ 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.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)
+
+ 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)
{
- 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)
+ 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;
- 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;
- else
- clicked_t = ImSaturate(clicked_t + delta);
+ input_delta *= 10.0f;
+
+ g.SliderCurrentAccum += input_delta;
+ g.SliderCurrentAccumDirty = true;
}
- }
- if (set_new_value)
- {
- TYPE v_new;
- if (is_power)
+ float delta = g.SliderCurrentAccum;
+ if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
{
- // 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);
- }
+ ClearActiveID();
}
- else
+ else if (g.SliderCurrentAccumDirty)
{
- // Linear slider
- if (is_decimal)
+ 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
{
- v_new = ImLerp(v_min, v_max, clicked_t);
+ set_new_value = false;
+ g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate
}
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;
+ 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 = 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);
+
+ if (delta > 0)
+ g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta);
else
- v_new = v_min + v_new_off_floor;
+ g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta);
}
+
+ g.SliderCurrentAccumDirty = false;
}
+ }
+
+ if (set_new_value)
+ {
+ 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
- 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)
@@ -2510,7 +2732,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 = 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);
@@ -2526,32 +2748,39 @@ 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)
{
+ // 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) || (flags & ImGuiSliderFlags_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; }
- 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);
+ 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, 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);
+ 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, 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);
+ 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, 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);
+ 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, 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);
+ 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, 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, flags, out_grab_bb);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
@@ -2560,7 +2789,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type
// 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)
+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)
@@ -2572,7 +2801,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);
@@ -2587,11 +2816,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);
- bool temp_input_start = false;
+ 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)
{
@@ -2599,15 +2828,20 @@ 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_start = true;
+ temp_input_is_active = true;
FocusableItemUnregister(window);
}
}
}
- if (temp_input_is_active || temp_input_start)
- return TempInputScalar(frame_bb, id, label, data_type, p_data, format);
+
+ if (temp_input_is_active)
+ {
+ // 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);
@@ -2616,7 +2850,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, flags, &grab_bb);
if (value_changed)
MarkItemEdited(id);
@@ -2627,7 +2861,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);
@@ -2637,7 +2871,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat
}
// 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)
+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)
@@ -2654,7 +2888,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 |= SliderScalar("", data_type, v, v_min, v_max, format, flags);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
@@ -2672,57 +2906,57 @@ bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, i
return value_changed;
}
-bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power)
+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, power);
+ return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);
}
-bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power)
+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, power);
+ return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags);
}
-bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power)
+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, power);
+ return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags);
}
-bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power)
+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, power);
+ return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags);
}
-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, ImGuiSliderFlags 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);
- *v_rad = v_deg * (2*IM_PI) / 360.0f;
+ float v_deg = (*v_rad) * 360.0f / (2 * IM_PI);
+ 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, ImGuiSliderFlags 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, ImGuiSliderFlags 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, ImGuiSliderFlags 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, ImGuiSliderFlags 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)
+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)
@@ -2762,7 +2996,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, flags | ImGuiSliderFlags_Vertical, &grab_bb);
if (value_changed)
MarkItemEdited(id);
@@ -2774,23 +3008,50 @@ 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);
return value_changed;
}
-bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_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 VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, 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, power);
+ return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);
}
-bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+
+// 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 VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format);
+ 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)
+{
+ 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
+
//-------------------------------------------------------------------------
// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
//-------------------------------------------------------------------------
@@ -2906,7 +3167,11 @@ 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 only forwarding the min/max values clamping values if the
+// 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)
{
ImGuiContext& g = *GImGui;
@@ -2918,10 +3183,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_backup, p_data, data_type_size) != 0;
if (value_changed)
MarkItemEdited(id);
}
@@ -2949,7 +3225,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)
{
@@ -3040,7 +3316,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)
@@ -3097,7 +3373,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)
@@ -3118,7 +3394,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);
}
//-------------------------------------------------------------------------
@@ -3133,7 +3409,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)
@@ -3168,7 +3444,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;
@@ -3229,10 +3505,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; }
@@ -3245,6 +3521,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;
@@ -3279,6 +3556,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';
@@ -3367,7 +3645,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);
@@ -3420,21 +3698,25 @@ 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'));
+ *p_char = (c += (unsigned int)('A' - 'a'));
if (flags & ImGuiInputTextFlags_CharsNoBlank)
if (ImCharIsBlankW(c))
@@ -3474,6 +3756,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)
@@ -3494,7 +3777,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);
@@ -3672,6 +3955,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;
@@ -3684,7 +3968,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]))
@@ -3780,9 +4064,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);
}
@@ -3841,7 +4125,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; )
{
@@ -3909,7 +4193,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);
@@ -3931,8 +4215,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)
{
@@ -4173,7 +4463,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);
@@ -4236,7 +4526,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)
@@ -4347,8 +4637,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" };
@@ -4375,7 +4665,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
@@ -4383,7 +4673,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)
@@ -4391,9 +4681,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))
{
@@ -4408,7 +4698,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;
@@ -4425,11 +4715,11 @@ 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))
- OpenPopupOnItemClick("context");
+ OpenPopupContextItem("context");
if (BeginPopup("picker"))
{
@@ -4586,7 +4876,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);
@@ -4625,10 +4915,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;
@@ -4649,7 +4939,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)
{
@@ -4657,19 +4947,19 @@ 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))
- OpenPopupOnItemClick("context");
+ OpenPopupContextItem("context");
// Hue bar logic
SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
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;
}
}
@@ -4681,7 +4971,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;
}
}
@@ -4732,7 +5022,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);
@@ -4755,7 +5045,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;
@@ -4835,17 +5125,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)
@@ -4883,7 +5173,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
@@ -4955,8 +5245,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
{
@@ -5074,7 +5364,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"))
{
@@ -5118,16 +5408,16 @@ 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();
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();
@@ -5302,7 +5592,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;
@@ -5316,9 +5606,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);
@@ -5364,17 +5654,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;
@@ -5452,9 +5739,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
{
@@ -5575,13 +5862,13 @@ 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.
// 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;
@@ -5599,7 +5886,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.
@@ -5612,7 +5899,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.
@@ -5624,8 +5912,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 = 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);
@@ -5634,33 +5922,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;
}
@@ -5679,7 +5969,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)))
@@ -5706,15 +5996,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
@@ -5929,7 +6219,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;
@@ -5975,7 +6265,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);
@@ -6136,7 +6426,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);
@@ -6250,7 +6541,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;
@@ -6280,7 +6571,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)
@@ -6376,7 +6667,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));
@@ -6599,9 +6890,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);
@@ -6634,7 +6925,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().
@@ -6658,15 +6949,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)
@@ -6824,6 +7117,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.
@@ -7019,7 +7317,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;
@@ -7106,7 +7404,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)
{
@@ -7155,7 +7454,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open,
else
{
IM_ASSERT(tab->Window == NULL);
- tab->NameOffset = tab_bar->TabsNames.size();
+ tab->NameOffset = (ImS16)tab_bar->TabsNames.size();
tab_bar->TabsNames.append(label, label + strlen(label) + 1); // Append name _with_ the zero-terminator.
}
@@ -7175,6 +7474,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;
@@ -7184,7 +7484,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);
@@ -7231,6 +7533,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();
@@ -7291,8 +7598,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;
}
}
}
@@ -7323,7 +7631,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;
@@ -7338,14 +7646,15 @@ 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;
}
// [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.
void ImGui::SetTabItemClosed(const char* label)
{
ImGuiContext& g = *GImGui;
@@ -7353,9 +7662,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()
}
else if (ImGuiWindow* window = FindWindowByName(label))
{
@@ -7408,13 +7717,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);
@@ -7434,11 +7751,12 @@ 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 == tab_id || g.ActiveId == close_button_id)
+ 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)))
@@ -7456,6 +7774,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;
}
@@ -7464,6 +7787,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()
@@ -7481,6 +7805,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();
@@ -7575,7 +7911,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))
@@ -7615,11 +7951,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()
@@ -7628,8 +7964,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)
@@ -7677,8 +8015,9 @@ 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->HostWorkRect = window->WorkRect;
+ 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
@@ -7749,25 +8088,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);
@@ -7775,8 +8120,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);
@@ -7854,7 +8197,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);
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 69108e3e..3d62dc4b 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.
@@ -381,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;
@@ -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;
@@ -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).
@@ -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;
@@ -559,6 +562,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);
@@ -574,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;
@@ -589,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;
@@ -607,8 +606,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;