diff --git a/.travis.yml b/.travis.yml
index ccdb19429..044b87a96 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -9,10 +9,10 @@ compiler:
- clang
before_install:
- - if [ $TRAVIS_OS_NAME == linux ]; then sudo add-apt-repository -y ppa:pyglfw/pyglfw && sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends libglfw3-dev libxrandr-dev libxi-dev libxxf86vm-dev; fi
- - if [ $TRAVIS_OS_NAME == osx ]; then brew update && brew install glfw3; fi
+ - if [ $TRAVIS_OS_NAME == linux ]; then sudo add-apt-repository -y ppa:pyglfw/pyglfw && sudo apt-add-repository --yes ppa:zoogie/sdl2-snapshots && sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends libglfw3-dev libxrandr-dev libxi-dev libxxf86vm-dev libsdl2-dev; fi
+ - if [ $TRAVIS_OS_NAME == osx ]; then brew update && brew install glfw3 && brew install sdl2; fi
script:
- make -C examples/opengl2_example
- make -C examples/opengl3_example
-
+ - make -C examples/sdl_opengl3_example
diff --git a/LICENSE b/LICENSE.txt
similarity index 94%
rename from LICENSE
rename to LICENSE.txt
index b28ef2253..21b6ee7e2 100644
--- a/LICENSE
+++ b/LICENSE.txt
@@ -1,6 +1,6 @@
The MIT License (MIT)
-Copyright (c) 2014-2015 Omar Cornut and ImGui contributors
+Copyright (c) 2014-2018 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README.md
index 9c352696b..c76e6a8f8 100644
--- a/README.md
+++ b/README.md
@@ -3,17 +3,21 @@ dear imgui,
[![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui)
[![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720)
-(This library is free and will stay free, but needs your support to sustain its development. There are lots of desirable new features and maintenance to do. If you work for a company using ImGui or have the means to do so, please consider financial support)
+(This library is free but needs your support to sustain its development. There are lots of desirable new features and maintenance to do. If you are an individual using dear imgui, please consider donating via Patreon or PayPal. If your company is using dear imgui, please consider financial support (e.g. sponsoring a few weeks/months of development). I can invoice for private support, custom development etc. E-mail: omarcornut at gmail.)
-[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
+Monthly donations via Patreon:
+ [![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui)
-dear imgui (AKA ImGui), is a bloat-free graphical user interface library for C++. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies).
+One-off donations via PayPal:
+ [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
-ImGui is designed to enable fast iteration and empower programmers to create content creation tools and visualization/ debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries.
+Dear ImGui is a bloat-free graphical user interface library for C++. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies).
-ImGui is particularly suited to integration in realtime 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard.
+Dear ImGui is designed to enable fast iteration and empower programmers to create content creation tools and visualization/ debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries.
-ImGui is self-contained within a few files that you can easily copy and compile into your application/engine:
+Dear ImGui is particularly suited to integration in realtime 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard.
+
+Dear ImGui is self-contained within a few files that you can easily copy and compile into your application/engine:
- imgui.cpp
- imgui.h
@@ -27,53 +31,63 @@ ImGui is self-contained within a few files that you can easily copy and compile
No specific build process is required. You can add the .cpp files to your project or #include them from an existing file.
-Your code passes mouse/keyboard inputs and settings to ImGui (see example applications for more details). After ImGui is setup, you can use it like in this example:
+Your code passes mouse/keyboard inputs and settings to Dear ImGui (see example applications for more details). After Dear ImGui is setup, you can use it like in this example:
-![screenshot of sample code alongside its output with ImGui](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01.png)
+![screenshot of sample code alongside its output with dear imgui](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01.png)
-ImGui outputs vertex buffers and simple command-lists that you can render in your application. The number of draw calls and state changes is typically very small. Because it doesn't know or touch graphics state directly, you can call ImGui commands 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 ImGui with your existing codebase.
+Dear ImGui outputs vertex buffers and simple command-lists that you can render in your application. The number of draw calls and state changes is typically very small. Because it doesn't know or touch graphics state directly, you can call ImGui commands 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 that some people think immediate mode gui == immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes, as the gui functions as called by the user. Some lazy IMGUI-style librairies may work this way but 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 rather optimal and you can render them later, in your app or even remotely._
+_A common misunderstanding is to think that immediate mode gui == 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 by the user. 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._
-ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, etc.
+Dear ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! Dear ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, an entire game making editor/framework, etc.
Binaries/Demo
-------------
-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 the features of ImGui, you can download Windows binaries of the demo app here.
-- [imgui-demo-binaries-20161113.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20161113.zip) (Windows binaries, ImGui 1.49+ 2016/11/13, 5 executables, 588 KB)
+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-20171226.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20171226.zip) (Windows binaries, Dear ImGui 1.53 built 2017/12/26, 5 executables)
Bindings
--------
-_NB: those third-party bindings may be more or less maintained, more or less close to the spirit of original API. People who create language bindings sometimes haven't used the C++ API themselves. ImGui was designed with C++ in mind and some of the subtleties may be lost in translation with other languages. If your language supports it, I would suggest replicating the function overloading and default parameters used in the original, else the API may be harder to use. In doubt, always check the original C++ version first!_
+Integrating Dear ImGui within your custom engine is a matter of wiring mouse/keyboard inputs and providing a render function that can bind a texture and render simple textured triangles. The examples/ folder is populated with applications doing just that. If you are an experienced programmer it should take you less than an hour to integrate Dear ImGui in your custom engine, but make sure to spend time reading the FAQ, the comments and other documentation!
+
+_NB: those third-party bindings may be more or less maintained, more or less close to the spirit of original API and therefore I cannot give much guarantee about them. People who create language bindings sometimes haven't used the C++ API themselves (for the good reason that they aren't C++ users). Dear ImGui was designed with C++ in mind and some of the subtleties may be lost in translation with other languages. If your language supports it, I would suggest replicating the function overloading and default parameters used in the original, else the API may be harder to use. In doubt, please check the original C++ version first!_
Languages:
-- cimgui: thin c-api wrapper for ImGui https://github.com/Extrawurst/cimgui
-- ImGui.NET: An ImGui wrapper for .NET Core https://github.com/mellinoe/ImGui.NET
-- imgui-rs: Rust bindings for dear imgui https://github.com/Gekkio/imgui-rs
-- DerelictImgui: Dynamic bindings for the D programming language: https://github.com/Extrawurst/DerelictImgui
-- CyImGui: Python bindings for dear imgui using Cython: https://github.com/chromy/cyimgui
-- pyimgui: Another Python bindings for dear imgui: https://github.com/swistakm/pyimgui
-- LUA: https://github.com/patrickriordan/imgui_lua_bindings
+- C (cimgui): https://github.com/Extrawurst/cimgui
+- C#/.Net (ImGui.NET): https://github.com/mellinoe/ImGui.NET
+- ChaiScript: https://github.com/JuJuBoSc/imgui-chaiscript
+- D (DerelictImgui): https://github.com/Extrawurst/DerelictImgui
+- Go (go-imgui): https://github.com/Armored-Dragon/go-imgui
+- Haxe/hxcpp (linc_imgui): https://github.com/Aidan63/linc_imgui
+- Lua: https://github.com/patrickriordan/imgui_lua_bindings
+- Odin: https://github.com/ThisDrunkDane/odin-dear_imgui
+- Pascal (imgui-pas): https://github.com/dpethes/imgui-pas
+- Python (CyImGui): https://github.com/chromy/cyimgui
+- Python (pyimgui): https://github.com/swistakm/pyimgui
+- Rust (imgui-rs): https://github.com/Gekkio/imgui-rs
Frameworks:
- Main ImGui repository include examples for DirectX9, DirectX10, DirectX11, OpenGL2/3, Vulkan, Allegro 5, SDL+GL2/3, iOS and Marmalade: https://github.com/ocornut/imgui/tree/master/examples
-- Unmerged PR: DirectX12 example (with issues) https://github.com/ocornut/imgui/pull/301
-- Unmerged PR: SDL2 + OpenGLES + Emscripten example https://github.com/ocornut/imgui/pull/336
-- Unmerged PR: FreeGlut + OpenGL2 example https://github.com/ocornut/imgui/pull/801
-- Unmerged PR: Native Win32 and OSX example https://github.com/ocornut/imgui/pull/281
-- Unmerged PR: Android Example https://github.com/ocornut/imgui/pull/421
-- Cinder backend for dear imgui https://github.com/simongeilfus/Cinder-ImGui
-- FlexGUI: Flexium/SFML backend for dear imgui https://github.com/DXsmiley/FlexGUI
-- IrrIMGUI: Irrlicht backend for dear imgui https://github.com/ZahlGraf/IrrIMGUI
-- LÖVE backend for dear imgui https://github.com/slages/love-imgui
-- Ogre backend for dear imgui https://bitbucket.org/LMCrashy/ogreimgui/src
-- ofxImGui: openFrameworks backend for dear imgui https://github.com/jvcleave/ofxImGui
-- SFML backend for dear imgui https://github.com/EliasD/imgui-sfml
-- SFML backend for dear imgui https://github.com/Mischa-Alff/imgui-backends
-- cocos2d-x with imgui https://github.com/c0i/imguix https://github.com/ocornut/imgui/issues/551
-- NanoRT: software raytraced version https://github.com/syoyo/imgui/tree/nanort/examples/raytrace_example
+- Unmerged PR: DirectX12: https://github.com/ocornut/imgui/pull/301
+- Unmerged PR: SDL2 + OpenGLES + Emscripten: https://github.com/ocornut/imgui/pull/336
+- Unmerged PR: FreeGlut + OpenGL2: https://github.com/ocornut/imgui/pull/801
+- Unmerged PR: Native Win32 and OSX: https://github.com/ocornut/imgui/pull/281
+- Unmerged PR: Android: https://github.com/ocornut/imgui/pull/421
+- Cinder: https://github.com/simongeilfus/Cinder-ImGui
+- cocos2d-x: https://github.com/c0i/imguix https://github.com/ocornut/imgui/issues/551
+- Flexium/SFML (FlexGUI): https://github.com/DXsmiley/FlexGUI
+- GML/GameMakerStudio2 (ImGuiGML): https://marketplace.yoyogames.com/assets/6221/imguigml
+- Irrlicht (IrrIMGUI): https://github.com/ZahlGraf/IrrIMGUI
+- Ogre: https://bitbucket.org/LMCrashy/ogreimgui/src
+- openFrameworks (ofxImGui): https://github.com/jvcleave/ofxImGui
+- OpenSceneGraph/OSG: https://gist.github.com/fulezi/d2442ca7626bf270226014501357042c
+- LÖVE: https://github.com/slages/love-imgui
+- NanoRT (software raytraced) https://github.com/syoyo/imgui/tree/nanort/examples/raytrace_example
+- Qt3d https://github.com/alpqr/imgui-qt3d
+- Unreal Engine 4: https://github.com/segross/UnrealImGui or https://github.com/sronsse/UnrealEngine_ImGui
+- SFML: https://github.com/EliasD/imgui-sfml or https://github.com/Mischa-Alff/imgui-backends
For other bindings: see [this page](https://github.com/ocornut/imgui/wiki/Links/).
Please contact me with the Issues tracker or Twitter to fix/update this list.
@@ -82,20 +96,21 @@ Gallery
-------
See the [Screenshots Thread](https://github.com/ocornut/imgui/issues/123) for some user creations.
+Also see the [Mega screenshots](https://github.com/ocornut/imgui/issues/1273) for an idea of the available features.
![screenshot 1](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_01.png)
+[![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png)
![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_02.png)
-[![profiler](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler-880.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler.png)
+[![screenshot profiler](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler-880.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler.png)
-![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_01.png)
-![screenshot 3](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_02.png)
-![screenshot 4](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_03.png)
-![screenshot 5](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v140/test_window_05_menus.png)
+![screenshot picker](https://user-images.githubusercontent.com/8225057/29062188-471e95ba-7c53-11e7-9618-c4484c0b75fe.PNG)
+
+![screenshot 5](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v151/menus.png)
![screenshot 6](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/skinning_sample_02.png)
![screenshot 7](https://cloud.githubusercontent.com/assets/8225057/7903336/96f0fb7c-07d0-11e5-95d6-41c6a1595e5a.png)
-ImGui can load TTF fonts. UTF-8 is supported for text display and input. Here using Arial Unicode font to display Japanese. Initialize custom font with:
+Dear ImGui can load TTF/OTF fonts. UTF-8 is supported for text display and input. Here using Arial Unicode font to display Japanese. Initialize custom font with:
```
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
@@ -113,6 +128,10 @@ The Immediate Mode GUI paradigm may at first appear unusual to some users. This
- [A presentation by Rickard Gustafsson and Johannes Algelind](http://www.cse.chalmers.se/edu/year/2011/course/TDA361/Advanced%20Computer%20Graphics/IMGUI.pdf).
- [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/).
- [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861).
+- [Nicolas Guillemot's CppCon'16 flashtalk about Dear ImGui](https://www.youtube.com/watch?v=LSRJ1jZq90k).
+- [Thierry Excoffier's Zero Memory Widget](http://perso.univ-lyon1.fr/thierry.excoffier/ZMW/).
+
+See the [Software using dear imgui page](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) for an incomplete list of software which are publicly known to use dear migui.
See the [Links page](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to different languages and frameworks.
@@ -122,41 +141,46 @@ Frequently Asked Question (FAQ)
Where is the documentation?
- The documentation is at the top of imgui.cpp + effectively imgui.h.
-- Example code is in imgui_demo.cpp and particularly the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output.
+- Example code is in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output.
- Standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder.
- We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort.
+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. The library is fairly stable and regressions tend to be fixed fast when reported. You may also want to checkout the [navigation branch](https://github.com/ocornut/imgui/tree/navigation) if you want to use Dear ImGui with a gamepad (it is also possible to map keyboard inputs to some degree). The Navigation branch is being kept up to date with Master.
+
Why the odd dual naming, "dear imgui" vs "ImGui"?
The library started its life and is best known as "ImGui" only due to the fact that I didn't give it a proper name when I released it. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations. It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "dear imgui" that people can use to refer to this specific library in ambiguous situations.
-How do I update to a newer version of ImGui?
- What is ImTextureID and how do I display an image?
- I integrated ImGui in my engine and the text or lines are blurry..
- I integrated ImGui in my engine and some elements are disappearing when I move windows around..
- 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.
- How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
+How can I help
+ How can I display an image? What is ImTextureID, how does it works?
+ How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels and the ID stack.
+ How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application? How can I load a different font than the default? How can I easily use icons in my application? How can I load multiple fonts? How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
+ How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables)
+ How can I use the drawing facilities without an Dear ImGui window? (using ImDrawList API)
+ I integrated Dear ImGui in my engine and the text or lines are blurry..
+ I integrated Dear ImGui in my engine and some elements are disappearing when I move windows around..
See the FAQ in imgui.cpp for answers.
-How do you use ImGui on a platform that may not have a mouse or keyboard?
+How do you use Dear ImGui on a platform that may not have a mouse or keyboard?
-I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/symless/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accommodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate.
+I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/symless/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. Dear ImGui allows to increase the hit box of widgets (via the _style.TouchPadding_ setting) to accommodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate. You can also checkout the beta [navigation branch](https://github.com/ocornut/imgui/tree/navigation) which provides support for using Dear ImGui with a game controller.
-Can you create elaborate/serious tools with ImGui?
+Can you create elaborate/serious tools with Dear ImGui?
-Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools).
+Yes. People have written game editors, data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools).
-ImGui is very programmer centric and the immediate-mode GUI paradigm might requires you to readjust some habits before you can realize its full potential. Many programmers have unfortunately been taught by their environment to make unnecessarily complicated things. ImGui is about making things that are simple, efficient and powerful.
+Dear ImGui is very programmer centric and the immediate-mode GUI paradigm might requires you to readjust some habits before you can realize its full potential. Dear ImGui is about making things that are simple, efficient and powerful.
-Is ImGui fast?
+Is Dear ImGui fast?
-Probably fast enough for most uses. Down to the foundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it.
+Probably fast enough for most uses. Down to the foundation of its visual design, Dear ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but Dear ImGui aims to minimize it.
Mileage may vary but the following screenshot can give you a rough idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup are likely to be the bottleneck. Testing performance as part of a real application is recommended).
@@ -164,30 +188,34 @@ Mileage may vary but the following screenshot can give you a rough idea of the c
This is showing framerate for the full application loop on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M with an optimized executable. In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint.
-If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - one way is using helpers such as ImGuiListClipper - in order to avoid submitting them to ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem.
+If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - one way is using helpers such as ImGuiListClipper - in order to avoid submitting them to Dear ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem.
-Can you reskin the look of ImGui?
+Can you reskin the look of Dear ImGui?
-You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface.
+You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as Dear ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. Below is a screenshot from [LumixEngine](https://github.com/nem0/LumixEngine) with custom colors + a docking/tabs extension (both of which you can find in the Issues section and will eventually be merged):
-This is [LumixEngine](https://github.com/nem0/LumixEngine) with a minor skinning hack + a docking/tabs extension (both of which you can find in the Issues section and will eventually be merged).
-
-[![Skinning in LumixEngine](https://cloud.githubusercontent.com/assets/8225057/13198792/92808c5c-d812-11e5-9507-16b63918b05b.jpg)](https://cloud.githubusercontent.com/assets/8225057/13044612/59f07aec-d3cf-11e5-8ccb-39adf2e13e69.png)
+![LumixEngine](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v151/lumix-201710-rearranged.png)
Why using C++ (as opposed to C)?
-ImGui takes advantage of a few C++ features for convenience but nothing anywhere Boost-insanity/quagmire. In particular, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience but could be removed.
+Dear ImGui takes advantage of a few C++ languages features for convenience but nothing anywhere Boost-insanity/quagmire. Dear ImGui does NOT require C++11 so it can be used with most old C++ compilers. Dear ImGui doesn't use any C++ header file. Language-wise, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience.
-There is an unofficial but reasonably maintained [c-api for ImGui](https://github.com/Extrawurst/cimgui) by Stephan Dilly. I would suggest using your target language functionality to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. It was really designed with C++ in mind and may not make the same amount of sense with another language. Also see [Links](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to other languages.
+There is an reasonably maintained [c-api for ImGui](https://github.com/Extrawurst/cimgui) by Stephan Dilly designed for binding in other languages. I would suggest using your target language functionalities to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. Also see [Links](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to other languages.
-Donate
-------
+Support dear imgui
+------------------
-Can I donate to support the development of ImGui?
+How can I help financing further development of Dear ImGui?
-[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
+Your contributions are keeping the library alive. If you are an individual using dear imgui, please consider donating to enable me to spend more time improving the library.
-I'm currently an independent developer and your contributions are useful. I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui please consider making a contribution. One-off donations are also greatly appreciated. I am available for hire to work on or with ImGui. Thanks!
+Monthly donations via Patreon:
+ [![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui)
+
+One-off donations via PayPal:
+ [![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U)
+
+If your company uses dear imgui, please consider financial support (e.g. sponsoring a few weeks/months of development). I can invoice for private support, custom development etc. E-mail: omarcornut at gmail. Thanks!
Credits
-------
@@ -202,21 +230,24 @@ Embeds [stb_textedit.h, stb_truetype.h, stb_rectpack.h](https://github.com/nothi
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.
-Ongoing ImGui development is financially supported on [**Patreon**](http://www.patreon.com/imgui).
+Ongoing dear imgui development is financially supported on [**Patreon**](http://www.patreon.com/imgui).
Double-chocolate sponsors:
- Media Molecule
- Mobigame
- Insomniac Games (sponsored the gamepad/keyboard navigation branch)
- Aras Pranckevičius
+- Lizardcube
+- Greggman
Salty caramel supporters:
-- Jetha Chan, Wild Sheep Studio, Pastagames, Mārtiņš Možeiko, Daniel Collin, Recognition Robotics, Chris Genova, ikrima, Glenn Fiedler, Geoffrey Evans, Dakko Dakko.
+- Jetha Chan, Wild Sheep Studio, Pastagames, Mārtiņš Možeiko, Daniel Collin, Recognition Robotics, Chris Genova, ikrima, Glenn Fiedler, Geoffrey Evans, Dakko Dakko, Mercury Labs, Singularity Demo Group, Mischa Alff, Sebastien Ronsse.
Caramel supporters:
-- Michel Courtine, César Leblic, Dale Kim, Alex Evans, Rui Figueira, Paul Patrashcu, Jerome Lanquetot, Ctrl Alt Ninja, Paul Fleming, Neil Henning, Stephan Dilly, Neil Blakey-Milner, Aleksei, NeiloGD, Justin Paver, FiniteSol, Vincent Pancaldi, James Billot, Robin Hübner, furrtek, Eric, Simon Barratt, Game Atelier, Julian Bosch, Simon Lundmark, Vincent Hamm, Farhan Wali, Jeff Roberts, Matt Reyer, Colin Riley, Victor Martins, Josh Simmons, Garrett Hoofman, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, [Kit framework](http://svkonsult.se/kit), Josh Faust, Martin Donlon, Quinton, Felix.
+- Michel Courtine, César Leblic, Dale Kim, Alex Evans, Rui Figueira, Paul Patrashcu, Jerome Lanquetot, Ctrl Alt Ninja, Paul Fleming, Neil Henning, Stephan Dilly, Neil Blakey-Milner, Aleksei, NeiloGD, Justin Paver, FiniteSol, Vincent Pancaldi, James Billot, Robin Hübner, furrtek, Eric, Simon Barratt, Game Atelier, Julian Bosch, Simon Lundmark, Vincent Hamm, Farhan Wali, Jeff Roberts, Matt Reyer, Colin Riley, Victor Martins, Josh Simmons, Garrett Hoofman, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, Kit framework, Josh Faust, Martin Donlon, Quinton, Felix, Andrew Belt, Codecat, Cort Stratton, Claudio Canepa, Doug McNabb, Emmanuel Julien, Guillaume Chereau, Jeffrey Slutter, Jeremiah Deckard, r-lyeh, Roger Clark, Nekith, Joshua Fisher, Malte Hoffmann, Mustafa Karaalioglu, Merlyn Morgan-Graham, Per Vognsen, Fabian Giesen, Jan Staubach, Matt Hargett, John Shearer, Jesse Chounard, kingcoopa, Miloš Tošić.
And other supporters; thanks!
+(Please contact me or PR if you would like to be added or removed from this list)
License
-------
diff --git a/TODO.txt b/TODO.txt
new file mode 100644
index 000000000..3a6535a03
--- /dev/null
+++ b/TODO.txt
@@ -0,0 +1,264 @@
+dear imgui
+ISSUES & TODO LIST
+
+Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues/XXXX
+The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point they usually exist on the github issue tracker).
+It's mostly a bunch of personal notes, probably incomplete. Feel free to query if you have any questions.
+
+ - doc/test: add a proper documentation+regression testing system (#435)
+ - doc/test: checklist app to verify binding/integration of imgui (test inputs, rendering, callback, etc.).
+ - doc/tips: tips of the day: website? applet in imgui_club?
+ - project: folder or separate repository with maintained helpers (e.g. imgui_memory_editor.h, imgui_stl.h, maybe imgui_dock would be there?)
+
+ - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis). (#690)
+ - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass.
+ - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify.
+ - window: allow resizing of child windows (possibly given min/max for each axis?.)
+ - window: background options for child windows, border option (disable rounding).
+ - window: resizing from any sides? done. > need backends to honor mouse cursors properly. (#822)
+ - window: resize from borders: support some form of outer padding to make it easier to grab borders. (#822)
+ - window: begin with *p_open == false should return false.
+ - window: get size/pos helpers given names (see discussion in #249)
+ - window: a collapsed window can be stuck behind the main menu bar?
+ - window: when window is very small, prioritize resize button over close button.
+ - window: detect extra End() call that pop the "Debug" window out and assert at End() call site instead of at end of frame.
+ - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd.
+ - window: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon?
+ - window: expose contents size. (#1045)
+ - window: GetWindowSize() returns (0,0) when not calculated? (#1045)
+ - window: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate.
+!- scrolling: allow immediately effective change of scroll after Begin() if we haven't appended items yet.
+ - scrolling/clipping: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y). (2017-08-20: can't repro)
+
+ - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack.
+ - drawlist: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command).
+ - drawlist: primtiives/helpers to manipulate vertices post submission, so e.g. a quad/rect can be resized to fit later submitted content, _without_ using the ChannelSplit api
+ - drawlist: make it easier to toggle AA per primitive, so we can use e.g. non-AA fill + AA borders more naturally
+ - drawlist: non-AA strokes have gaps between points (#593, #288), especially RenderCheckmark().
+ - drawlist: would be good to be able to deep copy a draw list (ImVector= op?).
+ - drawlist/opt: AddRect() axis aligned pixel aligned (no-aa) could use 8 triangles instead of 16 and no normal calculation.
+
+ - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them.
+ - main: find a way to preserve relative orders of multiple reappearing windows (so an app toggling between "modes" e.g. fullscreen vs all tools) won't lose relative ordering.
+ - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes
+ - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode?
+ - main: rename the main "Debug" window to avoid ID collision with user who may want to use "Debug" with specific flags.
+
+ - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. (#395)
+ - widgets: clean up widgets internal toward exposing everything and stabilizing imgui_internals.h.
+ - widgets: add visauls for Disabled/ReadOnly mode and expose publicly (#211)
+ - widgets: add always-allow-overlap mode.
+ - widgets: alignment options in style (e.g. center Selectable, Right-Align within Button, etc.) #1260
+ - widgets: activate by identifier (trigger button, focus given id)
+
+ - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile.
+ - 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: access public fields via a non-callback API e.g. InputTextGetState("xxx") that may return NULL if not active.
+ - input text: flag to disable live update of the user buffer (also applies to float/int text input) (#701)
+ - input text: way to dynamically grow the buffer without forcing the user to initially allocate for worse case, e.g. more natural std::string (follow up on #200)
+ - input text: hover tooltip could show unclamped text
+ - input text: option to Tab after an Enter validation.
+ - input text: add ImGuiInputTextFlags_EnterToApply? (off #218)
+ - input text: easier ways to update buffer (from source char*) while owned. preserve some sort of cursor position for multi-line text.
+ - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725)
+ - input text: display bug when clicking a drag/slider after an input text in a different window has all-selected text (order dependant). actually a very old bug but no one appears to have noticed it.
+ - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc).
+ - input text multi-line: support for cut/paste without selection (cut/paste the current line)
+ - input text multi-line: line numbers? status bar? (follow up on #200)
+ - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725)
+ - input text multi-line: better horizontal scrolling support (#383, #1224)
+ - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position.
+ - input number: optional range min/max for Input*() functions
+ - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled)
+ - input number: use mouse wheel to step up/down
+ - 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: horizontal layout helper (#97)
+ - layout: horizontal flow until no space left (#404)
+ - layout: more generic alignment state (left/right/centered) for single items?
+ - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding.
+ - layout: BeginGroup() needs a border option. (~#1496)
+ - layout: vertical alignement of mixed height items (e.g. buttons) within a same line (#1284)
+
+ - columns: sizing policy (e.g. for each column: fixed size, %, fill, distribute default size among fills) (#513, #125)
+ - columns: add a conditional parameter to SetColumnOffset() (#513, #125)
+ - columns: headers. reorderable. (#513, #125)
+ - columns: optional sorting modifiers (up/down), sort list so sorting can be done multi-critera. notify user when sort order changed.
+ - columns: option to alternate background colors on odd/even scanlines.
+ - columns: allow columns to recurse.
+ - columns: allow a same columns set to be interrupted by e.g. CollapsingHeader and resume with columns in sync when moving them.
+ - 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/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets)
+
+!- color: the color conversion helpers/types are a mess and needs sorting out.
+ - color: (api breaking) ImGui::ColorConvertXXX functions should be loose ImColorConvertXX to match imgui_internals.h
+ - coloredit: it is still somehow awkward to copy colors around (unless going through Hex mode).
+
+ - plot: full featured plot/graph api w/ scrolling, zooming etc. all bell & whistle. why not!
+ - plot: PlotLines() should use the polygon-stroke facilities, less verticles (currently issues with averaging normals)
+ - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots)
+ - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value)
+ - plot: option/feature: draw the zero line
+ - plot: option/feature: draw grid, vertical markers
+ - plot: option/feature: draw unit
+ - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID)
+
+ - clipper: ability to force display 1 item in the list would be convenient (for patterns where we need to set active id etc.)
+ - clipper: ability to disable the clipping through a simple flag/bool.
+ - clipper: ability to run without knowing full count in advance.
+
+ - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319)
+
+ - dock: docking extension
+ - dock: dock out from a collapsing header? would work nicely but need emitting window to keep submitting the code.
+
+ - tabs: re-ordering, close buttons, context menu, persistent order (#261, #351)
+
+ - ext: stl-ish friendly extension (imgui_stl.h) that has wrapped for std::string, std::vector etc.
+
+ - button: provide a button that looks framed.
+ - 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 is odd.
+ - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt()
+ - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar).
+ - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate.
+ - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign)
+ - slider: precision dragging
+ - slider: step option (#1183)
+ - knob: rotating knob widget (#942)
+ - slider & drag: int data passing through a float
+ - drag float: up/down axis
+ - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits)
+
+ - combo: use clipper: make it easier to disable clipper with a single flag.
+ - combo: option for BeginCombo to not return true when unchanged (#1182)
+ - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203)
+ - listbox: multiple selection.
+ - listbox: unselect option (#1208)
+ - listbox: make it easier/more natural to implement range-select (need some sort of info/ref about the last clicked/focused item that user can translate to an index?) (wip stash)
+ - listbox: user may want to initial scroll to focus on the one selected value?
+ - listbox: expose hovered item for a basic ListBox
+ - listbox: keyboard navigation.
+ - listbox: scrolling should track modified selection.
+
+!- 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: reopening context menu at new position should be the behavior by default? (equivalent to internal OpenPopupEx() with reopen_existing=true) (~#1497)
+ - popups: if the popup functions took explicit ImGuiID it would allow the user to manage the scope of those ID. (#331)
+ - popups: clicking outside (to close popup) and holding shouldn't drag window below.
+ - popups: add variant using global identifier similar to Begin/End (#402)
+ - popups: border options. richer api like BeginChild() perhaps? (#197)
+ - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred direction" and may teleport when moving mouse.
+ - tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic.
+ - tooltip: allow tooltips with timers? or general timer policy? (instaneous vs timed)
+
+ - menus: calling BeginMenu() twice with a same name doesn't append as Begin() does for regular windows (#1207)
+ - statusbar: add a per-window status bar helper similar to what menubar does.
+ - shortcuts: local-style shortcut api, e.g. parse "&Save"
+ - shortcuts,menus: global-style shortcut api e.g. "Save (CTRL+S)" -> explicit flag for recursing into closed menu
+ - shortcuts: programmatically access shortcuts "Focus("&Save"))
+ - menus: menubars: main menu-bar could affect clamping of windows position (~ akin to modifying DisplayMin)
+ - menus: hovering from menu to menu on a menu-bar has 1 frame without any menu, which is a little annoying. ideally either 0 either longer.
+
+ - text: selectable text (for copy) as a generic feature (ItemFlags?)
+ - text: proper alignment options in imgui_internal.h
+ - text wrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249)
+ - 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 link/url button: underlined. should api expose an ID or use text contents as ID? which colors enum to use?
+
+ - tree node / optimization: avoid formatting when clipped.
+ - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling.
+ - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings?
+ - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits?
+ - 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.
+
+!- settings: expose enough to save/load .ini from RAM instead of fopen
+ - 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)
+ - stb: add defines to disable stb implementations
+
+!- style: better default styles. (#707)
+ - style: border types: out-screen, in-screen, etc. (#447)
+ - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding.
+ - style: add window shadow (fading away from the window. Paint-style calculation of vertices alpha after drawlist would be easier)
+ - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc.
+ - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation).
+ - style: global scale setting.
+ - style: WindowPadding needs to be EVEN as the 0.5 multiplier used on this value probably have a subtle effect on clip rectangle
+ - style: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438, #707, #1223)
+ - style: gradients fill (#1223) ~ 2 bg colors for each fill? tricky with rounded shapes and using textures for corners.
+ - style editor: color child window height expressed in multiple of line height.
+
+ - log: LogButtons() options for specifying depth and/or hiding depth slider
+ - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope)
+ - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard)
+ - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs.
+
+ - filters: set a current filter that tree node can automatically query to hide themselves
+ - filters: handle wildcards (with implicit leading/trailing *), regexps
+ - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb)
+
+ - drag and drop: add demo. (#143, #479)
+ - drag and drop: test with reordering nodes (in a list, or a tree node). (#143)
+ - drag and drop: test integrating with os drag and drop.
+ - node/graph editor (#306)
+ - pie menus patterns (#434)
+ - markup: simple markup language for color change? (#902)
+
+ - font: better vertical centering (based e.g on height of lowercase 'x'?). currently Roboto-Medium size 16 px isn't currently centered.
+ - font: free the Alpha buffer if user only requested RGBA.
+!- font: better CalcTextSizeA() API, at least for simple use cases. current one is horrible (perhaps have simple vs extended versions).
+ - font: enforce monospace through ImFontConfig (for icons?) + create dual ImFont output from same input, reusing rasterized data but with different glyphs/AdvanceX
+ - font: finish CustomRectRegister() to allow mapping unicode codepoint to custom texture data
+ - font: PushFontSize API (#1018)
+ - font/atlas: incremental updates
+ - font/atlas: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier.
+ - font/atlas: allow user to submit its own primitive to be rectpacked, and allow to map them on a Unicode point.
+ - font: MemoryTTF taking ownership confusing/not obvious, maybe default should be opposite?
+ - font/text: vertical and/or rotated text renderer (#705) - vertical is easier clipping wise
+ - font: imgui_freetype.h alternative renderer (#618)
+ - 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).
+ - 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?
+ - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize)
+ - font: fix AddRemapChar() to work before font has been built.
+ - font: (api breaking) removed "TTF" from symbol names. also because it now supports OTF.
+
+!- nav/keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing.
+ - nav: integrate navigation branch into master. (#787)
+ - nav: integrate/design keyboard controls.
+ - nav: once tab should go through most/all widgets (in submission order?)
+ - nav: currently cannot access menubar of a child window with Alt/menu key.
+ - nav: esc/enter default behavior for popups, e.g. be able to mark an "ok" or "cancel" button that would get triggered by those keys.
+ - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622)
+ - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame)
+ - focus: unable to use SetKeyboardFocusHere() on clipped widgets. (#787)
+ - inputs: rework IO system to be able to pass actual ordered/timestamped events. use an event queue? (~#335, #71)
+ - inputs: allow to pass explicit double-clicks if that's the only thing the user's backend can get them. (e.g. for windows by the CS_DBLCLKS style).
+ - inputs: support track pad style scrolling & slider edit.
+
+ - misc: idle refresh: expose cursor blink animation timer for backend to be able to lower framerate.
+ - 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: fix for compilation settings where stdcall isn't the default (e.g. vectorcall) (#1230)
+ - remote: make a system like RemoteImGui first-class citizen/project (#75)
+
+ - natvis: more the imgui.natvis file in a better location. perhaps reorganize extra_fonts/? (#1569)
+
+ - demo: add vertical separator demo
+ - demo: add virtual scrolling example?
+ - examples: directx9: save/restore device state more thoroughly.
+ - examples: window minimize, maximize (#583)
+ - examples: provide a zero-framerate/idle example.
+ - examples: glfw: could go idle when minimized? if (glfwGetWindowAttrib(window, GLFW_ICONIFIED)) { glfwWaitEvents(); continue; } // the problem is that DeltaTime will be super high on resume, perhaps provide a way to let impl know (#440)
+ - optimization: replace vsnprintf with stb_printf? or enable the defines/infrastructure to allow it (#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: use another hash function than crc32, e.g. FNV1a
+ - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)?
+ - optimization: turn some the various stack vectors into statically-sized arrays
diff --git a/examples/.gitignore b/examples/.gitignore
index 54d153983..9516dc7f6 100644
--- a/examples/.gitignore
+++ b/examples/.gitignore
@@ -25,6 +25,14 @@ opengl3_example/Release/*
opengl3_example/ipch/*
opengl3_example/x64/*
opengl3_example/opengl3_example
+sdl_opengl2_example/Debug/*
+sdl_opengl2_example/Release/*
+sdl_opengl2_example/ipch/*
+sdl_opengl2_example/x64/*
+sdl_opengl3_example/Debug/*
+sdl_opengl3_example/Release/*
+sdl_opengl3_example/ipch/*
+sdl_opengl3_example/x64/*
*.opensdf
*.sdf
*.suo
@@ -34,6 +42,8 @@ opengl3_example/opengl3_example
*.exe
*.pdb
*.ilk
+*.VC.db
+*.VC.VC.opendb
## Ini files
imgui.ini
diff --git a/examples/README.txt b/examples/README.txt
index 54be766a4..cf99c5dc3 100644
--- a/examples/README.txt
+++ b/examples/README.txt
@@ -1,30 +1,35 @@
-Those are standalone ready-to-build applications to demonstrate ImGui.
+Those are standalone ready-to-build applications to demonstrate Dear ImGui.
Binaries of some of those demos: http://www.miracleworld.net/imgui/binaries
-Third party languages and frameworks bindings: https://github.com/ocornut/imgui/wiki/Links
-(languages: C, .net, rust, D, Python, Lua..)
-(frameworks: DX12, Vulkan, Cinder, OpenGLES, openFrameworks, Cocos2d-x, SFML, Flexium, NanoRT, Irrlicht..)
-(extras: RemoteImGui, ImWindow, imgui_wm..)
+Third party languages and frameworks bindings:
+ https://github.com/ocornut/imgui/wiki/Links
+(languages: C, C#, ChaiScript, D, Go, Haxe, Odin, Python, Rust, Lua, Pascal)
+(frameworks: DX12, OpenGLES, FreeGlut, Cinder, Cocos2d-x, SFML, GML/GameMaker Studio, Irrlicht, Ogre,
+ OpenSceneGraph, openFrameworks, LOVE, NanoRT, Qt3d, SFML, Unreal Engine 4, etc.)
+(extras: RemoteImGui, ImWindow, imgui_wm, etc.)
+
TL;DR;
- Newcomers, read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup ImGui in your codebase.
- - Refer to 'opengl2_example' to LEARN how the library is setup, it is the simplest one.
- The other examples requires more boilerplate and are harder to read.
- - If you are using OpenGL in your application, probably use an opengl3_xxx backend.
- Mixing old fixed pipeline OpenGL2 and programmable pipeline OpenGL3+ isn't well supported by drivers.
- If you are using of the backend provided here, so you can copy the imgui_impl_xxx.cpp/h files
to your project and use them unmodified.
- - If you have your own engine, you probably want to start from one of the OpenGL example and adapt it to
- your engine, but you can read the other examples as well.
+ - To LEARN how the library is setup, you may refer to 'opengl2_example' because is the simplest one to read.
+ However, do NOT USE the 'opengl2_example' if your code is using any modern GL3+ calls.
+ Mixing old fixed-pipeline OpenGL2 and modern OpenGL3+ is going to make everything more complicated.
+ Read comments below for details. If you are not sure, in doubt, use 'opengl3_example'.
+ - If you have your own engine, you probably want to read a few of the examples first then adapt it to
+ your engine. Please note that if your engine is based on OpenGL/DirectX you can perfectly use the
+ existing rendering backends, don't feel forced to rewrite them with your own engine API, or you can
+ do that later when you already got things to work.
-ImGui is highly portable and only requires a few things to run:
+Dear ImGui is highly portable and only requires a few things to run and render.
- Providing mouse/keyboard inputs
- Load the font atlas texture into graphics memory
- Providing a render function to render indexed textured triangles
- Optional: clipboard support, mouse cursor supports, Windows IME support, etc.
So this is essentially what those examples are doing + the obligatory cruft for portability.
-Unfortunately in 2016 it is still tedious to create and maintain portable build files using external
+Unfortunately in 2018 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:
- Makefiles for Linux/OSX
@@ -34,24 +39,29 @@ Please let me 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.
-ImGui has zero frame of lag for most behaviors and one frame of lag for some behaviors.
-At 60 FPS your experience should be pleasant. Consider that OS mouse cursors are typically drawn through
-a specific hardware accelerated route and may feel smoother than other GPU rendered contents. You may
-experiment with the io.MouseDrawCursor flag to request ImGui to draw a mouse cursor itself, to visualize
-the lag between a hardware cursor and a software cursor. It might be beneficial to the user experience
-to switch to a software rendered cursor when an interactive drag is in progress.
-Also note that some setup or GPU drivers may be causing extra lag (possibly by enforcing triple buffering),
-leaving you with no option but sadness/anger (Intel GPU drivers were reported as such).
+Dear ImGui has zero to one frame of lag for most behaviors, at 60 FPS your experience should be pleasant.
+Consider that OS mouse cursors are typically drawn through a specific hardware accelerated route and may
+feel smoother than other GPU rendered contents. You may experiment with the io.MouseDrawCursor flag to
+request ImGui to draw a mouse cursor itself, to visualize the lag between a hardware cursor and a software
+cursor. It might be beneficial to the user experience to switch to a software rendered cursor when an
+interactive drag is in progress.
+Also note that some setup or GPU drivers may be causing extra lag (possibly by enforcing triple buffering),
+leaving you with little option but sadness (Intel GPU drivers were reported as such).
+
opengl2_example/
- GLFW + OpenGL example (old fixed pipeline).
- This is simple to read. Prefer following this example to learn how ImGui works!
- (You might be able to use this code in a GL3/GL4 context but make sure you disable the programmable
- pipeline by calling "glUseProgram(0)" before ImGui::Render.)
+ **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+ **Prefer using the code in the opengl3_example/ folder**
+ GLFW + OpenGL example (legacy, fixed pipeline).
+ This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
+ If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
+ complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
+ confuse your GPU driver.
opengl3_example/
GLFW + OpenGL example (programmable pipeline, binding modern functions with GL3W).
- This uses more modern OpenGL calls and custom shaders. It's more messy.
+ This uses more modern OpenGL calls and custom shaders.
+ Prefer using that if you are using modern OpenGL in your application (anything with shaders, vbo, vao, etc.).
directx9_example/
DirectX9 example, Windows only.
@@ -70,10 +80,18 @@ apple_example/
Synergy keyboard integration is rather hacky.
sdl_opengl2_example/
- SDL2 + OpenGL example (old fixed pipeline).
+ **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+ **Prefer using the code in the sdl_opengl3_example/ folder**
+ SDL2 + OpenGL example (legacy, fixed pipeline).
+ This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
+ If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
+ complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
+ confuse your GPU driver.
sdl_opengl3_example/
SDL2 + OpenGL3 example.
+ This uses more modern OpenGL calls and custom shaders.
+ Prefer using that if you are using modern OpenGL in your application (anything with shaders, vbo, vao, etc.).
allegro5_example/
Allegro 5 example.
@@ -85,3 +103,4 @@ vulkan_example/
Vulkan example.
This is quite long and tedious, because: Vulkan.
+TODO: Apple, SDL GL2/GL3, Allegro, Marmalade, Vulkan examples do not honor the io.WantMoveMouse flag.
diff --git a/examples/allegro5_example/README.md b/examples/allegro5_example/README.md
index d891982b7..dcd83b8a9 100644
--- a/examples/allegro5_example/README.md
+++ b/examples/allegro5_example/README.md
@@ -4,7 +4,7 @@
- On Ubuntu 14.04+
```bash
-g++ -I ../imgui main.cpp imgui_impl_a5.cpp ../imgui/imgui*.cpp -lallegro -lallegro_primitives
+g++ -I ../.. main.cpp imgui_impl_a5.cpp ../../imgui*.cpp -lallegro -lallegro_primitives -o allegro5_example
```
- On Windows with Visual Studio's CLI
diff --git a/examples/allegro5_example/imgui_impl_a5.cpp b/examples/allegro5_example/imgui_impl_a5.cpp
index 9a04ff9c1..62f7af672 100644
--- a/examples/allegro5_example/imgui_impl_a5.cpp
+++ b/examples/allegro5_example/imgui_impl_a5.cpp
@@ -28,8 +28,6 @@ static double g_Time = 0.0;
static ALLEGRO_MOUSE_CURSOR* g_MouseCursorInvisible = NULL;
static ALLEGRO_VERTEX_DECL* g_VertexDecl = NULL;
-#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
-
struct ImDrawVertAllegro
{
ImVec2 pos;
@@ -162,9 +160,9 @@ bool ImGui_ImplA5_Init(ALLEGRO_DISPLAY* display)
// We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion.
ALLEGRO_VERTEX_ELEMENT elems[] =
{
- { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, OFFSETOF(ImDrawVertAllegro, pos) },
- { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, OFFSETOF(ImDrawVertAllegro, uv) },
- { ALLEGRO_PRIM_COLOR_ATTR, 0, OFFSETOF(ImDrawVertAllegro, col) },
+ { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, pos) },
+ { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, uv) },
+ { ALLEGRO_PRIM_COLOR_ATTR, 0, IM_OFFSETOF(ImDrawVertAllegro, col) },
{ 0, 0, 0 }
};
g_VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro));
@@ -179,6 +177,7 @@ bool ImGui_ImplA5_Init(ALLEGRO_DISPLAY* display)
io.KeyMap[ImGuiKey_PageDown] = ALLEGRO_KEY_PGDN;
io.KeyMap[ImGuiKey_Home] = ALLEGRO_KEY_HOME;
io.KeyMap[ImGuiKey_End] = ALLEGRO_KEY_END;
+ io.KeyMap[ImGuiKey_Insert] = ALLEGRO_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = ALLEGRO_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = ALLEGRO_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = ALLEGRO_KEY_ENTER;
@@ -204,6 +203,10 @@ void ImGui_ImplA5_Shutdown()
ImGui::Shutdown();
}
+// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
bool ImGui_ImplA5_ProcessEvent(ALLEGRO_EVENT *ev)
{
ImGuiIO &io = ImGui::GetIO();
@@ -212,6 +215,7 @@ bool ImGui_ImplA5_ProcessEvent(ALLEGRO_EVENT *ev)
{
case ALLEGRO_EVENT_MOUSE_AXES:
io.MouseWheel += ev->mouse.dz;
+ io.MouseWheelH += ev->mouse.dw;
return true;
case ALLEGRO_EVENT_KEY_CHAR:
if (ev->keyboard.display == g_Display)
@@ -227,7 +231,6 @@ bool ImGui_ImplA5_ProcessEvent(ALLEGRO_EVENT *ev)
return false;
}
-
void ImGui_ImplA5_NewFrame()
{
if (!g_Texture)
@@ -262,7 +265,7 @@ void ImGui_ImplA5_NewFrame()
}
else
{
- io.MousePos = ImVec2(-1, -1);
+ io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
}
al_get_mouse_state(&mouse);
@@ -290,6 +293,6 @@ void ImGui_ImplA5_NewFrame()
al_set_system_mouse_cursor(g_Display, cursor_id);
}
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/allegro5_example/main.cpp b/examples/allegro5_example/main.cpp
index a8cd156ba..3c9c9770e 100644
--- a/examples/allegro5_example/main.cpp
+++ b/examples/allegro5_example/main.cpp
@@ -25,29 +25,44 @@ int main(int, char**)
// Setup ImGui binding
ImGui_ImplA5_Init(display);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_color = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
bool running = true;
while (running)
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
ALLEGRO_EVENT ev;
while (al_get_next_event(queue, &ev))
{
ImGui_ImplA5_ProcessEvent(&ev);
- if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) running = false;
+ if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
+ running = false;
if (ev.type == ALLEGRO_EVENT_DISPLAY_RESIZE)
{
ImGui_ImplA5_InvalidateDeviceObjects();
@@ -57,32 +72,33 @@ int main(int, char**)
}
ImGui_ImplA5_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
- static float f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_color);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
- ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f/ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
+ static float f = 0.0f;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
+ ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
diff --git a/examples/apple_example/imguiex-ios/debug_hud.cpp b/examples/apple_example/imguiex-ios/debug_hud.cpp
index c75938a39..c81f273d1 100644
--- a/examples/apple_example/imguiex-ios/debug_hud.cpp
+++ b/examples/apple_example/imguiex-ios/debug_hud.cpp
@@ -9,7 +9,7 @@
void DebugHUD_InitDefaults( DebugHUD *hud )
{
- hud->show_test_window = true;
+ hud->show_demo_window = true;
hud->show_example_window = true;
hud->rotation_speed = 15.0f;
@@ -24,19 +24,18 @@ void DebugHUD_InitDefaults( DebugHUD *hud )
hud->cubeColor2[3] = 1.0f;
}
-void DebugHUD_DoInterface( DebugHUD *hud )
+void DebugHUD_DoInterface(DebugHUD *hud)
{
- if (hud->show_test_window)
+ if (hud->show_demo_window)
{
- ImGui::SetNextWindowPos( ImVec2( 400, 20 ), ImGuiSetCond_FirstUseEver );
- ImGui::ShowTestWindow( &hud->show_test_window );
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&hud->show_demo_window );
}
if (hud->show_example_window)
{
- ImGui::SetNextWindowPos( ImVec2( 20, 20 ), ImGuiSetCond_FirstUseEver );
- ImGui::SetNextWindowSize( ImVec2( 350, 200 ), ImGuiSetCond_FirstUseEver );
ImGui::Begin("Another Window", &hud->show_example_window);
+ ImGui::Text("Hello from another window!");
ImGui::ColorEdit3("Cube 1 Color", hud->cubeColor1);
ImGui::ColorEdit3("Cube 2 Color", hud->cubeColor2);
ImGui::SliderFloat("Rotation Speed", &hud->rotation_speed, 0.0f, 200.0f);
diff --git a/examples/apple_example/imguiex-ios/debug_hud.h b/examples/apple_example/imguiex-ios/debug_hud.h
index 17122f5e3..601376c3e 100644
--- a/examples/apple_example/imguiex-ios/debug_hud.h
+++ b/examples/apple_example/imguiex-ios/debug_hud.h
@@ -6,7 +6,7 @@
typedef struct DebugHUD
{
- bool show_test_window;
+ bool show_demo_window;
bool show_example_window;
float rotation_speed;
float cubeColor1[4];
diff --git a/examples/apple_example/imguiex-ios/imgui_impl_ios.mm b/examples/apple_example/imguiex-ios/imgui_impl_ios.mm
index 893dbf977..5b56d3ca3 100644
--- a/examples/apple_example/imguiex-ios/imgui_impl_ios.mm
+++ b/examples/apple_example/imguiex-ios/imgui_impl_ios.mm
@@ -488,6 +488,7 @@ void ImGui_ClipboardCallback(uSynergyCookie cookie, enum uSynergyClipboardFormat
io.KeyMap[ImGuiKey_DownArrow] = kVK_DownArrow+1;
io.KeyMap[ImGuiKey_Home] = kVK_Home+1;
io.KeyMap[ImGuiKey_End] = kVK_End+1;
+ io.KeyMap[ImGuiKey_Insert] = kVK_Help+1;
io.KeyMap[ImGuiKey_Delete] = kVK_ForwardDelete+1;
io.KeyMap[ImGuiKey_Backspace] = kVK_Delete+1;
io.KeyMap[ImGuiKey_Enter] = kVK_Return+1;
@@ -586,9 +587,9 @@ void ImGui_ClipboardCallback(uSynergyCookie cookie, enum uSynergyClipboardFormat
io.MouseDown[i] = g_MousePressed[i];
}
- // This is an arbitrary scaling factor that works for me. Not sure what units these
- // mousewheel values from synergy are supposed to be in
+ // This is an arbitrary scaling factor that works for me. Not sure what units these mousewheel values from synergy are supposed to be in.
io.MouseWheel = g_mouseWheelY / 500.0;
+ io.MouseWheelH = g_mouseWheelX / 500.0;
}
else
{
@@ -617,6 +618,7 @@ void ImGui_ClipboardCallback(uSynergyCookie cookie, enum uSynergyClipboardFormat
static void ImGui_ImplIOS_RenderDrawLists (ImDrawData *draw_data)
{
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
+ // FIXME: Backport changes from imgui_impl_glfw_gl3.cpp
GLint last_program, last_texture;
glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
@@ -792,11 +794,10 @@ bool ImGui_ImplIOS_CreateDeviceObjects()
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
-#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
- glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
- glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
- glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
-#undef OFFSETOF
+ glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
+ glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
+ glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
+
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
diff --git a/examples/directx10_example/directx10_example.vcxproj b/examples/directx10_example/directx10_example.vcxproj
index c4f15c569..3a403518e 100644
--- a/examples/directx10_example/directx10_example.vcxproj
+++ b/examples/directx10_example/directx10_example.vcxproj
@@ -110,6 +110,7 @@
truetrue..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;
+ falsetrue
@@ -127,6 +128,7 @@
truetrue..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;
+ falsetrue
@@ -151,6 +153,7 @@
+
diff --git a/examples/directx10_example/directx10_example.vcxproj.filters b/examples/directx10_example/directx10_example.vcxproj.filters
index 15e924c44..5a358463e 100644
--- a/examples/directx10_example/directx10_example.vcxproj.filters
+++ b/examples/directx10_example/directx10_example.vcxproj.filters
@@ -41,5 +41,8 @@
+
+ sources
+
\ No newline at end of file
diff --git a/examples/directx10_example/imgui_impl_dx10.cpp b/examples/directx10_example/imgui_impl_dx10.cpp
index 5bda68df2..14a47c4af 100644
--- a/examples/directx10_example/imgui_impl_dx10.cpp
+++ b/examples/directx10_example/imgui_impl_dx10.cpp
@@ -225,49 +225,78 @@ void ImGui_ImplDX10_RenderDrawLists(ImDrawData* draw_data)
ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
-IMGUI_API LRESULT ImGui_ImplDX10_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
+static bool IsAnyMouseButtonDown()
+{
+ ImGuiIO& io = ImGui::GetIO();
+ for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
+ if (io.MouseDown[n])
+ return true;
+ return false;
+}
+
+// Process Win32 mouse/keyboard inputs.
+// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
+// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds.
+// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
+IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
ImGuiIO& io = ImGui::GetIO();
switch (msg)
{
- case WM_LBUTTONDOWN:
- io.MouseDown[0] = true;
- return true;
+ case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
+ case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
+ case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
+ {
+ int button = 0;
+ if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
+ if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
+ if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
+ if (!IsAnyMouseButtonDown() && GetCapture() == NULL)
+ SetCapture(hwnd);
+ io.MouseDown[button] = true;
+ return 0;
+ }
case WM_LBUTTONUP:
- io.MouseDown[0] = false;
- return true;
- case WM_RBUTTONDOWN:
- io.MouseDown[1] = true;
- return true;
case WM_RBUTTONUP:
- io.MouseDown[1] = false;
- return true;
- case WM_MBUTTONDOWN:
- io.MouseDown[2] = true;
- return true;
case WM_MBUTTONUP:
- io.MouseDown[2] = false;
- return true;
+ {
+ int button = 0;
+ if (msg == WM_LBUTTONUP) button = 0;
+ if (msg == WM_RBUTTONUP) button = 1;
+ if (msg == WM_MBUTTONUP) button = 2;
+ io.MouseDown[button] = false;
+ if (!IsAnyMouseButtonDown() && GetCapture() == hwnd)
+ ReleaseCapture();
+ return 0;
+ }
case WM_MOUSEWHEEL:
io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
- return true;
+ return 0;
+ case WM_MOUSEHWHEEL:
+ io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
+ return 0;
case WM_MOUSEMOVE:
io.MousePos.x = (signed short)(lParam);
io.MousePos.y = (signed short)(lParam >> 16);
- return true;
+ return 0;
case WM_KEYDOWN:
+ case WM_SYSKEYDOWN:
if (wParam < 256)
io.KeysDown[wParam] = 1;
- return true;
+ return 0;
case WM_KEYUP:
+ case WM_SYSKEYUP:
if (wParam < 256)
io.KeysDown[wParam] = 0;
- return true;
+ return 0;
case WM_CHAR:
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
if (wParam > 0 && wParam < 0x10000)
io.AddInputCharacter((unsigned short)wParam);
- return true;
+ return 0;
}
return 0;
}
@@ -484,7 +513,7 @@ void ImGui_ImplDX10_InvalidateDeviceObjects()
return;
if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
- if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = 0; }
+ if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
@@ -519,6 +548,7 @@ bool ImGui_ImplDX10_Init(void* hwnd, ID3D10Device* device)
io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
io.KeyMap[ImGuiKey_Home] = VK_HOME;
io.KeyMap[ImGuiKey_End] = VK_END;
+ io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
@@ -572,10 +602,18 @@ void ImGui_ImplDX10_NewFrame()
// io.MouseDown : filled by WM_*BUTTON* events
// io.MouseWheel : filled by WM_MOUSEWHEEL events
+ // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
+ if (io.WantMoveMouse)
+ {
+ POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
+ ClientToScreen(g_hWnd, &pos);
+ SetCursorPos(pos.x, pos.y);
+ }
+
// Hide OS mouse cursor if ImGui is drawing it
if (io.MouseDrawCursor)
SetCursor(NULL);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/directx10_example/imgui_impl_dx10.h b/examples/directx10_example/imgui_impl_dx10.h
index 7877e775a..38a03a27e 100644
--- a/examples/directx10_example/imgui_impl_dx10.h
+++ b/examples/directx10_example/imgui_impl_dx10.h
@@ -20,5 +20,5 @@ IMGUI_API bool ImGui_ImplDX10_CreateDeviceObjects();
// You may or not need this for your implementation, but it can serve as reference for handling inputs.
// Commented out to avoid dragging dependencies on types. You can copy the extern declaration in your code.
/*
-IMGUI_API LRESULT ImGui_ImplDX10_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
*/
diff --git a/examples/directx10_example/main.cpp b/examples/directx10_example/main.cpp
index fb98cad16..38f4054ea 100644
--- a/examples/directx10_example/main.cpp
+++ b/examples/directx10_example/main.cpp
@@ -27,7 +27,6 @@ void CreateRenderTarget()
render_target_view_desc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer);
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
- g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
pBackBuffer->Release();
}
@@ -74,10 +73,10 @@ void CleanupDeviceD3D()
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
}
-extern LRESULT ImGui_ImplDX10_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- if (ImGui_ImplDX10_WndProcHandler(hWnd, msg, wParam, lParam))
+ if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
@@ -125,25 +124,39 @@ int main(int, char**)
// Setup ImGui binding
ImGui_ImplDX10_Init(hwnd, g_pd3dDevice);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_col = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
@@ -152,38 +165,42 @@ int main(int, char**)
}
ImGui_ImplDX10_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_col);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
- g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_col);
+ g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
+ g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color);
ImGui::Render();
- g_pSwapChain->Present(0, 0);
+
+ g_pSwapChain->Present(1, 0); // Present with vsync
+ //g_pSwapChain->Present(0, 0); // Present without vsync
}
ImGui_ImplDX10_Shutdown();
diff --git a/examples/directx11_example/directx11_example.vcxproj b/examples/directx11_example/directx11_example.vcxproj
index 944c8e863..347b4f007 100644
--- a/examples/directx11_example/directx11_example.vcxproj
+++ b/examples/directx11_example/directx11_example.vcxproj
@@ -110,6 +110,7 @@
truetrue..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;
+ falsetrue
@@ -127,6 +128,7 @@
truetrue..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;
+ falsetrue
@@ -151,6 +153,7 @@
+
diff --git a/examples/directx11_example/directx11_example.vcxproj.filters b/examples/directx11_example/directx11_example.vcxproj.filters
index 5cd0ca415..a79484cc1 100644
--- a/examples/directx11_example/directx11_example.vcxproj.filters
+++ b/examples/directx11_example/directx11_example.vcxproj.filters
@@ -41,5 +41,8 @@
+
+ sources
+
\ No newline at end of file
diff --git a/examples/directx11_example/imgui_impl_dx11.cpp b/examples/directx11_example/imgui_impl_dx11.cpp
index 0a3722ebc..4963fc12e 100644
--- a/examples/directx11_example/imgui_impl_dx11.cpp
+++ b/examples/directx11_example/imgui_impl_dx11.cpp
@@ -232,49 +232,78 @@ void ImGui_ImplDX11_RenderDrawLists(ImDrawData* draw_data)
ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
-IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
+static bool IsAnyMouseButtonDown()
+{
+ ImGuiIO& io = ImGui::GetIO();
+ for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
+ if (io.MouseDown[n])
+ return true;
+ return false;
+}
+
+// Process Win32 mouse/keyboard inputs.
+// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
+// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds.
+// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
+IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
ImGuiIO& io = ImGui::GetIO();
switch (msg)
{
- case WM_LBUTTONDOWN:
- io.MouseDown[0] = true;
- return true;
+ case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
+ case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
+ case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
+ {
+ int button = 0;
+ if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
+ if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
+ if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
+ if (!IsAnyMouseButtonDown() && GetCapture() == NULL)
+ SetCapture(hwnd);
+ io.MouseDown[button] = true;
+ return 0;
+ }
case WM_LBUTTONUP:
- io.MouseDown[0] = false;
- return true;
- case WM_RBUTTONDOWN:
- io.MouseDown[1] = true;
- return true;
case WM_RBUTTONUP:
- io.MouseDown[1] = false;
- return true;
- case WM_MBUTTONDOWN:
- io.MouseDown[2] = true;
- return true;
case WM_MBUTTONUP:
- io.MouseDown[2] = false;
- return true;
+ {
+ int button = 0;
+ if (msg == WM_LBUTTONUP) button = 0;
+ if (msg == WM_RBUTTONUP) button = 1;
+ if (msg == WM_MBUTTONUP) button = 2;
+ io.MouseDown[button] = false;
+ if (!IsAnyMouseButtonDown() && GetCapture() == hwnd)
+ ReleaseCapture();
+ return 0;
+ }
case WM_MOUSEWHEEL:
io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
- return true;
+ return 0;
+ case WM_MOUSEHWHEEL:
+ io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
+ return 0;
case WM_MOUSEMOVE:
io.MousePos.x = (signed short)(lParam);
io.MousePos.y = (signed short)(lParam >> 16);
- return true;
+ return 0;
case WM_KEYDOWN:
+ case WM_SYSKEYDOWN:
if (wParam < 256)
io.KeysDown[wParam] = 1;
- return true;
+ return 0;
case WM_KEYUP:
+ case WM_SYSKEYUP:
if (wParam < 256)
io.KeysDown[wParam] = 0;
- return true;
+ return 0;
case WM_CHAR:
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
if (wParam > 0 && wParam < 0x10000)
io.AddInputCharacter((unsigned short)wParam);
- return true;
+ return 0;
}
return 0;
}
@@ -485,7 +514,7 @@ void ImGui_ImplDX11_InvalidateDeviceObjects()
return;
if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; }
- if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = 0; }
+ if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
if (g_pIB) { g_pIB->Release(); g_pIB = NULL; }
if (g_pVB) { g_pVB->Release(); g_pVB = NULL; }
@@ -521,6 +550,7 @@ bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContex
io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
io.KeyMap[ImGuiKey_Home] = VK_HOME;
io.KeyMap[ImGuiKey_End] = VK_END;
+ io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
@@ -575,10 +605,18 @@ void ImGui_ImplDX11_NewFrame()
// io.MouseDown : filled by WM_*BUTTON* events
// io.MouseWheel : filled by WM_MOUSEWHEEL events
+ // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
+ if (io.WantMoveMouse)
+ {
+ POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
+ ClientToScreen(g_hWnd, &pos);
+ SetCursorPos(pos.x, pos.y);
+ }
+
// Hide OS mouse cursor if ImGui is drawing it
if (io.MouseDrawCursor)
SetCursor(NULL);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/directx11_example/imgui_impl_dx11.h b/examples/directx11_example/imgui_impl_dx11.h
index 7d6f710fd..36066746d 100644
--- a/examples/directx11_example/imgui_impl_dx11.h
+++ b/examples/directx11_example/imgui_impl_dx11.h
@@ -21,5 +21,5 @@ IMGUI_API bool ImGui_ImplDX11_CreateDeviceObjects();
// You may or not need this for your implementation, but it can serve as reference for handling inputs.
// Commented out to avoid dragging dependencies on types. You can copy the extern declaration in your code.
/*
-IMGUI_API LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
*/
diff --git a/examples/directx11_example/main.cpp b/examples/directx11_example/main.cpp
index e3fe5aa71..79e7bb169 100644
--- a/examples/directx11_example/main.cpp
+++ b/examples/directx11_example/main.cpp
@@ -27,7 +27,6 @@ void CreateRenderTarget()
render_target_view_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
- g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
pBackBuffer->Release();
}
@@ -60,8 +59,8 @@ HRESULT CreateDeviceD3D(HWND hWnd)
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
D3D_FEATURE_LEVEL featureLevel;
- const D3D_FEATURE_LEVEL featureLevelArray[1] = { D3D_FEATURE_LEVEL_11_0, };
- if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 1, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
+ const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, };
+ if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK)
return E_FAIL;
CreateRenderTarget();
@@ -77,10 +76,10 @@ void CleanupDeviceD3D()
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
}
-extern LRESULT ImGui_ImplDX11_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- if (ImGui_ImplDX11_WndProcHandler(hWnd, msg, wParam, lParam))
+ if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
@@ -128,25 +127,39 @@ int main(int, char**)
// Setup ImGui binding
ImGui_ImplDX11_Init(hwnd, g_pd3dDevice, g_pd3dDeviceContext);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_col = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
@@ -155,38 +168,42 @@ int main(int, char**)
}
ImGui_ImplDX11_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_col);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); // Normally user code doesn't need/want to call it because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
- g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_col);
+ g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
+ g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color);
ImGui::Render();
- g_pSwapChain->Present(0, 0);
+
+ g_pSwapChain->Present(1, 0); // Present with vsync
+ //g_pSwapChain->Present(0, 0); // Present without vsync
}
ImGui_ImplDX11_Shutdown();
diff --git a/examples/directx9_example/directx9_example.vcxproj b/examples/directx9_example/directx9_example.vcxproj
index c10731dee..e63bd35b5 100644
--- a/examples/directx9_example/directx9_example.vcxproj
+++ b/examples/directx9_example/directx9_example.vcxproj
@@ -110,6 +110,7 @@
truetrue..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;
+ falsetrue
@@ -127,6 +128,7 @@
truetrue..\..;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include;
+ falsetrue
@@ -151,6 +153,7 @@
+
diff --git a/examples/directx9_example/directx9_example.vcxproj.filters b/examples/directx9_example/directx9_example.vcxproj.filters
index 5cf028343..b0843b397 100644
--- a/examples/directx9_example/directx9_example.vcxproj.filters
+++ b/examples/directx9_example/directx9_example.vcxproj.filters
@@ -42,5 +42,8 @@
+
+ sources
+
\ No newline at end of file
diff --git a/examples/directx9_example/imgui_impl_dx9.cpp b/examples/directx9_example/imgui_impl_dx9.cpp
index 93472f65b..a4e676914 100644
--- a/examples/directx9_example/imgui_impl_dx9.cpp
+++ b/examples/directx9_example/imgui_impl_dx9.cpp
@@ -171,49 +171,78 @@ void ImGui_ImplDX9_RenderDrawLists(ImDrawData* draw_data)
d3d9_state_block->Release();
}
-IMGUI_API LRESULT ImGui_ImplDX9_WndProcHandler(HWND, UINT msg, WPARAM wParam, LPARAM lParam)
+static bool IsAnyMouseButtonDown()
+{
+ ImGuiIO& io = ImGui::GetIO();
+ for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
+ if (io.MouseDown[n])
+ return true;
+ return false;
+}
+
+// Process Win32 mouse/keyboard inputs.
+// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
+// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds.
+// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
+IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
ImGuiIO& io = ImGui::GetIO();
switch (msg)
{
- case WM_LBUTTONDOWN:
- io.MouseDown[0] = true;
- return true;
+ case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
+ case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
+ case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
+ {
+ int button = 0;
+ if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0;
+ if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1;
+ if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2;
+ if (!IsAnyMouseButtonDown() && GetCapture() == NULL)
+ SetCapture(hwnd);
+ io.MouseDown[button] = true;
+ return 0;
+ }
case WM_LBUTTONUP:
- io.MouseDown[0] = false;
- return true;
- case WM_RBUTTONDOWN:
- io.MouseDown[1] = true;
- return true;
case WM_RBUTTONUP:
- io.MouseDown[1] = false;
- return true;
- case WM_MBUTTONDOWN:
- io.MouseDown[2] = true;
- return true;
case WM_MBUTTONUP:
- io.MouseDown[2] = false;
- return true;
+ {
+ int button = 0;
+ if (msg == WM_LBUTTONUP) button = 0;
+ if (msg == WM_RBUTTONUP) button = 1;
+ if (msg == WM_MBUTTONUP) button = 2;
+ io.MouseDown[button] = false;
+ if (!IsAnyMouseButtonDown() && GetCapture() == hwnd)
+ ReleaseCapture();
+ return 0;
+ }
case WM_MOUSEWHEEL:
io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
- return true;
+ return 0;
+ case WM_MOUSEHWHEEL:
+ io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f;
+ return 0;
case WM_MOUSEMOVE:
io.MousePos.x = (signed short)(lParam);
io.MousePos.y = (signed short)(lParam >> 16);
- return true;
+ return 0;
case WM_KEYDOWN:
+ case WM_SYSKEYDOWN:
if (wParam < 256)
io.KeysDown[wParam] = 1;
- return true;
+ return 0;
case WM_KEYUP:
+ case WM_SYSKEYUP:
if (wParam < 256)
io.KeysDown[wParam] = 0;
- return true;
+ return 0;
case WM_CHAR:
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
if (wParam > 0 && wParam < 0x10000)
io.AddInputCharacter((unsigned short)wParam);
- return true;
+ return 0;
}
return 0;
}
@@ -238,6 +267,7 @@ bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device)
io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
io.KeyMap[ImGuiKey_Home] = VK_HOME;
io.KeyMap[ImGuiKey_End] = VK_END;
+ io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
@@ -311,12 +341,14 @@ void ImGui_ImplDX9_InvalidateDeviceObjects()
g_pIB->Release();
g_pIB = NULL;
}
- if (LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)ImGui::GetIO().Fonts->TexID)
- {
- tex->Release();
- ImGui::GetIO().Fonts->TexID = 0;
- }
+
+ // At this point note that we set ImGui::GetIO().Fonts->TexID to be == g_FontTexture, so clear both.
+ ImGuiIO& io = ImGui::GetIO();
+ IM_ASSERT(g_FontTexture == io.Fonts->TexID);
+ if (g_FontTexture)
+ g_FontTexture->Release();
g_FontTexture = NULL;
+ io.Fonts->TexID = NULL;
}
void ImGui_ImplDX9_NewFrame()
@@ -347,10 +379,18 @@ void ImGui_ImplDX9_NewFrame()
// io.MouseDown : filled by WM_*BUTTON* events
// io.MouseWheel : filled by WM_MOUSEWHEEL events
+ // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
+ if (io.WantMoveMouse)
+ {
+ POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
+ ClientToScreen(g_hWnd, &pos);
+ SetCursorPos(pos.x, pos.y);
+ }
+
// Hide OS mouse cursor if ImGui is drawing it
if (io.MouseDrawCursor)
SetCursor(NULL);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/directx9_example/imgui_impl_dx9.h b/examples/directx9_example/imgui_impl_dx9.h
index 090ca9987..acaed5318 100644
--- a/examples/directx9_example/imgui_impl_dx9.h
+++ b/examples/directx9_example/imgui_impl_dx9.h
@@ -20,5 +20,5 @@ IMGUI_API bool ImGui_ImplDX9_CreateDeviceObjects();
// You may or not need this for your implementation, but it can serve as reference for handling inputs.
// Commented out to avoid dragging dependencies on types. You can copy the extern declaration in your code.
/*
-IMGUI_API LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
*/
diff --git a/examples/directx9_example/main.cpp b/examples/directx9_example/main.cpp
index babee5fd4..09a109d98 100644
--- a/examples/directx9_example/main.cpp
+++ b/examples/directx9_example/main.cpp
@@ -12,10 +12,10 @@
static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
static D3DPRESENT_PARAMETERS g_d3dpp;
-extern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- if (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam))
+ if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
@@ -63,7 +63,8 @@ int main(int, char**)
g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
g_d3dpp.EnableAutoDepthStencil = TRUE;
g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
- g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
+ g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync
+ //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate
// Create the D3DDevice
if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
@@ -76,19 +77,29 @@ int main(int, char**)
// Setup ImGui binding
ImGui_ImplDX9_Init(hwnd, g_pd3dDevice);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_col = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
@@ -97,6 +108,10 @@ int main(int, char**)
UpdateWindow(hwnd);
while (msg.message != WM_QUIT)
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
@@ -105,46 +120,56 @@ int main(int, char**)
}
ImGui_ImplDX9_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_col);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
+ ImGui::EndFrame();
g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
- D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_col.x*255.0f), (int)(clear_col.y*255.0f), (int)(clear_col.z*255.0f), (int)(clear_col.w*255.0f));
+ D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f));
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
if (g_pd3dDevice->BeginScene() >= 0)
{
ImGui::Render();
g_pd3dDevice->EndScene();
}
- g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
+ HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
+
+ // Handle loss of D3D9 device
+ if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
+ {
+ ImGui_ImplDX9_InvalidateDeviceObjects();
+ g_pd3dDevice->Reset(&g_d3dpp);
+ ImGui_ImplDX9_CreateDeviceObjects();
+ }
}
ImGui_ImplDX9_Shutdown();
diff --git a/examples/libs/imgui.natvis b/examples/libs/imgui.natvis
new file mode 100644
index 000000000..38c676c75
--- /dev/null
+++ b/examples/libs/imgui.natvis
@@ -0,0 +1,40 @@
+
+
+
+
+
+
+
+ {{Size={Size} Capacity={Capacity}}}
+
+
+ Size
+ Data
+
+
+
+
+
+ {{x={x,g} y={y,g}}}
+
+
+
+ {{x={x,g} y={y,g} z={z,g} w={w,g}}}
+
+
+
+ {{Min=({Min.x,g} {Min.y,g}) Max=({Max.x,g} {Max.y,g}) Size=({Max.x-Min.x,g} {Max.y-Min.y,g})}}
+
+ Min
+ Max
+ Max.x - Min.x
+ Max.y - Min.y
+
+
+
+
+ {{Name={Name,s}}}
+ {{Name={Name,s}} Inactive}
+
+
+
\ No newline at end of file
diff --git a/examples/libs/usynergy/README.txt b/examples/libs/usynergy/README.txt
new file mode 100644
index 000000000..c86b90965
--- /dev/null
+++ b/examples/libs/usynergy/README.txt
@@ -0,0 +1,8 @@
+
+uSynergy client -- Implementation for the embedded Synergy client library
+version 1.0.0, July 7th, 2012
+Copyright (c) 2012 Alex Evans
+
+This is a copy of the files once found at:
+ https://github.com/symless/synergy-core/tree/790d108a56ada9caad8e56ff777d444485a69da9/src/micro
+
diff --git a/examples/marmalade_example/imgui_impl_marmalade.cpp b/examples/marmalade_example/imgui_impl_marmalade.cpp
index ae7f10c0d..36fc8328c 100644
--- a/examples/marmalade_example/imgui_impl_marmalade.cpp
+++ b/examples/marmalade_example/imgui_impl_marmalade.cpp
@@ -21,13 +21,12 @@
// Data
static double g_Time = 0.0f;
static bool g_MousePressed[3] = { false, false, false };
-static float g_MouseWheel = 0.0f;
static CIwTexture* g_FontTexture = NULL;
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_scale = ImVec2(1.0f,1.0f);
+static ImVec2 g_RenderScale = ImVec2(1.0f,1.0f);
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
void ImGui_Marmalade_RenderDrawLists(ImDrawData* draw_data)
@@ -48,9 +47,9 @@ void ImGui_Marmalade_RenderDrawLists(ImDrawData* draw_data)
for( int i=0; i < nVert; i++ )
{
- // TODO: optimize multiplication on gpu using vertex shader
- pVertStream[i].x = cmd_list->VtxBuffer[i].pos.x * g_scale.x;
- pVertStream[i].y = cmd_list->VtxBuffer[i].pos.y * g_scale.y;
+ // TODO: optimize multiplication on gpu using vertex shader/projection matrix.
+ pVertStream[i].x = cmd_list->VtxBuffer[i].pos.x * g_RenderScale.x;
+ pVertStream[i].y = cmd_list->VtxBuffer[i].pos.y * g_RenderScale.y;
pUVStream[i].x = cmd_list->VtxBuffer[i].uv.x;
pUVStream[i].y = cmd_list->VtxBuffer[i].uv.y;
pColStream[i] = cmd_list->VtxBuffer[i].col;
@@ -128,9 +127,9 @@ int32 ImGui_Marmalade_PointerButtonEventCallback(void* SystemData, void* pUserDa
if (pEvent->m_Button == S3E_POINTER_BUTTON_MIDDLEMOUSE)
g_MousePressed[2] = true;
if (pEvent->m_Button == S3E_POINTER_BUTTON_MOUSEWHEELUP)
- g_MouseWheel += pEvent->m_y;
+ io.MouseWheel += pEvent->m_y;
if (pEvent->m_Button == S3E_POINTER_BUTTON_MOUSEWHEELDOWN)
- g_MouseWheel += pEvent->m_y;
+ io.MouseWheel += pEvent->m_y;
}
return 0;
@@ -220,6 +219,7 @@ bool ImGui_Marmalade_Init(bool install_callbacks)
io.KeyMap[ImGuiKey_PageDown] = s3eKeyPageDown;
io.KeyMap[ImGuiKey_Home] = s3eKeyHome;
io.KeyMap[ImGuiKey_End] = s3eKeyEnd;
+ io.KeyMap[ImGuiKey_Insert] = s3eKeyInsert;
io.KeyMap[ImGuiKey_Delete] = s3eKeyDelete;
io.KeyMap[ImGuiKey_Backspace] = s3eKeyBackspace;
io.KeyMap[ImGuiKey_Enter] = s3eKeyEnter;
@@ -273,7 +273,7 @@ void ImGui_Marmalade_NewFrame()
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 in screen coordinates (set to -1,-1 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++)
{
@@ -281,13 +281,10 @@ void ImGui_Marmalade_NewFrame()
g_MousePressed[i] = false;
}
- io.MouseWheel = g_MouseWheel;
- g_MouseWheel = 0.0f;
-
// TODO: Hide OS mouse cursor if ImGui is drawing it
// s3ePointerSetInt(S3E_POINTER_HIDE_CURSOR,(io.MouseDrawCursor ? 0 : 1));
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
// Show/hide OSD keyboard
diff --git a/examples/marmalade_example/main.cpp b/examples/marmalade_example/main.cpp
index c49aa844f..2b5edb77f 100644
--- a/examples/marmalade_example/main.cpp
+++ b/examples/marmalade_example/main.cpp
@@ -17,60 +17,75 @@ int main(int, char**)
// Setup ImGui binding
ImGui_Marmalade_Init(true);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_color = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
while (true)
{
- if (s3eDeviceCheckQuitRequest())
- break;
+ if (s3eDeviceCheckQuitRequest())
+ break;
- s3eKeyboardUpdate();
- s3ePointerUpdate();
- ImGui_Marmalade_NewFrame();
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
+ s3eKeyboardUpdate();
+ s3ePointerUpdate();
+ ImGui_Marmalade_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_color);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
- IwGxSetColClear(clear_color.x*255,clear_color.y*255,clear_color.z*255,clear_color.w*255) ;
+ IwGxSetColClear(clear_color.x * 255, clear_color.y * 255, clear_color.z * 255, clear_color.w * 255);
IwGxClear();
ImGui::Render();
IwGxSwapBuffers();
diff --git a/examples/null_example/build_win32.bat b/examples/null_example/build_win32.bat
new file mode 100644
index 000000000..7bb78232a
--- /dev/null
+++ b/examples/null_example/build_win32.bat
@@ -0,0 +1,3 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
+mkdir Debug
+cl /nologo /Zi /MD /I ..\.. *.cpp ..\..\*.cpp /FeDebug/null_example.exe /FoDebug/ /link gdi32.lib shell32.lib
diff --git a/examples/null_example/main.cpp b/examples/null_example/main.cpp
new file mode 100644
index 000000000..04c1bda40
--- /dev/null
+++ b/examples/null_example/main.cpp
@@ -0,0 +1,33 @@
+// ImGui - null/dummy example application (compile and link imgui with no inputs, no outputs)
+#include
+#include
+
+int main(int, char**)
+{
+ ImGuiIO& io = ImGui::GetIO();
+
+ // Build atlas
+ unsigned char* tex_pixels = NULL;
+ int tex_w, tex_h;
+ io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_w, &tex_h);
+
+ for (int n = 0; n < 50; n++)
+ {
+ printf("NewFrame() %d\n", n);
+ io.DisplaySize = ImVec2(1920, 1080);
+ io.DeltaTime = 1.0f / 60.0f;
+ ImGui::NewFrame();
+
+ static float f = 0.0f;
+ ImGui::Text("Hello, world!");
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
+ ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
+ ImGui::ShowDemoWindow(NULL);
+
+ ImGui::Render();
+ }
+
+ printf("Shutdown()\n");
+ ImGui::Shutdown();
+ return 0;
+}
diff --git a/examples/opengl2_example/Makefile b/examples/opengl2_example/Makefile
index 631abe4ba..f10c59a8d 100644
--- a/examples/opengl2_example/Makefile
+++ b/examples/opengl2_example/Makefile
@@ -1,6 +1,6 @@
#
# Cross Platform Makefile
-# Compatible with Ubuntu 14.04.1 and Mac OS X
+# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X
#
#
# if you using Mac OS X:
@@ -11,7 +11,7 @@
#CXX = g++
EXE = opengl2_example
-OBJS = main.o imgui_impl_glfw.o
+OBJS = main.o imgui_impl_glfw_gl2.o
OBJS += ../../imgui.o ../../imgui_demo.o ../../imgui_draw.o
UNAME_S := $(shell uname -s)
@@ -37,7 +37,7 @@ ifeq ($(UNAME_S), Darwin) #APPLE
CFLAGS = $(CXXFLAGS)
endif
-ifeq ($(UNAME_S), MINGW64_NT-6.3)
+ifeq ($(findstring MINGW,$(UNAME_S)),MINGW)
ECHO_MESSAGE = "Windows"
LIBS = -lglfw3 -lgdi32 -lopengl32 -limm32
diff --git a/examples/opengl2_example/imgui_impl_glfw.h b/examples/opengl2_example/imgui_impl_glfw.h
deleted file mode 100644
index 07dd96f04..000000000
--- a/examples/opengl2_example/imgui_impl_glfw.h
+++ /dev/null
@@ -1,29 +0,0 @@
-// ImGui GLFW binding with OpenGL
-// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
-
-// If your context is GL3/GL3 then prefer using the code in opengl3_example.
-// You *might* use this code with a GL3/GL4 context but make sure you disable the programmable pipeline by calling "glUseProgram(0)" before ImGui::Render().
-// We cannot do that from GL2 code because the function doesn't exist.
-
-// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
-// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
-// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
-// https://github.com/ocornut/imgui
-
-struct GLFWwindow;
-
-IMGUI_API bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks);
-IMGUI_API void ImGui_ImplGlfw_Shutdown();
-IMGUI_API void ImGui_ImplGlfw_NewFrame();
-
-// Use if you want to reset your rendering device without losing ImGui state.
-IMGUI_API void ImGui_ImplGlfw_InvalidateDeviceObjects();
-IMGUI_API bool ImGui_ImplGlfw_CreateDeviceObjects();
-
-// GLFW callbacks (installed by default if you enable 'install_callbacks' during initialization)
-// Provided here if you want to chain callbacks.
-// You can also handle inputs yourself and use those as a reference.
-IMGUI_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
-IMGUI_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
-IMGUI_API void ImGui_ImplGlFw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
-IMGUI_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);
diff --git a/examples/opengl2_example/imgui_impl_glfw.cpp b/examples/opengl2_example/imgui_impl_glfw_gl2.cpp
similarity index 67%
rename from examples/opengl2_example/imgui_impl_glfw.cpp
rename to examples/opengl2_example/imgui_impl_glfw_gl2.cpp
index 3755c6088..e5fe2f47b 100644
--- a/examples/opengl2_example/imgui_impl_glfw.cpp
+++ b/examples/opengl2_example/imgui_impl_glfw_gl2.cpp
@@ -1,9 +1,14 @@
-// ImGui GLFW binding with OpenGL
+// ImGui GLFW binding with OpenGL (legacy, fixed pipeline)
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
-// If your context is GL3/GL3 then prefer using the code in opengl3_example.
-// You *might* use this code with a GL3/GL4 context but make sure you disable the programmable pipeline by calling "glUseProgram(0)" before ImGui::Render().
-// We cannot do that from GL2 code because the function doesn't exist.
+// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+// **Prefer using the code in the opengl3_example/ folder**
+// This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
+// If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
+// complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
+// confuse your GPU driver.
+// The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
@@ -11,7 +16,7 @@
// https://github.com/ocornut/imgui
#include
-#include "imgui_impl_glfw.h"
+#include "imgui_impl_glfw_gl2.h"
// GLFW
#include
@@ -25,14 +30,13 @@
// Data
static GLFWwindow* g_Window = NULL;
static double g_Time = 0.0f;
-static bool g_MousePressed[3] = { false, false, false };
-static float g_MouseWheel = 0.0f;
+static bool g_MouseJustPressed[3] = { false, false, false };
static GLuint g_FontTexture = 0;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
-// If text or lines are blurry when integrating ImGui in your engine:
-// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
-void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
+void ImGui_ImplGlfwGL2_RenderDrawLists(ImDrawData* draw_data)
+// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
+// If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
@@ -43,8 +47,9 @@ void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// We are using the OpenGL fixed pipeline to make the example code simpler to read!
- // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
+ // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
+ GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
@@ -57,7 +62,8 @@ void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_TEXTURE_2D);
- //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
// Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
@@ -70,15 +76,14 @@ void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
glLoadIdentity();
// Render command lists
- #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
- glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, pos)));
- glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, uv)));
- glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, col)));
+ glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
+ glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
+ glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
@@ -96,7 +101,6 @@ void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
idx_buffer += pcmd->ElemCount;
}
}
- #undef OFFSETOF
// Restore modified state
glDisableClientState(GL_COLOR_ARRAY);
@@ -108,32 +112,35 @@ void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data)
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
+ glPolygonMode(GL_FRONT, last_polygon_mode[0]); glPolygonMode(GL_BACK, last_polygon_mode[1]);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
-static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
+static const char* ImGui_ImplGlfwGL2_GetClipboardText(void* user_data)
{
return glfwGetClipboardString((GLFWwindow*)user_data);
}
-static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
+static void ImGui_ImplGlfwGL2_SetClipboardText(void* user_data, const char* text)
{
glfwSetClipboardString((GLFWwindow*)user_data, text);
}
-void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
+void ImGui_ImplGlfwGL2_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
{
if (action == GLFW_PRESS && button >= 0 && button < 3)
- g_MousePressed[button] = true;
+ g_MouseJustPressed[button] = true;
}
-void ImGui_ImplGlfw_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
+void ImGui_ImplGlfwGL2_ScrollCallback(GLFWwindow*, double xoffset, double yoffset)
{
- g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
+ ImGuiIO& io = ImGui::GetIO();
+ io.MouseWheelH += (float)xoffset;
+ io.MouseWheel += (float)yoffset;
}
-void ImGui_ImplGlFw_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
+void ImGui_ImplGlfwGL2_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
{
ImGuiIO& io = ImGui::GetIO();
if (action == GLFW_PRESS)
@@ -148,14 +155,14 @@ void ImGui_ImplGlFw_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER];
}
-void ImGui_ImplGlfw_CharCallback(GLFWwindow*, unsigned int c)
+void ImGui_ImplGlfwGL2_CharCallback(GLFWwindow*, unsigned int c)
{
ImGuiIO& io = ImGui::GetIO();
if (c > 0 && c < 0x10000)
io.AddInputCharacter((unsigned short)c);
}
-bool ImGui_ImplGlfw_CreateDeviceObjects()
+bool ImGui_ImplGlfwGL2_CreateDeviceObjects()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
@@ -181,7 +188,7 @@ bool ImGui_ImplGlfw_CreateDeviceObjects()
return true;
}
-void ImGui_ImplGlfw_InvalidateDeviceObjects()
+void ImGui_ImplGlfwGL2_InvalidateDeviceObjects()
{
if (g_FontTexture)
{
@@ -191,7 +198,7 @@ void ImGui_ImplGlfw_InvalidateDeviceObjects()
}
}
-bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks)
+bool ImGui_ImplGlfwGL2_Init(GLFWwindow* window, bool install_callbacks)
{
g_Window = window;
@@ -205,6 +212,7 @@ bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks)
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
+ io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
@@ -216,9 +224,9 @@ bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks)
io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;
io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;
- io.RenderDrawListsFn = ImGui_ImplGlfw_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
- io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
- io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
+ io.RenderDrawListsFn = ImGui_ImplGlfwGL2_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
+ io.SetClipboardTextFn = ImGui_ImplGlfwGL2_SetClipboardText;
+ io.GetClipboardTextFn = ImGui_ImplGlfwGL2_GetClipboardText;
io.ClipboardUserData = g_Window;
#ifdef _WIN32
io.ImeWindowHandle = glfwGetWin32Window(g_Window);
@@ -226,25 +234,25 @@ bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks)
if (install_callbacks)
{
- glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
- glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
- glfwSetKeyCallback(window, ImGui_ImplGlFw_KeyCallback);
- glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
+ glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL2_MouseButtonCallback);
+ glfwSetScrollCallback(window, ImGui_ImplGlfwGL2_ScrollCallback);
+ glfwSetKeyCallback(window, ImGui_ImplGlfwGL2_KeyCallback);
+ glfwSetCharCallback(window, ImGui_ImplGlfwGL2_CharCallback);
}
return true;
}
-void ImGui_ImplGlfw_Shutdown()
+void ImGui_ImplGlfwGL2_Shutdown()
{
- ImGui_ImplGlfw_InvalidateDeviceObjects();
+ ImGui_ImplGlfwGL2_InvalidateDeviceObjects();
ImGui::Shutdown();
}
-void ImGui_ImplGlfw_NewFrame()
+void ImGui_ImplGlfwGL2_NewFrame()
{
if (!g_FontTexture)
- ImGui_ImplGlfw_CreateDeviceObjects();
+ ImGui_ImplGlfwGL2_CreateDeviceObjects();
ImGuiIO& io = ImGui::GetIO();
@@ -265,27 +273,32 @@ void ImGui_ImplGlfw_NewFrame()
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
{
- double mouse_x, mouse_y;
- glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
- io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.)
+ if (io.WantMoveMouse)
+ {
+ glfwSetCursorPos(g_Window, (double)io.MousePos.x, (double)io.MousePos.y); // Set mouse position if requested by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
+ }
+ else
+ {
+ double mouse_x, mouse_y;
+ glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
+ io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
+ }
}
else
{
- io.MousePos = ImVec2(-1,-1);
+ io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX);
}
for (int i = 0; i < 3; i++)
{
- io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 0; // 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.
- g_MousePressed[i] = false;
+ // 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] || glfwGetMouseButton(g_Window, i) != 0;
+ g_MouseJustPressed[i] = false;
}
- io.MouseWheel = g_MouseWheel;
- g_MouseWheel = 0.0f;
-
// Hide OS mouse cursor if ImGui is drawing it
glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/opengl2_example/imgui_impl_glfw_gl2.h b/examples/opengl2_example/imgui_impl_glfw_gl2.h
new file mode 100644
index 000000000..d04a84fa8
--- /dev/null
+++ b/examples/opengl2_example/imgui_impl_glfw_gl2.h
@@ -0,0 +1,29 @@
+// ImGui GLFW binding with OpenGL (legacy, fixed pipeline)
+// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+
+// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+// **Prefer using the code in the opengl3_example/ folder**
+// See imgui_impl_glfw.cpp for details.
+
+// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
+// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
+// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// https://github.com/ocornut/imgui
+
+struct GLFWwindow;
+
+IMGUI_API bool ImGui_ImplGlfwGL2_Init(GLFWwindow* window, bool install_callbacks);
+IMGUI_API void ImGui_ImplGlfwGL2_Shutdown();
+IMGUI_API void ImGui_ImplGlfwGL2_NewFrame();
+
+// Use if you want to reset your rendering device without losing ImGui state.
+IMGUI_API void ImGui_ImplGlfwGL2_InvalidateDeviceObjects();
+IMGUI_API bool ImGui_ImplGlfwGL2_CreateDeviceObjects();
+
+// GLFW callbacks (registered by default to GLFW if you enable 'install_callbacks' during initialization)
+// Provided here if you want to chain callbacks yourself. You may also handle inputs yourself and use those as a reference.
+IMGUI_API void ImGui_ImplGlfwGL2_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
+IMGUI_API void ImGui_ImplGlfwGL2_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
+IMGUI_API void ImGui_ImplGlfwGL2_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
+IMGUI_API void ImGui_ImplGlfwGL2_CharCallback(GLFWwindow* window, unsigned int c);
diff --git a/examples/opengl2_example/main.cpp b/examples/opengl2_example/main.cpp
index a844db520..6359f5b62 100644
--- a/examples/opengl2_example/main.cpp
+++ b/examples/opengl2_example/main.cpp
@@ -1,8 +1,13 @@
-// ImGui - standalone example application for Glfw + OpenGL 2, using fixed pipeline
+// ImGui - standalone example application for GLFW + OpenGL2, using legacy fixed pipeline
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+
+// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+// **Prefer using the code in the opengl3_example/ folder**
+// See imgui_impl_glfw.cpp for details.
#include
-#include "imgui_impl_glfw.h"
+#include "imgui_impl_glfw_gl2.h"
#include
#include
@@ -19,56 +24,72 @@ int main(int, char**)
return 1;
GLFWwindow* window = glfwCreateWindow(1280, 720, "ImGui OpenGL2 example", NULL, NULL);
glfwMakeContextCurrent(window);
+ glfwSwapInterval(1); // Enable vsync
// Setup ImGui binding
- ImGui_ImplGlfw_Init(window, true);
+ ImGui_ImplGlfwGL2_Init(window, true);
+
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_color = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
while (!glfwWindowShouldClose(window))
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
glfwPollEvents();
- ImGui_ImplGlfw_NewFrame();
+ ImGui_ImplGlfwGL2_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_color);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
@@ -77,12 +98,13 @@ int main(int, char**)
glViewport(0, 0, display_w, display_h);
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
+ //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound, but prefer using the GL3+ code.
ImGui::Render();
glfwSwapBuffers(window);
}
// Cleanup
- ImGui_ImplGlfw_Shutdown();
+ ImGui_ImplGlfwGL2_Shutdown();
glfwTerminate();
return 0;
diff --git a/examples/opengl2_example/opengl2_example.vcxproj b/examples/opengl2_example/opengl2_example.vcxproj
index bea2104d1..bf1a3ed4e 100644
--- a/examples/opengl2_example/opengl2_example.vcxproj
+++ b/examples/opengl2_example/opengl2_example.vcxproj
@@ -116,6 +116,7 @@
truetrue$(SolutionDir)\libs\glfw\include;..\..;%(AdditionalIncludeDirectories)
+ falsetrue
@@ -135,6 +136,7 @@
truetrue$(SolutionDir)\libs\glfw\include;..\..;%(AdditionalIncludeDirectories)
+ falsetrue
@@ -151,16 +153,17 @@
-
+
-
+
+
diff --git a/examples/opengl2_example/opengl2_example.vcxproj.filters b/examples/opengl2_example/opengl2_example.vcxproj.filters
index f2282bf69..35fd6ffaf 100644
--- a/examples/opengl2_example/opengl2_example.vcxproj.filters
+++ b/examples/opengl2_example/opengl2_example.vcxproj.filters
@@ -16,7 +16,7 @@
imgui
-
+ sources
@@ -33,7 +33,7 @@
imgui
-
+ sources
@@ -42,5 +42,8 @@
+
+ sources
+
\ No newline at end of file
diff --git a/examples/opengl3_example/Makefile b/examples/opengl3_example/Makefile
index 5d91708aa..32343ed23 100644
--- a/examples/opengl3_example/Makefile
+++ b/examples/opengl3_example/Makefile
@@ -1,12 +1,13 @@
#
# Cross Platform Makefile
-# Compatible with Ubuntu 14.04.1 and Mac OS X
+# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X
#
#
# You will need GLFW (http://www.glfw.org)
#
# apt-get install libglfw-dev # Linux
# brew install glfw # Mac OS X
+# pacman -S --noconfirm --needed mingw-w64-x86_64-toolchain mingw-w64-x86_64-glfw # MSYS2
#
#CXX = g++
@@ -39,7 +40,7 @@ ifeq ($(UNAME_S), Darwin) #APPLE
CFLAGS = $(CXXFLAGS)
endif
-ifeq ($(UNAME_S), MINGW64_NT-6.3)
+ifeq ($(findstring MINGW,$(UNAME_S)),MINGW)
ECHO_MESSAGE = "Windows"
LIBS = -lglfw3 -lgdi32 -lopengl32 -limm32
diff --git a/examples/opengl3_example/imgui_impl_glfw_gl3.cpp b/examples/opengl3_example/imgui_impl_glfw_gl3.cpp
index 97a125d89..a71fc515d 100644
--- a/examples/opengl3_example/imgui_impl_glfw_gl3.cpp
+++ b/examples/opengl3_example/imgui_impl_glfw_gl3.cpp
@@ -1,5 +1,7 @@
// ImGui GLFW binding with OpenGL3 + shaders
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+// (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.)
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
@@ -22,8 +24,7 @@
// Data
static GLFWwindow* g_Window = NULL;
static double g_Time = 0.0f;
-static bool g_MousePressed[3] = { false, false, false };
-static float g_MouseWheel = 0.0f;
+static bool g_MouseJustPressed[3] = { false, false, false };
static GLuint g_FontTexture = 0;
static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
@@ -31,8 +32,8 @@ static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_Attr
static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
-// If text or lines are blurry when integrating ImGui in your engine:
-// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
+// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
+// If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
@@ -44,31 +45,36 @@ void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data)
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// 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);
- GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture);
+ GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler);
GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
- GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
- GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
- GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
- GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
+ GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
- GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
+ GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
+ GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
+ GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
+ GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
+ GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
+ GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
+ GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
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);
- // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
+ // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
- glActiveTexture(GL_TEXTURE0);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
@@ -83,6 +89,7 @@ void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data)
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
glBindVertexArray(g_VaoHandle);
+ glBindSampler(0, 0); // Rely on combined texture/sampler state.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
@@ -114,17 +121,19 @@ void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data)
// Restore modified GL state
glUseProgram(last_program);
- glActiveTexture(last_active_texture);
glBindTexture(GL_TEXTURE_2D, last_texture);
+ glBindSampler(0, last_sampler);
+ glActiveTexture(last_active_texture);
glBindVertexArray(last_vertex_array);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
- glBlendFunc(last_blend_src, last_blend_dst);
+ glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
+ glPolygonMode(GL_FRONT_AND_BACK, last_polygon_mode[0]);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
@@ -142,12 +151,14 @@ static void ImGui_ImplGlfwGL3_SetClipboardText(void* user_data, const char* text
void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
{
if (action == GLFW_PRESS && button >= 0 && button < 3)
- g_MousePressed[button] = true;
+ g_MouseJustPressed[button] = true;
}
-void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
+void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double xoffset, double yoffset)
{
- g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
+ ImGuiIO& io = ImGui::GetIO();
+ io.MouseWheelH += (float)xoffset;
+ io.MouseWheel += (float)yoffset;
}
void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
@@ -207,7 +218,7 @@ bool ImGui_ImplGlfwGL3_CreateDeviceObjects()
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
const GLchar *vertex_shader =
- "#version 330\n"
+ "#version 150\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
@@ -222,7 +233,7 @@ bool ImGui_ImplGlfwGL3_CreateDeviceObjects()
"}\n";
const GLchar* fragment_shader =
- "#version 330\n"
+ "#version 150\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
@@ -259,11 +270,9 @@ bool ImGui_ImplGlfwGL3_CreateDeviceObjects()
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
-#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
- glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
- glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
- glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
-#undef OFFSETOF
+ glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
+ glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
+ glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
ImGui_ImplGlfwGL3_CreateFontsTexture();
@@ -315,6 +324,7 @@ bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks)
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
+ io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
@@ -375,27 +385,32 @@ void ImGui_ImplGlfwGL3_NewFrame()
// (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents())
if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED))
{
- double mouse_x, mouse_y;
- glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
- io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.)
+ if (io.WantMoveMouse)
+ {
+ glfwSetCursorPos(g_Window, (double)io.MousePos.x, (double)io.MousePos.y); // Set mouse position if requested by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation)
+ }
+ else
+ {
+ double mouse_x, mouse_y;
+ glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
+ io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
+ }
}
else
{
- io.MousePos = ImVec2(-1,-1);
+ io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX);
}
for (int i = 0; i < 3; i++)
{
- io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 0; // 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.
- g_MousePressed[i] = false;
+ // 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] || glfwGetMouseButton(g_Window, i) != 0;
+ g_MouseJustPressed[i] = false;
}
- io.MouseWheel = g_MouseWheel;
- g_MouseWheel = 0.0f;
-
// Hide OS mouse cursor if ImGui is drawing it
glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/opengl3_example/imgui_impl_glfw_gl3.h b/examples/opengl3_example/imgui_impl_glfw_gl3.h
index 83c69aa86..5f3043988 100644
--- a/examples/opengl3_example/imgui_impl_glfw_gl3.h
+++ b/examples/opengl3_example/imgui_impl_glfw_gl3.h
@@ -1,5 +1,7 @@
// ImGui GLFW binding with OpenGL3 + shaders
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+// (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.)
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
diff --git a/examples/opengl3_example/main.cpp b/examples/opengl3_example/main.cpp
index 074bab548..6beb855dc 100644
--- a/examples/opengl3_example/main.cpp
+++ b/examples/opengl3_example/main.cpp
@@ -1,5 +1,7 @@
-// ImGui - standalone example application for Glfw + OpenGL 3, using programmable pipeline
+// ImGui - standalone example application for GLFW + OpenGL 3, using programmable pipeline
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+// (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.)
#include
#include "imgui_impl_glfw_gl3.h"
@@ -19,64 +21,80 @@ int main(int, char**)
if (!glfwInit())
return 1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
- glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
+ glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
GLFWwindow* window = glfwCreateWindow(1280, 720, "ImGui OpenGL3 example", NULL, NULL);
glfwMakeContextCurrent(window);
+ glfwSwapInterval(1); // Enable vsync
gl3wInit();
// Setup ImGui binding
ImGui_ImplGlfwGL3_Init(window, true);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_color = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
while (!glfwWindowShouldClose(window))
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
glfwPollEvents();
ImGui_ImplGlfwGL3_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_color);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
diff --git a/examples/opengl3_example/opengl3_example.vcxproj b/examples/opengl3_example/opengl3_example.vcxproj
index 8d8bec90f..2a78226f7 100644
--- a/examples/opengl3_example/opengl3_example.vcxproj
+++ b/examples/opengl3_example/opengl3_example.vcxproj
@@ -116,6 +116,7 @@
truetrue$(SolutionDir)\libs\glfw\include;$(SolutionDir)\libs\gl3w;..\..;%(AdditionalIncludeDirectories)
+ falsetrue
@@ -135,6 +136,7 @@
truetrue$(SolutionDir)\libs\glfw\include;$(SolutionDir)\libs\gl3w;..\..;%(AdditionalIncludeDirectories)
+ falsetrue
@@ -164,6 +166,7 @@
+
diff --git a/examples/opengl3_example/opengl3_example.vcxproj.filters b/examples/opengl3_example/opengl3_example.vcxproj.filters
index f19cd16b2..c743ace31 100644
--- a/examples/opengl3_example/opengl3_example.vcxproj.filters
+++ b/examples/opengl3_example/opengl3_example.vcxproj.filters
@@ -54,5 +54,8 @@
+
+ sources
+
\ No newline at end of file
diff --git a/examples/sdl_opengl2_example/README.md b/examples/sdl_opengl2_example/README.md
index deae32392..a1a44a584 100644
--- a/examples/sdl_opengl2_example/README.md
+++ b/examples/sdl_opengl2_example/README.md
@@ -5,18 +5,18 @@
```
set SDL2DIR=path_to_your_sdl2_folder
-cl /Zi /MD /I %SDL2DIR%\include /I ..\.. main.cpp imgui_impl_sdl.cpp ..\..\imgui*.cpp /link /LIBPATH:%SDL2DIR%\lib SDL2.lib SDL2main.lib opengl32.lib /subsystem:console
+cl /Zi /MD /I %SDL2DIR%\include /I ..\.. main.cpp imgui_impl_sdl_gl2.cpp ..\..\imgui*.cpp /link /LIBPATH:%SDL2DIR%\lib SDL2.lib SDL2main.lib opengl32.lib /subsystem:console
```
- On Linux and similar Unixes
```
-c++ `sdl2-config --cflags` -I ../.. main.cpp imgui_impl_sdl.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL -o sdl2example
+c++ `sdl2-config --cflags` -I ../.. main.cpp imgui_impl_sdl_gl2.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL -o sdl2example
```
- On Mac OS X
```
brew install sdl2
-c++ `sdl2-config --cflags` -I ../.. main.cpp imgui_impl_sdl.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl -o sdl2example
+c++ `sdl2-config --cflags` -I ../.. main.cpp imgui_impl_sdl_gl2.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl -o sdl2example
```
diff --git a/examples/sdl_opengl2_example/build_win32.bat b/examples/sdl_opengl2_example/build_win32.bat
new file mode 100644
index 000000000..799561dec
--- /dev/null
+++ b/examples/sdl_opengl2_example/build_win32.bat
@@ -0,0 +1,3 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
+mkdir Debug
+cl /nologo /Zi /MD /I ..\.. /I ..\libs\gl3w /I %SDL_DIR%\include main.cpp imgui_impl_sdl_gl2.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/sdl_opengl2_example.exe /FoDebug/ /link /libpath:%SDL_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console
diff --git a/examples/sdl_opengl2_example/imgui_impl_sdl.h b/examples/sdl_opengl2_example/imgui_impl_sdl.h
deleted file mode 100644
index a322bf2d9..000000000
--- a/examples/sdl_opengl2_example/imgui_impl_sdl.h
+++ /dev/null
@@ -1,19 +0,0 @@
-// ImGui SDL2 binding with OpenGL
-// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
-
-// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
-// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
-// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
-// https://github.com/ocornut/imgui
-
-struct SDL_Window;
-typedef union SDL_Event SDL_Event;
-
-IMGUI_API bool ImGui_ImplSdl_Init(SDL_Window* window);
-IMGUI_API void ImGui_ImplSdl_Shutdown();
-IMGUI_API void ImGui_ImplSdl_NewFrame(SDL_Window* window);
-IMGUI_API bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event);
-
-// Use if you want to reset your rendering device without losing ImGui state.
-IMGUI_API void ImGui_ImplSdl_InvalidateDeviceObjects();
-IMGUI_API bool ImGui_ImplSdl_CreateDeviceObjects();
diff --git a/examples/sdl_opengl2_example/imgui_impl_sdl.cpp b/examples/sdl_opengl2_example/imgui_impl_sdl_gl2.cpp
similarity index 63%
rename from examples/sdl_opengl2_example/imgui_impl_sdl.cpp
rename to examples/sdl_opengl2_example/imgui_impl_sdl_gl2.cpp
index 7be0fcdb4..76def29c3 100644
--- a/examples/sdl_opengl2_example/imgui_impl_sdl.cpp
+++ b/examples/sdl_opengl2_example/imgui_impl_sdl_gl2.cpp
@@ -1,5 +1,14 @@
-// ImGui SDL2 binding with OpenGL
+// ImGui SDL2 binding with OpenGL (legacy, fixed pipeline)
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+
+// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+// **Prefer using the code in the sdl_opengl3_example/ folder**
+// This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
+// If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
+// complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
+// confuse your GPU driver.
+// The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
@@ -10,18 +19,17 @@
#include
#include
#include
-#include "imgui_impl_sdl.h"
+#include "imgui_impl_sdl_gl2.h"
// Data
static double g_Time = 0.0f;
static bool g_MousePressed[3] = { false, false, false };
-static float g_MouseWheel = 0.0f;
static GLuint g_FontTexture = 0;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
-// If text or lines are blurry when integrating ImGui in your engine:
-// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
-void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
+// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
+// If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
+void ImGui_ImplSdlGL2_RenderDrawLists(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
@@ -32,8 +40,9 @@ void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// We are using the OpenGL fixed pipeline to make the example code simpler to read!
- // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
+ // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
+ GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
@@ -46,7 +55,8 @@ void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_TEXTURE_2D);
- //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+ //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
// Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
@@ -59,15 +69,14 @@ void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
glLoadIdentity();
// Render command lists
- #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
- glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, pos)));
- glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, uv)));
- glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, col)));
+ glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
+ glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
+ glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
@@ -85,7 +94,6 @@ void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
idx_buffer += pcmd->ElemCount;
}
}
- #undef OFFSETOF
// Restore modified state
glDisableClientState(GL_COLOR_ARRAY);
@@ -97,31 +105,36 @@ void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data)
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
+ glPolygonMode(GL_FRONT, last_polygon_mode[0]); glPolygonMode(GL_BACK, last_polygon_mode[1]);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
-static const char* ImGui_ImplSdl_GetClipboardText(void*)
+static const char* ImGui_ImplSdlGL2_GetClipboardText(void*)
{
return SDL_GetClipboardText();
}
-static void ImGui_ImplSdl_SetClipboardText(void*, const char* text)
+static void ImGui_ImplSdlGL2_SetClipboardText(void*, const char* text)
{
SDL_SetClipboardText(text);
}
-bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event)
+// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
+bool ImGui_ImplSdlGL2_ProcessEvent(SDL_Event* event)
{
ImGuiIO& io = ImGui::GetIO();
switch (event->type)
{
case SDL_MOUSEWHEEL:
{
- if (event->wheel.y > 0)
- g_MouseWheel = 1;
- if (event->wheel.y < 0)
- g_MouseWheel = -1;
+ if (event->wheel.x > 0) io.MouseWheelH += 1;
+ if (event->wheel.x < 0) io.MouseWheelH -= 1;
+ if (event->wheel.y > 0) io.MouseWheel += 1;
+ if (event->wheel.y < 0) io.MouseWheel -= 1;
return true;
}
case SDL_MOUSEBUTTONDOWN:
@@ -151,7 +164,7 @@ bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event)
return false;
}
-bool ImGui_ImplSdl_CreateDeviceObjects()
+bool ImGui_ImplSdlGL2_CreateDeviceObjects()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
@@ -178,7 +191,7 @@ bool ImGui_ImplSdl_CreateDeviceObjects()
return true;
}
-void ImGui_ImplSdl_InvalidateDeviceObjects()
+void ImGui_ImplSdlGL2_InvalidateDeviceObjects()
{
if (g_FontTexture)
{
@@ -188,7 +201,7 @@ void ImGui_ImplSdl_InvalidateDeviceObjects()
}
}
-bool ImGui_ImplSdl_Init(SDL_Window* window)
+bool ImGui_ImplSdlGL2_Init(SDL_Window* window)
{
ImGuiIO& io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
@@ -200,6 +213,7 @@ bool ImGui_ImplSdl_Init(SDL_Window* window)
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
+ io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
@@ -211,9 +225,9 @@ bool ImGui_ImplSdl_Init(SDL_Window* window)
io.KeyMap[ImGuiKey_Y] = SDLK_y;
io.KeyMap[ImGuiKey_Z] = SDLK_z;
- io.RenderDrawListsFn = ImGui_ImplSdl_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
- io.SetClipboardTextFn = ImGui_ImplSdl_SetClipboardText;
- io.GetClipboardTextFn = ImGui_ImplSdl_GetClipboardText;
+ io.RenderDrawListsFn = ImGui_ImplSdlGL2_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
+ io.SetClipboardTextFn = ImGui_ImplSdlGL2_SetClipboardText;
+ io.GetClipboardTextFn = ImGui_ImplSdlGL2_GetClipboardText;
io.ClipboardUserData = NULL;
#ifdef _WIN32
@@ -228,16 +242,16 @@ bool ImGui_ImplSdl_Init(SDL_Window* window)
return true;
}
-void ImGui_ImplSdl_Shutdown()
+void ImGui_ImplSdlGL2_Shutdown()
{
- ImGui_ImplSdl_InvalidateDeviceObjects();
+ ImGui_ImplSdlGL2_InvalidateDeviceObjects();
ImGui::Shutdown();
}
-void ImGui_ImplSdl_NewFrame(SDL_Window *window)
+void ImGui_ImplSdlGL2_NewFrame(SDL_Window *window)
{
if (!g_FontTexture)
- ImGui_ImplSdl_CreateDeviceObjects();
+ ImGui_ImplSdlGL2_CreateDeviceObjects();
ImGuiIO& io = ImGui::GetIO();
@@ -252,29 +266,37 @@ void ImGui_ImplSdl_NewFrame(SDL_Window *window)
// Setup time step
Uint32 time = SDL_GetTicks();
double current_time = time / 1000.0;
- 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
- // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent())
+ // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters from our event handler)
int mx, my;
- Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
- if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)
- io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
- else
- io.MousePos = ImVec2(-1,-1);
-
- io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // 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[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
- io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
+ Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my);
+ io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
+ io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // 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[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
+ io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
- io.MouseWheel = g_MouseWheel;
- g_MouseWheel = 0.0f;
+ // We need to use SDL_CaptureMouse() to easily retrieve mouse coordinates outside of the client area. This is only supported from SDL 2.0.4 (released Jan 2016)
+#if (SDL_MAJOR_VERSION >= 2) && (SDL_MINOR_VERSION >= 0) && (SDL_PATCHLEVEL >= 4)
+ if ((SDL_GetWindowFlags(window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE)) != 0)
+ io.MousePos = ImVec2((float)mx, (float)my);
+ bool any_mouse_button_down = false;
+ for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
+ any_mouse_button_down |= io.MouseDown[n];
+ if (any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) == 0)
+ SDL_CaptureMouse(SDL_TRUE);
+ if (!any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) != 0)
+ SDL_CaptureMouse(SDL_FALSE);
+#else
+ if ((SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0)
+ io.MousePos = ImVec2((float)mx, (float)my);
+#endif
// Hide OS mouse cursor if ImGui is drawing it
SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/sdl_opengl2_example/imgui_impl_sdl_gl2.h b/examples/sdl_opengl2_example/imgui_impl_sdl_gl2.h
new file mode 100644
index 000000000..32d7bc0e9
--- /dev/null
+++ b/examples/sdl_opengl2_example/imgui_impl_sdl_gl2.h
@@ -0,0 +1,24 @@
+// ImGui SDL2 binding with OpenGL (legacy, fixed pipeline)
+// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+
+// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+// **Prefer using the code in the sdl_opengl3_example/ folder**
+// See imgui_impl_sdl.cpp for details.
+
+// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
+// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
+// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// https://github.com/ocornut/imgui
+
+struct SDL_Window;
+typedef union SDL_Event SDL_Event;
+
+IMGUI_API bool ImGui_ImplSdlGL2_Init(SDL_Window* window);
+IMGUI_API void ImGui_ImplSdlGL2_Shutdown();
+IMGUI_API void ImGui_ImplSdlGL2_NewFrame(SDL_Window* window);
+IMGUI_API bool ImGui_ImplSdlGL2_ProcessEvent(SDL_Event* event);
+
+// Use if you want to reset your rendering device without losing ImGui state.
+IMGUI_API void ImGui_ImplSdlGL2_InvalidateDeviceObjects();
+IMGUI_API bool ImGui_ImplSdlGL2_CreateDeviceObjects();
diff --git a/examples/sdl_opengl2_example/main.cpp b/examples/sdl_opengl2_example/main.cpp
index f42e7faf4..21b567a83 100644
--- a/examples/sdl_opengl2_example/main.cpp
+++ b/examples/sdl_opengl2_example/main.cpp
@@ -1,8 +1,13 @@
// ImGui - standalone example application for SDL2 + OpenGL
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+
+// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+// **Prefer using the code in the sdl_opengl3_example/ folder**
+// See imgui_impl_sdl.cpp for details.
#include
-#include "imgui_impl_sdl.h"
+#include "imgui_impl_sdl_gl2.h"
#include
#include
#include
@@ -28,73 +33,89 @@ int main(int, char**)
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
// Setup ImGui binding
- ImGui_ImplSdl_Init(window);
+ ImGui_ImplSdlGL2_Init(window);
+
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_color = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
bool done = false;
while (!done)
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
SDL_Event event;
while (SDL_PollEvent(&event))
{
- ImGui_ImplSdl_ProcessEvent(&event);
+ ImGui_ImplSdlGL2_ProcessEvent(&event);
if (event.type == SDL_QUIT)
done = true;
}
- ImGui_ImplSdl_NewFrame(window);
+ ImGui_ImplSdlGL2_NewFrame(window);
// 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_color);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y);
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
+ //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound
ImGui::Render();
SDL_GL_SwapWindow(window);
}
// Cleanup
- ImGui_ImplSdl_Shutdown();
+ ImGui_ImplSdlGL2_Shutdown();
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
SDL_Quit();
diff --git a/examples/sdl_opengl3_example/Makefile b/examples/sdl_opengl3_example/Makefile
new file mode 100644
index 000000000..364ca1239
--- /dev/null
+++ b/examples/sdl_opengl3_example/Makefile
@@ -0,0 +1,61 @@
+#
+# Cross Platform Makefile
+# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X
+#
+#
+# You will need SDL2 (http://www.libsdl.org)
+#
+# apt-get install libsdl2-dev # Linux
+# brew install sdl2 # Mac OS X
+# pacman -S mingw-w64-i686-SDL # MSYS2
+#
+
+#CXX = g++
+
+EXE = sdl_opengl3_example
+OBJS = main.o imgui_impl_sdl_gl3.o
+OBJS += ../../imgui.o ../../imgui_demo.o ../../imgui_draw.o
+OBJS += ../libs/gl3w/GL/gl3w.o
+
+UNAME_S := $(shell uname -s)
+
+
+ifeq ($(UNAME_S), Linux) #LINUX
+ ECHO_MESSAGE = "Linux"
+ LIBS = -lGL -ldl `sdl2-config --libs`
+
+ CXXFLAGS = -I../../ -I../libs/gl3w `sdl2-config --cflags`
+ CXXFLAGS += -Wall -Wformat
+ CFLAGS = $(CXXFLAGS)
+endif
+
+ifeq ($(UNAME_S), Darwin) #APPLE
+ ECHO_MESSAGE = "Mac OS X"
+ LIBS = -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl2-config --libs`
+
+ CXXFLAGS = -I../../ -I../libs/gl3w -I/usr/local/include `sdl2-config --cflags`
+ CXXFLAGS += -Wall -Wformat
+ CFLAGS = $(CXXFLAGS)
+endif
+
+ifeq ($(findstring MINGW,$(UNAME_S)),MINGW)
+ ECHO_MESSAGE = "Windows"
+ LIBS = -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl2`
+
+ CXXFLAGS = -I../../ -I../libs/gl3w `pkg-config --cflags sdl2`
+ CXXFLAGS += -Wall -Wformat
+ CFLAGS = $(CXXFLAGS)
+endif
+
+
+.cpp.o:
+ $(CXX) $(CXXFLAGS) -c -o $@ $<
+
+all: $(EXE)
+ @echo Build complete for $(ECHO_MESSAGE)
+
+$(EXE): $(OBJS)
+ $(CXX) -o $(EXE) $(OBJS) $(CXXFLAGS) $(LIBS)
+
+clean:
+ rm $(EXE) $(OBJS)
diff --git a/examples/sdl_opengl3_example/build_win32.bat b/examples/sdl_opengl3_example/build_win32.bat
new file mode 100644
index 000000000..43567542d
--- /dev/null
+++ b/examples/sdl_opengl3_example/build_win32.bat
@@ -0,0 +1,3 @@
+@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
+mkdir Debug
+cl /nologo /Zi /MD /I ..\.. /I ..\libs\gl3w /I %SDL_DIR%\include main.cpp imgui_impl_sdl_gl3.cpp ..\..\imgui*.cpp ..\libs\gl3w\GL\gl3w.c /FeDebug/sdl_opengl3_example.exe /FoDebug/ /link /libpath:%SDL_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console
diff --git a/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.cpp b/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.cpp
index 9acbf881c..35d9cdde1 100644
--- a/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.cpp
+++ b/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.cpp
@@ -1,5 +1,7 @@
// ImGui SDL2 binding with OpenGL3
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+// (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.)
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
@@ -17,7 +19,6 @@
// Data
static double g_Time = 0.0f;
static bool g_MousePressed[3] = { false, false, false };
-static float g_MouseWheel = 0.0f;
static GLuint g_FontTexture = 0;
static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
@@ -25,8 +26,8 @@ static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_Attr
static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
-// If text or lines are blurry when integrating ImGui in your engine:
-// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
+// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so.
+// If text or lines are blurry when integrating ImGui in your engine: in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_ImplSdlGL3_RenderDrawLists(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
@@ -38,33 +39,38 @@ void ImGui_ImplSdlGL3_RenderDrawLists(ImDrawData* draw_data)
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// 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);
- GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture);
+ GLint last_sampler; glGetIntegerv(GL_SAMPLER_BINDING, &last_sampler);
GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
- GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
- GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
- GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
- GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
+ GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
- GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
+ GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
+ GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
+ GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
+ GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
+ GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
+ GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
+ GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
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);
- // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
+ // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
- glActiveTexture(GL_TEXTURE0);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
- // Setup orthographic projection matrix
+ // Setup viewport, orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
const float ortho_projection[4][4] =
{
@@ -77,6 +83,7 @@ void ImGui_ImplSdlGL3_RenderDrawLists(ImDrawData* draw_data)
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
glBindVertexArray(g_VaoHandle);
+ glBindSampler(0, 0); // Rely on combined texture/sampler state.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
@@ -84,10 +91,10 @@ void ImGui_ImplSdlGL3_RenderDrawLists(ImDrawData* draw_data)
const ImDrawIdx* idx_buffer_offset = 0;
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
- glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
+ glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (GLvoid*)cmd_list->IdxBuffer.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);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
@@ -108,17 +115,19 @@ void ImGui_ImplSdlGL3_RenderDrawLists(ImDrawData* draw_data)
// Restore modified GL state
glUseProgram(last_program);
- glActiveTexture(last_active_texture);
glBindTexture(GL_TEXTURE_2D, last_texture);
+ glBindSampler(0, last_sampler);
+ glActiveTexture(last_active_texture);
glBindVertexArray(last_vertex_array);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
- glBlendFunc(last_blend_src, last_blend_dst);
+ glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
+ glPolygonMode(GL_FRONT_AND_BACK, last_polygon_mode[0]);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
@@ -133,6 +142,10 @@ static void ImGui_ImplSdlGL3_SetClipboardText(void*, const char* text)
SDL_SetClipboardText(text);
}
+// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
bool ImGui_ImplSdlGL3_ProcessEvent(SDL_Event* event)
{
ImGuiIO& io = ImGui::GetIO();
@@ -140,10 +153,10 @@ bool ImGui_ImplSdlGL3_ProcessEvent(SDL_Event* event)
{
case SDL_MOUSEWHEEL:
{
- if (event->wheel.y > 0)
- g_MouseWheel = 1;
- if (event->wheel.y < 0)
- g_MouseWheel = -1;
+ if (event->wheel.x > 0) io.MouseWheelH += 1;
+ if (event->wheel.x < 0) io.MouseWheelH -= 1;
+ if (event->wheel.y > 0) io.MouseWheel += 1;
+ if (event->wheel.y < 0) io.MouseWheel -= 1;
return true;
}
case SDL_MOUSEBUTTONDOWN:
@@ -207,7 +220,7 @@ bool ImGui_ImplSdlGL3_CreateDeviceObjects()
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
const GLchar *vertex_shader =
- "#version 330\n"
+ "#version 150\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
@@ -222,7 +235,7 @@ bool ImGui_ImplSdlGL3_CreateDeviceObjects()
"}\n";
const GLchar* fragment_shader =
- "#version 330\n"
+ "#version 150\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
@@ -259,11 +272,9 @@ bool ImGui_ImplSdlGL3_CreateDeviceObjects()
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
-#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
- glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
- glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
- glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
-#undef OFFSETOF
+ glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos));
+ glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv));
+ glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col));
ImGui_ImplSdlGL3_CreateFontsTexture();
@@ -313,6 +324,7 @@ bool ImGui_ImplSdlGL3_Init(SDL_Window* window)
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
+ io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
@@ -368,26 +380,34 @@ void ImGui_ImplSdlGL3_NewFrame(SDL_Window* window)
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
g_Time = current_time;
- // Setup inputs
- // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent())
+ // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters from our event handler)
int mx, my;
- Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
- if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)
- io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
- else
- io.MousePos = ImVec2(-1, -1);
-
- io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // 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[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
- io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
+ Uint32 mouse_buttons = SDL_GetMouseState(&mx, &my);
+ io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
+ io.MouseDown[0] = g_MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // 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[1] = g_MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
+ io.MouseDown[2] = g_MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
- io.MouseWheel = g_MouseWheel;
- g_MouseWheel = 0.0f;
+ // We need to use SDL_CaptureMouse() to easily retrieve mouse coordinates outside of the client area. This is only supported from SDL 2.0.4 (released Jan 2016)
+#if (SDL_MAJOR_VERSION >= 2) && (SDL_MINOR_VERSION >= 0) && (SDL_PATCHLEVEL >= 4)
+ if ((SDL_GetWindowFlags(window) & (SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_MOUSE_CAPTURE)) != 0)
+ io.MousePos = ImVec2((float)mx, (float)my);
+ bool any_mouse_button_down = false;
+ for (int n = 0; n < IM_ARRAYSIZE(io.MouseDown); n++)
+ any_mouse_button_down |= io.MouseDown[n];
+ if (any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) == 0)
+ SDL_CaptureMouse(SDL_TRUE);
+ if (!any_mouse_button_down && (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_CAPTURE) != 0)
+ SDL_CaptureMouse(SDL_FALSE);
+#else
+ if ((SDL_GetWindowFlags(window) & SDL_WINDOW_INPUT_FOCUS) != 0)
+ io.MousePos = ImVec2((float)mx, (float)my);
+#endif
// Hide OS mouse cursor if ImGui is drawing it
SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.h b/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.h
index 99abd4094..543818664 100644
--- a/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.h
+++ b/examples/sdl_opengl3_example/imgui_impl_sdl_gl3.h
@@ -1,5 +1,7 @@
// ImGui SDL2 binding with OpenGL3
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
+// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+// (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.)
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
diff --git a/examples/sdl_opengl3_example/main.cpp b/examples/sdl_opengl3_example/main.cpp
index c396405fb..7ee60389c 100644
--- a/examples/sdl_opengl3_example/main.cpp
+++ b/examples/sdl_opengl3_example/main.cpp
@@ -1,5 +1,7 @@
// ImGui - standalone example application for SDL2 + OpenGL
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
+// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
+// (GL3W is a helper library to access OpenGL functions since there is no standard header to access modern OpenGL functions easily. Alternatives are GLEW, Glad, etc.)
#include
#include "imgui_impl_sdl_gl3.h"
@@ -33,24 +35,38 @@ int main(int, char**)
// Setup ImGui binding
ImGui_ImplSdlGL3_Init(window);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_color = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
bool done = false;
while (!done)
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
SDL_Event event;
while (SDL_PollEvent(&event))
{
@@ -60,32 +76,33 @@ int main(int, char**)
}
ImGui_ImplSdlGL3_NewFrame(window);
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_color);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
// Rendering
diff --git a/examples/vulkan_example/build_win32.bat b/examples/vulkan_example/build_win32.bat
index e8b5a6c7a..bacb63943 100644
--- a/examples/vulkan_example/build_win32.bat
+++ b/examples/vulkan_example/build_win32.bat
@@ -1,4 +1,7 @@
@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
-mkdir Debug
-cl /nologo /Zi /MD /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\*.cpp /FeDebug/vulkan_example.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\bin32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib
+mkdir Debug
+cl /nologo /Zi /MD /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\*.cpp /FeDebug/vulkan_example.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib
+
+mkdir Release
+cl /nologo /Zi /MD /Ox /Oi /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\*.cpp /FeRelease/vulkan_example.exe /FoRelease/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib
diff --git a/examples/vulkan_example/build_win64.bat b/examples/vulkan_example/build_win64.bat
new file mode 100644
index 000000000..71e557b19
--- /dev/null
+++ b/examples/vulkan_example/build_win64.bat
@@ -0,0 +1,7 @@
+@REM Build for Visual Studio compiler. Run your copy of amd64/vcvars32.bat to setup 64-bit command-line compiler.
+
+mkdir Debug
+cl /nologo /Zi /MD /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\*.cpp /FeDebug/vulkan_example.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib
+
+mkdir Release
+cl /nologo /Zi /MD /Ox /Oi /I ..\.. /I ..\libs\glfw\include /I %VULKAN_SDK%\include *.cpp ..\..\*.cpp /FeRelease/vulkan_example.exe /FoRelease/ /link /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib
diff --git a/examples/vulkan_example/imgui_impl_glfw_vulkan.cpp b/examples/vulkan_example/imgui_impl_glfw_vulkan.cpp
index ef9da8954..b9e6d78f2 100644
--- a/examples/vulkan_example/imgui_impl_glfw_vulkan.cpp
+++ b/examples/vulkan_example/imgui_impl_glfw_vulkan.cpp
@@ -24,8 +24,7 @@
// GLFW Data
static GLFWwindow* g_Window = NULL;
static double g_Time = 0.0f;
-static bool g_MousePressed[3] = { false, false, false };
-static float g_MouseWheel = 0.0f;
+static bool g_MouseJustPressed[3] = { false, false, false };
// Vulkan Data
static VkAllocationCallbacks* g_Allocator = NULL;
@@ -236,10 +235,10 @@ void ImGui_ImplGlfwVulkan_RenderDrawLists(ImDrawData* draw_data)
VkMappedMemoryRange range[2] = {};
range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range[0].memory = g_VertexBufferMemory[g_FrameIndex];
- range[0].size = vertex_size;
+ range[0].size = VK_WHOLE_SIZE;
range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range[1].memory = g_IndexBufferMemory[g_FrameIndex];
- range[1].size = index_size;
+ range[1].size = VK_WHOLE_SIZE;
err = vkFlushMappedMemoryRanges(g_Device, 2, range);
ImGui_ImplGlfwVulkan_VkResult(err);
vkUnmapMemory(g_Device, g_VertexBufferMemory[g_FrameIndex]);
@@ -301,10 +300,10 @@ void ImGui_ImplGlfwVulkan_RenderDrawLists(ImDrawData* draw_data)
else
{
VkRect2D scissor;
- scissor.offset.x = (int32_t)(pcmd->ClipRect.x);
- scissor.offset.y = (int32_t)(pcmd->ClipRect.y);
+ scissor.offset.x = (int32_t)(pcmd->ClipRect.x) > 0 ? (int32_t)(pcmd->ClipRect.x) : 0;
+ scissor.offset.y = (int32_t)(pcmd->ClipRect.y) > 0 ? (int32_t)(pcmd->ClipRect.y) : 0;
scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
- scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // TODO: + 1??????
+ scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
vkCmdSetScissor(g_CommandBuffer, 0, 1, &scissor);
vkCmdDrawIndexed(g_CommandBuffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
}
@@ -327,12 +326,14 @@ static void ImGui_ImplGlfwVulkan_SetClipboardText(void* user_data, const char* t
void ImGui_ImplGlfwVulkan_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/)
{
if (action == GLFW_PRESS && button >= 0 && button < 3)
- g_MousePressed[button] = true;
+ g_MouseJustPressed[button] = true;
}
-void ImGui_ImplGlfwVulkan_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset)
+void ImGui_ImplGlfwVulkan_ScrollCallback(GLFWwindow*, double xoffset, double yoffset)
{
- g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines.
+ ImGuiIO& io = ImGui::GetIO();
+ io.MouseWheelH += (float)xoffset;
+ io.MouseWheel += (float)yoffset;
}
void ImGui_ImplGlfwVulkan_KeyCallback(GLFWwindow*, int key, int, int action, int mods)
@@ -483,6 +484,7 @@ bool ImGui_ImplGlfwVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
region.imageSubresource.layerCount = 1;
region.imageExtent.width = width;
region.imageExtent.height = height;
+ region.imageExtent.depth = 1;
vkCmdCopyBufferToImage(command_buffer, g_UploadBuffer, g_FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
VkImageMemoryBarrier use_barrier[1] = {};
@@ -540,6 +542,7 @@ bool ImGui_ImplGlfwVulkan_CreateDeviceObjects()
info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
info.minLod = -1000;
info.maxLod = 1000;
+ info.maxAnisotropy = 1.0f;
err = vkCreateSampler(g_Device, &info, g_Allocator, &g_FontSampler);
ImGui_ImplGlfwVulkan_VkResult(err);
}
@@ -748,6 +751,7 @@ bool ImGui_ImplGlfwVulkan_Init(GLFWwindow* window, bool install_callbacks, Im
io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;
io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;
io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;
+ io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT;
io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;
io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;
@@ -809,26 +813,23 @@ void ImGui_ImplGlfwVulkan_NewFrame()
{
double mouse_x, mouse_y;
glfwGetCursorPos(g_Window, &mouse_x, &mouse_y);
- io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.)
+ io.MousePos = ImVec2((float)mouse_x, (float)mouse_y);
}
else
{
- io.MousePos = ImVec2(-1,-1);
+ io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX);
}
for (int i = 0; i < 3; i++)
{
- io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 0; // 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.
- g_MousePressed[i] = false;
+ io.MouseDown[i] = g_MouseJustPressed[i] || glfwGetMouseButton(g_Window, i) != 0; // 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.
+ g_MouseJustPressed[i] = false;
}
- io.MouseWheel = g_MouseWheel;
- g_MouseWheel = 0.0f;
-
// Hide OS mouse cursor if ImGui is drawing it
glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL);
- // Start the frame
+ // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application.
ImGui::NewFrame();
}
diff --git a/examples/vulkan_example/main.cpp b/examples/vulkan_example/main.cpp
index 8116e08c2..6c4ef33fe 100644
--- a/examples/vulkan_example/main.cpp
+++ b/examples/vulkan_example/main.cpp
@@ -12,6 +12,10 @@
#include "imgui_impl_glfw_vulkan.h"
#define IMGUI_MAX_POSSIBLE_BACK_BUFFERS 16
+#define IMGUI_UNLIMITED_FRAME_RATE
+//#ifdef _DEBUG
+//#define IMGUI_VULKAN_DEBUG_REPORT
+//#endif
static VkAllocationCallbacks* g_Allocator = NULL;
static VkInstance g_Instance = VK_NULL_HANDLE;
@@ -22,17 +26,17 @@ static VkSwapchainKHR g_Swapchain = VK_NULL_HANDLE;
static VkRenderPass g_RenderPass = VK_NULL_HANDLE;
static uint32_t g_QueueFamily = 0;
static VkQueue g_Queue = VK_NULL_HANDLE;
+static VkDebugReportCallbackEXT g_Debug_Report = VK_NULL_HANDLE;
-static VkFormat g_ImageFormat = VK_FORMAT_B8G8R8A8_UNORM;
-static VkFormat g_ViewFormat = VK_FORMAT_B8G8R8A8_UNORM;
-static VkColorSpaceKHR g_ColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
+static VkSurfaceFormatKHR g_SurfaceFormat;
static VkImageSubresourceRange g_ImageRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
+static VkPresentModeKHR g_PresentMode;
static VkPipelineCache g_PipelineCache = VK_NULL_HANDLE;
static VkDescriptorPool g_DescriptorPool = VK_NULL_HANDLE;
static int fb_width, fb_height;
-static uint32_t g_BackBufferIndex = 0;
+static uint32_t g_BackbufferIndices[IMGUI_VK_QUEUED_FRAMES]; // keep track of recently rendered swapchain frame indices
static uint32_t g_BackBufferCount = 0;
static VkImage g_BackBuffer[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
static VkImageView g_BackBufferView[IMGUI_MAX_POSSIBLE_BACK_BUFFERS] = {};
@@ -42,7 +46,8 @@ static uint32_t g_FrameIndex = 0;
static VkCommandPool g_CommandPool[IMGUI_VK_QUEUED_FRAMES];
static VkCommandBuffer g_CommandBuffer[IMGUI_VK_QUEUED_FRAMES];
static VkFence g_Fence[IMGUI_VK_QUEUED_FRAMES];
-static VkSemaphore g_Semaphore[IMGUI_VK_QUEUED_FRAMES];
+static VkSemaphore g_PresentCompleteSemaphore[IMGUI_VK_QUEUED_FRAMES];
+static VkSemaphore g_RenderCompleteSemaphore[IMGUI_VK_QUEUED_FRAMES];
static VkClearValue g_ClearValue = {};
@@ -76,14 +81,14 @@ static void resize_vulkan(GLFWwindow* /*window*/, int w, int h)
VkSwapchainCreateInfoKHR info = {};
info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
info.surface = g_Surface;
- info.imageFormat = g_ImageFormat;
- info.imageColorSpace = g_ColorSpace;
+ info.imageFormat = g_SurfaceFormat.format;
+ info.imageColorSpace = g_SurfaceFormat.colorSpace;
info.imageArrayLayers = 1;
info.imageUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
- info.presentMode = VK_PRESENT_MODE_FIFO_KHR;
+ info.presentMode = g_PresentMode;
info.clipped = VK_TRUE;
info.oldSwapchain = old_swapchain;
VkSurfaceCapabilitiesKHR cap;
@@ -93,6 +98,7 @@ static void resize_vulkan(GLFWwindow* /*window*/, int w, int h)
info.minImageCount = (cap.minImageCount + 2 < cap.maxImageCount) ? (cap.minImageCount + 2) : cap.maxImageCount;
else
info.minImageCount = cap.minImageCount + 2;
+
if (cap.currentExtent.width == 0xffffffff)
{
fb_width = w;
@@ -120,14 +126,14 @@ static void resize_vulkan(GLFWwindow* /*window*/, int w, int h)
// Create the Render Pass:
{
VkAttachmentDescription attachment = {};
- attachment.format = g_ViewFormat;
+ attachment.format = g_SurfaceFormat.format;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
- attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
+ attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference color_attachment = {};
color_attachment.attachment = 0;
color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
@@ -150,7 +156,7 @@ static void resize_vulkan(GLFWwindow* /*window*/, int w, int h)
VkImageViewCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
info.viewType = VK_IMAGE_VIEW_TYPE_2D;
- info.format = g_ViewFormat;
+ info.format = g_SurfaceFormat.format;
info.components.r = VK_COMPONENT_SWIZZLE_R;
info.components.g = VK_COMPONENT_SWIZZLE_G;
info.components.b = VK_COMPONENT_SWIZZLE_B;
@@ -184,20 +190,64 @@ static void resize_vulkan(GLFWwindow* /*window*/, int w, int h)
}
}
+#ifdef IMGUI_VULKAN_DEBUG_REPORT
+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)
+{
+ printf("[vulkan] ObjectType: %i\nMessage: %s\n\n", objectType, pMessage );
+ return VK_FALSE;
+}
+#endif // IMGUI_VULKAN_DEBUG_REPORT
+
static void setup_vulkan(GLFWwindow* window)
{
VkResult err;
// Create Vulkan Instance
{
- uint32_t glfw_extensions_count;
- const char** glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extensions_count);
+ uint32_t extensions_count;
+ const char** glfw_extensions = glfwGetRequiredInstanceExtensions(&extensions_count);
+
VkInstanceCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
- create_info.enabledExtensionCount = glfw_extensions_count;
+ create_info.enabledExtensionCount = extensions_count;
create_info.ppEnabledExtensionNames = glfw_extensions;
+
+#ifdef IMGUI_VULKAN_DEBUG_REPORT
+ // enabling multiple validation layers grouped as lunarg standard validation
+ const char* layers[] = {"VK_LAYER_LUNARG_standard_validation"};
+ create_info.enabledLayerCount = 1;
+ create_info.ppEnabledLayerNames = layers;
+
+ // need additional storage for char pointer to debug report extension
+ const char** extensions = (const char**)malloc(sizeof(const char*) * (extensions_count + 1));
+ for (size_t i = 0; i < extensions_count; i++)
+ extensions[i] = glfw_extensions[i];
+ extensions[ extensions_count ] = "VK_EXT_debug_report";
+ create_info.enabledExtensionCount = extensions_count+1;
+ create_info.ppEnabledExtensionNames = extensions;
+#endif // IMGUI_VULKAN_DEBUG_REPORT
+
err = vkCreateInstance(&create_info, g_Allocator, &g_Instance);
check_vk_result(err);
+
+#ifdef IMGUI_VULKAN_DEBUG_REPORT
+ free(extensions);
+
+ // create the debug report callback
+ VkDebugReportCallbackCreateInfoEXT debug_report_ci ={};
+ debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
+ debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
+ debug_report_ci.pfnCallback = debug_report;
+ debug_report_ci.pUserData = NULL;
+
+ // get the proc address of the function pointer, required for used extensions
+ PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT =
+ (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT");
+
+ err = vkCreateDebugReportCallbackEXT( g_Instance, &debug_report_ci, g_Allocator, &g_Debug_Report );
+ check_vk_result(err);
+#endif // IMGUI_VULKAN_DEBUG_REPORT
}
// Create Window Surface
@@ -206,11 +256,21 @@ static void setup_vulkan(GLFWwindow* window)
check_vk_result(err);
}
- // Get GPU (WARNING here we assume the first gpu is one we can use)
+ // Get GPU
{
- uint32_t count = 1;
- err = vkEnumeratePhysicalDevices(g_Instance, &count, &g_Gpu);
+ uint32_t gpu_count;
+ err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, NULL);
check_vk_result(err);
+
+ VkPhysicalDevice* gpus = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * gpu_count);
+ err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus);
+ check_vk_result(err);
+
+ // If a number >1 of GPUs got reported, you should find the best fit GPU for your purpose
+ // e.g. VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU if available, or with the greatest memory available, etc.
+ // for sake of simplicity we'll just take the first one, assuming it has a graphics queue family.
+ g_Gpu = gpus[0];
+ free(gpus);
}
// Get queue
@@ -243,26 +303,83 @@ static void setup_vulkan(GLFWwindow* window)
// Get Surface Format
{
- VkFormat image_view_format[][2] = {{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM}, {VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM}};
+ // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
+ // Assuming that the default behavior is without setting this bit, there is no need for separate Spawchain image and image view format
+ // additionally several new color spaces were introduced with Vulkan Spec v1.0.40
+ // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used
uint32_t count;
vkGetPhysicalDeviceSurfaceFormatsKHR(g_Gpu, g_Surface, &count, NULL);
VkSurfaceFormatKHR *formats = (VkSurfaceFormatKHR*)malloc(sizeof(VkSurfaceFormatKHR) * count);
vkGetPhysicalDeviceSurfaceFormatsKHR(g_Gpu, g_Surface, &count, formats);
- for (size_t i = 0; i < sizeof(image_view_format) / sizeof(image_view_format[0]); i++)
+
+ // first check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
+ if (count == 1)
{
- for (uint32_t j = 0; j < count; j++)
+ if( formats[0].format == VK_FORMAT_UNDEFINED )
{
- if (formats[j].format == image_view_format[i][0])
+ g_SurfaceFormat.format = VK_FORMAT_B8G8R8A8_UNORM;
+ g_SurfaceFormat.colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
+ }
+ else
+ { // no point in searching another format
+ g_SurfaceFormat = formats[0];
+ }
+ }
+ else
+ {
+ // request several formats, the first found will be used
+ VkFormat requestSurfaceImageFormat[] = {VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_R8G8B8_UNORM};
+ VkColorSpaceKHR requestSurfaceColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
+ bool requestedFound = false;
+ for (size_t i = 0; i < sizeof(requestSurfaceImageFormat) / sizeof(requestSurfaceImageFormat[0]); i++)
+ {
+ if( requestedFound ) {
+ break;
+ }
+ for (uint32_t j = 0; j < count; j++)
{
- g_ImageFormat = image_view_format[i][0];
- g_ViewFormat = image_view_format[i][1];
- g_ColorSpace = formats[j].colorSpace;
+ if (formats[j].format == requestSurfaceImageFormat[i] && formats[j].colorSpace == requestSurfaceColorSpace)
+ {
+ g_SurfaceFormat = formats[j];
+ requestedFound = true;
+ }
}
}
+
+ // if none of the requested image formats could be found, use the first available
+ if (!requestedFound)
+ g_SurfaceFormat = formats[0];
}
free(formats);
}
+
+ // Get Present Mode
+ {
+ // Requst a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
+#ifdef IMGUI_UNLIMITED_FRAME_RATE
+ g_PresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
+#else
+ g_PresentMode = VK_PRESENT_MODE_FIFO_KHR;
+#endif
+ uint32_t count = 0;
+ vkGetPhysicalDeviceSurfacePresentModesKHR(g_Gpu, g_Surface, &count, nullptr);
+ VkPresentModeKHR* presentModes = (VkPresentModeKHR*)malloc(sizeof(VkQueueFamilyProperties) * count);
+ vkGetPhysicalDeviceSurfacePresentModesKHR(g_Gpu, g_Surface, &count, presentModes);
+ bool presentModeAvailable = false;
+ for (size_t i = 0; i < count; i++)
+ {
+ if (presentModes[i] == g_PresentMode)
+ {
+ presentModeAvailable = true;
+ break;
+ }
+ }
+ if( !presentModeAvailable )
+ g_PresentMode = VK_PRESENT_MODE_FIFO_KHR; // always available
+ }
+
+
// Create Logical Device
{
int device_extension_count = 1;
@@ -324,7 +441,9 @@ static void setup_vulkan(GLFWwindow* window)
{
VkSemaphoreCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
- err = vkCreateSemaphore(g_Device, &info, g_Allocator, &g_Semaphore[i]);
+ err = vkCreateSemaphore(g_Device, &info, g_Allocator, &g_PresentCompleteSemaphore[i]);
+ check_vk_result(err);
+ err = vkCreateSemaphore(g_Device, &info, g_Allocator, &g_RenderCompleteSemaphore[i]);
check_vk_result(err);
}
}
@@ -364,7 +483,8 @@ static void cleanup_vulkan()
vkDestroyFence(g_Device, g_Fence[i], g_Allocator);
vkFreeCommandBuffers(g_Device, g_CommandPool[i], 1, &g_CommandBuffer[i]);
vkDestroyCommandPool(g_Device, g_CommandPool[i], g_Allocator);
- vkDestroySemaphore(g_Device, g_Semaphore[i], g_Allocator);
+ vkDestroySemaphore(g_Device, g_PresentCompleteSemaphore[i], g_Allocator);
+ vkDestroySemaphore(g_Device, g_RenderCompleteSemaphore[i], g_Allocator);
}
for (uint32_t i = 0; i < g_BackBufferCount; i++)
{
@@ -374,6 +494,13 @@ static void cleanup_vulkan()
vkDestroyRenderPass(g_Device, g_RenderPass, g_Allocator);
vkDestroySwapchainKHR(g_Device, g_Swapchain, g_Allocator);
vkDestroySurfaceKHR(g_Instance, g_Surface, g_Allocator);
+
+#ifdef IMGUI_VULKAN_DEBUG_REPORT
+ // get the proc address of the function pointer, required for used extensions
+ auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT");
+ vkDestroyDebugReportCallbackEXT(g_Instance, g_Debug_Report, g_Allocator);
+#endif // IMGUI_VULKAN_DEBUG_REPORT
+
vkDestroyDevice(g_Device, g_Allocator);
vkDestroyInstance(g_Instance, g_Allocator);
}
@@ -389,7 +516,7 @@ static void frame_begin()
check_vk_result(err);
}
{
- err = vkAcquireNextImageKHR(g_Device, g_Swapchain, UINT64_MAX, g_Semaphore[g_FrameIndex], VK_NULL_HANDLE, &g_BackBufferIndex);
+ err = vkAcquireNextImageKHR(g_Device, g_Swapchain, UINT64_MAX, g_PresentCompleteSemaphore[g_FrameIndex], VK_NULL_HANDLE, &g_BackbufferIndices[g_FrameIndex]);
check_vk_result(err);
}
{
@@ -405,7 +532,7 @@ static void frame_begin()
VkRenderPassBeginInfo info = {};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
info.renderPass = g_RenderPass;
- info.framebuffer = g_Framebuffer[g_BackBufferIndex];
+ info.framebuffer = g_Framebuffer[g_BackbufferIndices[g_FrameIndex]];
info.renderArea.extent.width = fb_width;
info.renderArea.extent.height = fb_height;
info.clearValueCount = 1;
@@ -418,28 +545,17 @@ static void frame_end()
{
VkResult err;
vkCmdEndRenderPass(g_CommandBuffer[g_FrameIndex]);
- {
- VkImageMemoryBarrier barrier = {};
- barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
- barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
- barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
- barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
- barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
- barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
- barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
- barrier.image = g_BackBuffer[g_BackBufferIndex];
- barrier.subresourceRange = g_ImageRange;
- vkCmdPipelineBarrier(g_CommandBuffer[g_FrameIndex], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &barrier);
- }
{
VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
VkSubmitInfo info = {};
info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
info.waitSemaphoreCount = 1;
- info.pWaitSemaphores = &g_Semaphore[g_FrameIndex];
+ info.pWaitSemaphores = &g_PresentCompleteSemaphore[g_FrameIndex];
info.pWaitDstStageMask = &wait_stage;
info.commandBufferCount = 1;
info.pCommandBuffers = &g_CommandBuffer[g_FrameIndex];
+ info.signalSemaphoreCount = 1;
+ info.pSignalSemaphores = &g_RenderCompleteSemaphore[g_FrameIndex];
err = vkEndCommandBuffer(g_CommandBuffer[g_FrameIndex]);
check_vk_result(err);
@@ -448,21 +564,31 @@ static void frame_end()
err = vkQueueSubmit(g_Queue, 1, &info, g_Fence[g_FrameIndex]);
check_vk_result(err);
}
- {
- VkResult res;
- VkSwapchainKHR swapchains[1] = {g_Swapchain};
- uint32_t indices[1] = {g_BackBufferIndex};
- VkPresentInfoKHR info = {};
- info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
- info.swapchainCount = 1;
- info.pSwapchains = swapchains;
- info.pImageIndices = indices;
- info.pResults = &res;
- err = vkQueuePresentKHR(g_Queue, &info);
- check_vk_result(err);
- check_vk_result(res);
- }
- g_FrameIndex = (g_FrameIndex) % IMGUI_VK_QUEUED_FRAMES;
+}
+
+static void frame_present()
+{
+ VkResult err;
+ // If IMGUI_UNLIMITED_FRAME_RATE is defined we present the latest but one frame. Otherwise we present the latest rendered frame
+#ifdef IMGUI_UNLIMITED_FRAME_RATE
+ uint32_t PresentIndex = (g_FrameIndex + IMGUI_VK_QUEUED_FRAMES - 1) % IMGUI_VK_QUEUED_FRAMES;
+#else
+ uint32_t PresentIndex = g_FrameIndex;
+#endif // IMGUI_UNLIMITED_FRAME_RATE
+
+ VkSwapchainKHR swapchains[1] = {g_Swapchain};
+ uint32_t indices[1] = {g_BackbufferIndices[PresentIndex]};
+ VkPresentInfoKHR info = {};
+ info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
+ info.waitSemaphoreCount = 1;
+ info.pWaitSemaphores = &g_RenderCompleteSemaphore[PresentIndex];
+ info.swapchainCount = 1;
+ info.pSwapchains = swapchains;
+ info.pImageIndices = indices;
+ err = vkQueuePresentKHR(g_Queue, &info);
+ check_vk_result(err);
+
+ g_FrameIndex = (g_FrameIndex + 1) % IMGUI_VK_QUEUED_FRAMES;
}
static void error_callback(int error, const char* description)
@@ -499,15 +625,25 @@ int main(int, char**)
init_data.check_vk_result = check_vk_result;
ImGui_ImplGlfwVulkan_Init(window, true, &init_data);
+ // Setup style
+ ImGui::StyleColorsClassic();
+ //ImGui::StyleColorsDark();
+
// Load Fonts
- // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt for more details)
+ // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
+ // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
+ // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
+ // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
+ // - Read 'extra_fonts/README.txt' for more instructions and details.
+ // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//ImGuiIO& io = ImGui::GetIO();
//io.Fonts->AddFontDefault();
+ //io.Fonts->AddFontFromFileTTF("../../extra_fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
- //io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f);
//io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f);
- //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
+ //IM_ASSERT(font != NULL);
// Upload Fonts
{
@@ -536,52 +672,65 @@ int main(int, char**)
ImGui_ImplGlfwVulkan_InvalidateFontUploadObjects();
}
- bool show_test_window = true;
+ bool show_demo_window = true;
bool show_another_window = false;
- ImVec4 clear_color = ImColor(114, 144, 154);
+ ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
+
+ // When IMGUI_UNLIMITED_FRAME_RATE is defined we render into latest image acquired from the swapchain but we display the image which was rendered before.
+ // Hence we must render once and increase the g_FrameIndex without presenting, which we do before entering the render loop.
+ // This is also the reason why frame_end() is split into frame_end() and frame_present(), the later one not being called here.
+#ifdef IMGUI_UNLIMITED_FRAME_RATE
+ ImGui_ImplGlfwVulkan_NewFrame();
+ frame_begin();
+ ImGui_ImplGlfwVulkan_Render(g_CommandBuffer[g_FrameIndex]);
+ frame_end();
+ g_FrameIndex = (g_FrameIndex + 1) % IMGUI_VK_QUEUED_FRAMES;
+#endif // IMGUI_UNLIMITED_FRAME_RATE
// Main loop
while (!glfwWindowShouldClose(window))
{
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
glfwPollEvents();
ImGui_ImplGlfwVulkan_NewFrame();
- // 1. Show a simple window
- // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
+ // 1. Show a simple window.
+ // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets automatically appears in a window called "Debug".
{
static float f = 0.0f;
- ImGui::Text("Hello, world!");
- ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
- ImGui::ColorEdit3("clear color", (float*)&clear_color);
- if (ImGui::Button("Test Window")) show_test_window ^= 1;
- if (ImGui::Button("Another Window")) show_another_window ^= 1;
+ ImGui::Text("Hello, world!"); // Some text (you can use a format string too)
+ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float as a slider from 0.0f to 1.0f
+ ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats as a color
+ if (ImGui::Button("Demo Window")) // Use buttons to toggle our bools. We could use Checkbox() as well.
+ show_demo_window ^= 1;
+ if (ImGui::Button("Another Window"))
+ show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
- // 2. Show another simple window, this time using an explicit Begin/End pair
+ // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name the window.
if (show_another_window)
{
- ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
- ImGui::Text("Hello");
+ ImGui::Text("Hello from another window!");
ImGui::End();
}
- // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
- if (show_test_window)
+ // 3. Show the ImGui demo window. Most of the sample code is in ImGui::ShowDemoWindow().
+ if (show_demo_window)
{
- ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
- ImGui::ShowTestWindow(&show_test_window);
+ ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway. Here we just want to make the demo initial state a bit more friendly!
+ ImGui::ShowDemoWindow(&show_demo_window);
}
- g_ClearValue.color.float32[0] = clear_color.x;
- g_ClearValue.color.float32[1] = clear_color.y;
- g_ClearValue.color.float32[2] = clear_color.z;
- g_ClearValue.color.float32[3] = clear_color.w;
-
+ memcpy(&g_ClearValue.color.float32[0], &clear_color, 4 * sizeof(float));
frame_begin();
ImGui_ImplGlfwVulkan_Render(g_CommandBuffer[g_FrameIndex]);
frame_end();
+ frame_present();
}
// Cleanup
diff --git a/extra_fonts/README.txt b/extra_fonts/README.txt
index 60d33e2e6..2287f6eaa 100644
--- a/extra_fonts/README.txt
+++ b/extra_fonts/README.txt
@@ -1,43 +1,74 @@
- The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' that you can use without any external files.
- The files in this folder are only provided as a convenience, you can use any of your own .TTF files.
+The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer) that is used by default.
+We embed the 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.
+(Note: .OTF support in stb_truetype.h currently doesn't appear to load every font)
- Fonts are rasterized in a single texture at the time of calling either of io.Fonts.GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build().
+Fonts are rasterized in a single texture at the time of calling either of io.Fonts.GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build().
+Also read dear imgui FAQ in imgui.cpp!
----------------------------------
+In this document:
+
+- Using Icons
+- Fonts Loading Instructions
+- FreeType rasterizer, Small font sizes
+- Building Custom Glyph Ranges
+- Remapping Codepoints
+- Embedding Fonts in Source Code
+- Credits/Licences for fonts included in this folder
+- Links, Other fonts
+
+
+---------------------------------------
USING ICONS
----------------------------------
+---------------------------------------
Using an icon font (such as FontAwesome: http://fontawesome.io) is an easy and practical way to use icons in your ImGui application.
- A common pattern is to merge the icon font within your main font, so you can refer to the icons directly from your strings without having to change fonts back and forth.
- To refer to the icon from your C++ code, you can use headers files created by Juliette Foucaut, at https://github.com/juliettef/IconFontCppHeaders
+ A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without
+ having to change fonts back and forth.
+
+ To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut:
+ https://github.com/juliettef/IconFontCppHeaders
+
+ The C++11 version of those files uses the u8"" utf-8 encoding syntax + \u
+ #define ICON_FA_SEARCH u8"\uf002"
+ The pre-C++11 version has the values directly encoded as utf-8:
+ #define ICON_FA_SEARCH "\xEF\x80\x82"
+
+ Example:
// Merge icons into default tool font
#include "IconsFontAwesome.h"
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontDefault();
+
ImFontConfig config;
config.MergeMode = true;
- const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
+ static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges);
+
// Usage, e.g.
ImGui::Text("%s Search", ICON_FA_SEARCH);
----------------------------------
+ See Links below for other icons fonts and related tools.
+
+
+---------------------------------------
FONTS LOADING INSTRUCTIONS
----------------------------------
+---------------------------------------
Load default font with:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontDefault();
- Load .TTF file with:
+ Load .TTF/.OTF file with:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
- Detailed options:
+ For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally)
ImFontConfig config;
config.OversampleH = 3;
@@ -83,20 +114,58 @@
font->DisplayOffset.y += 1; // Render 1 pixel down
----------------------------------
+---------------------------------------
+ FREETYPE RASTERIZER, SMALL FONT SIZES
+---------------------------------------
+
+ Dear Imgui uses stb_truetype.h to rasterize fonts (with optional oversampling).
+ This technique and implementation are not ideal for fonts rendered at _small sizes_, which may appear a little blurry.
+ There is an implementation of the ImFontAtlas builder using FreeType that you can use:
+
+ https://github.com/ocornut/imgui_club
+
+ 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)
+
+
+---------------------------------------
+ BUILDING CUSTOM GLYPH RANGES
+---------------------------------------
+
+ You can use the ImFontAtlas::GlyphRangesBuilder helper to create glyph ranges based on text input.
+ For exemple: 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;
+ ImFontAtlas::GlyphRangesBuilder 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);
+
+
+---------------------------------------
REMAPPING CODEPOINTS
----------------------------------
+---------------------------------------
- All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese CP-1251 for Cyrillic) will not work.
+ All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese, or CP-1251 for Cyrillic) will NOT work!
In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
- You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code.
+ e.g.
+ u8"hello"
+ u8"こんにちは"
+ You may also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code.
----------------------------------
- EMBEDDING FONT IN SOURCE CODE
----------------------------------
+---------------------------------------
+ EMBEDDING FONTS IN SOURCE CODE
+---------------------------------------
- Compile and use 'binary_to_compressed_c.cpp' to create a compressed C style array. Then load the font with:
+ 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 optionally used Base85 encoding to reduce the size of _source code_ but the read-only arrays will be about 20% bigger.
+
+ Then load the font with:
ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);
@@ -105,9 +174,9 @@
ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
----------------------------------
- FONT FILES INCLUDED IN THIS FOLDER
----------------------------------
+---------------------------------------
+ CREDITS/LICENSES FOR FONTS INCLUDED IN THIS FOLDER
+---------------------------------------
Roboto-Medium.ttf
Apache License 2.0
@@ -123,7 +192,7 @@
DroidSans.ttf
Copyright (c) Steve Matteson
Apache License, version 2.0
- http://www.google.com/fonts/specimen/Droid+Sans
+ https://www.fontsquirrel.com/fonts/droid-sans
ProggyClean.ttf
Copyright (c) 2004, 2005 Tristan Grimmer
@@ -142,34 +211,45 @@
SIL OPEN FONT LICENSE Version 1.1
----------------------------------
- LINKS
----------------------------------
+---------------------------------------
+ LINKS, OTHER FONTS
+---------------------------------------
- Icon fonts
+ (Icons) Icon fonts
https://fortawesome.github.io/Font-Awesome/
https://github.com/SamBrishes/kenney-icon-font
https://design.google.com/icons/
+ You can use https://github.com/juliettef/IconFontCppHeaders for C/C++ header files with name #define to access icon codepoint in source code.
- Typefaces for source code beautification
- https://github.com/chrissimpkins/codeface
+ (Icons) IcoMoon - Custom Icon font builder
+ https://icomoon.io/app
+
+ (Regular) Open Sans Fonts
+ https://fonts.google.com/specimen/Open+Sans
+
+ (Regular) Google Noto Fonts (worldwide languages)
+ https://www.google.com/get/noto/
- Programmation fonts
+ (Monospace) Typefaces for source code beautification
+ https://github.com/chrissimpkins/codeface
+
+ (Monospace) Programmation fonts
http://s9w.github.io/font_compare/
- Proggy Programming Fonts
+ (Monospace) Proggy Programming Fonts
http://upperbounds.net
- Inconsolata
+ (Monospace) Inconsolata
http://www.levien.com/type/myfonts/inconsolata.html
- Adobe Source Code Pro: Monospaced font family for user interface and coding environments
+ (Monospace) 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
+ (Monospace) Monospace/Fixed Width Programmer's Fonts
http://www.lowing.org/fonts/
(Japanese) M+ fonts by Coji Morishita are free and include most useful Kanjis you would need.
http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html
Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing).
+
diff --git a/extra_fonts/binary_to_compressed_c.cpp b/extra_fonts/binary_to_compressed_c.cpp
index 79beaad6b..e373e69c6 100644
--- a/extra_fonts/binary_to_compressed_c.cpp
+++ b/extra_fonts/binary_to_compressed_c.cpp
@@ -7,12 +7,17 @@
// Note that even with compression, the output array is likely to be bigger than the binary file..
// Load compressed TTF fonts with ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF()
-// Single file application, build with:
-// # cl.exe binary_to_compressed_c.cpp
-// # gcc binary_to_compressed_c.cpp
-// etc.
+// Build with, e.g:
+// # cl.exe binary_to_compressed_c.cpp
+// # gcc binary_to_compressed_c.cpp
// You can also find a precompiled Windows binary in the binary/demo package available from https://github.com/ocornut/imgui
+// Usage:
+// binary_to_compressed_c.exe [-base85] [-nocompress]
+// Usage example:
+// # binary_to_compressed_c.exe myfont.ttf MyFont > myfont.cpp
+// # binary_to_compressed_c.exe -base85 myfont.ttf MyFont > myfont.cpp
+
#define _CRT_SECURE_NO_WARNINGS
#include
#include
@@ -48,8 +53,7 @@ int main(int argc, char** argv)
}
}
- binary_to_compressed_c(argv[argn], argv[argn+1], use_base85_encoding, use_compression);
- return 1;
+ return binary_to_compressed_c(argv[argn], argv[argn+1], use_base85_encoding, use_compression) ? 0 : 1;
}
char Encode85Byte(unsigned int x)
diff --git a/imconfig.h b/imconfig.h
index 2a956d377..824a81afe 100644
--- a/imconfig.h
+++ b/imconfig.h
@@ -13,23 +13,27 @@
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
+//---- Don't define obsolete functions names. Consider enabling from time to time or when updating to reduce like hood of using already obsolete function/names
+//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+
//---- Include imgui_user.h at the end of imgui.h
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions)
-//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS
-//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS
+//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
+//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
-//---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty)
-//#define IMGUI_DISABLE_TEST_WINDOWS
+//---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
+//---- It is very strongly recommended to NOT disable the demo windows. Please read the comment at the top of imgui_demo.cpp to learn why.
+//#define IMGUI_DISABLE_DEMO_WINDOWS
-//---- Don't define obsolete functions names
-//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+//---- Don't implement ImFormatString(), ImFormatStringV() so you can reimplement them yourself.
+//#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
//---- Pack colors to BGRA instead of RGBA (remove need to post process vertex buffer in back ends)
//#define IMGUI_USE_BGRA_PACKED_COLOR
-//---- Implement STB libraries in a namespace to avoid conflicts
+//---- Implement STB libraries in a namespace to avoid linkage conflicts
//#define IMGUI_STB_NAMESPACE ImGuiStb
//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
@@ -43,6 +47,9 @@
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
+//---- Use 32-bit vertex indices (instead of default: 16-bit) to allow meshes with more than 64K vertices
+//#define ImDrawIdx unsigned int
+
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers.
/*
diff --git a/imgui.cpp b/imgui.cpp
index cd1c12010..076eb4b5c 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -1,14 +1,14 @@
-// dear imgui, v1.50 WIP
+// dear imgui, v1.54 WIP
// (main code and documentation)
-// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code.
-// Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase.
+// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
+// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
// Releases change-log at https://github.com/ocornut/imgui/releases
-// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/772
+// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// This library is free but I need your support to sustain development and maintenance.
-// If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui
+// If you work for a company, please consider financial support, see Readme. For individuals: https://www.patreon.com/imgui
/*
@@ -16,20 +16,24 @@
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE (read me!)
+ - Read first
+ - How to update to a newer version of Dear ImGui
+ - Getting started with integrating Dear ImGui in your code/engine
- API BREAKING CHANGES (read me when you update!)
+ - ISSUES & TODO LIST
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- How can I help?
- - How do I update to a newer version of ImGui?
- - What is ImTextureID and how do I display an image?
- - I integrated ImGui in my engine and the text or lines are blurry..
- - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- - 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.
- - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
+ - How can I dipslay an image? What is ImTextureID, how does it works?
+ - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels and the ID stack.
+ - How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
- How can I load a different font than the default?
- How can I easily use icons in my application?
- How can I load multiple fonts?
- How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
+ - How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables)
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
+ - I integrated Dear ImGui in my engine and the text or lines are blurry..
+ - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- ISSUES & TODO-LIST
- CODE
@@ -37,112 +41,169 @@
MISSION STATEMENT
=================
- - easy to use to create code-driven and data-driven tools
- - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
- - easy to hack and improve
- - minimize screen real-estate usage
- - minimize setup and maintenance
- - minimize state storage on user side
- - portable, minimize dependencies, run on target (consoles, phones, etc.)
- - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything)
- - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html
+ - Easy to use to create code-driven and data-driven tools
+ - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
+ - Easy to hack and improve
+ - Minimize screen real-estate usage
+ - Minimize setup and maintenance
+ - Minimize state storage on user side
+ - Portable, minimize dependencies, run on target (consoles, phones, etc.)
+ - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window, opening a tree node
+ for the first time, etc. but a typical frame won't allocate anything)
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- - doesn't look fancy, doesn't animate
- - limited layout features, intricate layouts are typically crafted in code
- - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction.
+ - Doesn't look fancy, doesn't animate
+ - Limited layout features, intricate layouts are typically crafted in code
END-USER GUIDE
==============
- - double-click title bar to collapse window
- - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin()
- - click and drag on lower right corner to resize window
- - click and drag on any empty space to move window
- - double-click/double-tap on lower right corner grip to auto-fit to content
- - TAB/SHIFT+TAB to cycle through keyboard editable fields
- - use mouse wheel to scroll
- - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true)
- - CTRL+Click on a slider or drag box to input value as text
- - text editor:
+ - Double-click on title bar to collapse window.
+ - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
+ - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
+ - Click and drag on any empty space to move window.
+ - TAB/SHIFT+TAB to cycle through keyboard editable fields.
+ - CTRL+Click on a slider or drag box to input value as text.
+ - Use mouse wheel to scroll.
+ - Text editor:
- Hold SHIFT or use mouse to select text.
- - CTRL+Left/Right to word jump
- - CTRL+Shift+Left/Right to select words
- - CTRL+A our Double-Click to select all
- - CTRL+X,CTRL+C,CTRL+V to use OS clipboard
- - CTRL+Z,CTRL+Y to undo/redo
- - ESCAPE to revert text to its original value
+ - CTRL+Left/Right to word jump.
+ - CTRL+Shift+Left/Right to select words.
+ - CTRL+A our Double-Click to select all.
+ - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
+ - CTRL+Z,CTRL+Y to undo/redo.
+ - ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
+ - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
PROGRAMMER GUIDE
================
- - read the FAQ below this section!
- - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs.
- - call and read ImGui::ShowTestWindow() for demo code demonstrating most features.
- - see examples/ folder for standalone sample applications. Prefer reading examples/opengl2_example/ first as it is the simplest.
- you may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
- - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme).
+ READ FIRST
- - getting started:
- - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'.
- - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory.
- - every frame:
- 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input'
- 2/ call ImGui::NewFrame() as early as you can!
- 3/ use any ImGui function you want between NewFrame() and Render()
- 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure.
- (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.)
- - all rendering information are stored into command-lists until ImGui::Render() is called.
- - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide.
- - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application.
- - refer to the examples applications in the examples/ folder for instruction on how to setup your code.
- - a typical application skeleton may be:
+ - Read the FAQ below this section!
+ - Your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention
+ on your side, no state duplication, less sync, less bugs.
+ - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
+ - You can learn about immediate-mode gui principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861
- // Application init
+ HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
+
+ - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
+ - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
+ If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API.
+ If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it.
+ Please report any issue to the GitHub page!
+ - Try to keep your copy of dear imgui reasonably up to date.
+
+ GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
+
+ - Add the Dear ImGui source files to your projects, using your preferred build system.
+ It is recommended you build the .cpp files as part of your project and not as a library.
+ - You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types.
+ - See examples/ folder for standalone sample applications.
+ - You may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
+ - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
+
+ - Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize
+ (application resolution). Later on you will fill your keyboard mapping, clipboard handlers, and other advanced features but for a basic
+ integration you don't need to worry about it all.
+ - Init: call io.Fonts->GetTexDataAsRGBA32(...), it will build the font atlas texture, then load the texture pixels into graphics memory.
+ - Every frame:
+ - In your main loop as early a possible, fill the IO fields marked 'Input' (e.g. mouse position, buttons, keyboard info, etc.)
+ - Call ImGui::NewFrame() to begin the frame
+ - You can use any ImGui function you want between NewFrame() and Render()
+ - Call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your io.RenderDrawListFn handler.
+ (Even if you don't render, call Render() and ignore the callback, or call EndFrame() instead. Otherwhise some features will break)
+ - All rendering information are stored into command-lists until ImGui::Render() is called.
+ - Dear ImGui never touches or knows about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide.
+ - Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases
+ of your own application.
+ - Refer to the examples applications in the examples/ folder for instruction on how to setup your code.
+ - A minimal application skeleton may be:
+
+ // Application init
+ ImGuiIO& io = ImGui::GetIO();
+ io.DisplaySize.x = 1920.0f;
+ io.DisplaySize.y = 1280.0f;
+ io.RenderDrawListsFn = MyRenderFunction; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access render data.
+ // TODO: Fill others settings of the io structure later.
+
+ // Load texture atlas (there is a default font so you don't need to care about choosing a font yet)
+ unsigned char* pixels;
+ int width, height;
+ io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
+ // TODO: At this points you've got the texture data and you need to upload that your your graphic system:
+ MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA)
+ // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'. This will be passed back to your via the renderer.
+ io.Fonts->TexID = (void*)texture;
+
+ // Application main loop
+ while (true)
+ {
+ // Setup low-level inputs (e.g. on Win32, GetKeyboardState(), or write to those fields from your Windows message loop handlers, etc.)
ImGuiIO& io = ImGui::GetIO();
- io.DisplaySize.x = 1920.0f;
- io.DisplaySize.y = 1280.0f;
- io.IniFilename = "imgui.ini";
- io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data.
- // TODO: Fill others settings of the io structure
+ io.DeltaTime = 1.0f/60.0f;
+ io.MousePos = mouse_pos;
+ io.MouseDown[0] = mouse_button_0;
+ io.MouseDown[1] = mouse_button_1;
- // Load texture atlas
- // There is a default font so you don't need to care about choosing a font yet
- unsigned char* pixels;
- int width, height;
- io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
- // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system
- // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'
+ // Call NewFrame(), after this point you can use ImGui::* functions anytime
+ ImGui::NewFrame();
- // Application main loop
- while (true)
- {
- // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.)
- // TODO: fill all fields of IO structure and call NewFrame
- ImGuiIO& io = ImGui::GetIO();
- io.DeltaTime = 1.0f/60.0f;
- io.MousePos = mouse_pos;
- io.MouseDown[0] = mouse_button_0;
- io.MouseDown[1] = mouse_button_1;
- io.KeysDown[i] = ...
+ // Most of your application code here
+ MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
+ MyGameRender(); // may use any ImGui functions as well!
+
+ // Render & swap video buffers
+ ImGui::Render();
+ SwapBuffers();
+ }
- // 2) call NewFrame(), after this point you can use ImGui::* functions anytime
- ImGui::NewFrame();
+ - A minimal render function skeleton may be:
- // 3) most of your application code here
- MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
- MyGameRender(); // may use any ImGui functions
+ void void MyRenderFunction(ImDrawData* draw_data)
+ {
+ // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
+ // TODO: Setup viewport, orthographic projection matrix
+ // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
+ {
+ const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
+ const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
+ for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
+ {
+ const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
+ if (pcmd->UserCallback)
+ {
+ pcmd->UserCallback(cmd_list, pcmd);
+ }
+ else
+ {
+ // The texture for the draw call is specified by pcmd->TextureId.
+ // The vast majority of draw calls with use the imgui texture atlas, which value you have set yourself during initialization.
+ MyEngineBindTexture(pcmd->TextureId);
- // 4) render & swap video buffers
- ImGui::Render();
- SwapBuffers();
- }
+ // We are using scissoring to clip some objects. All low-level graphics API supports it.
+ // If your engine doesn't support scissoring yet, you will get some small glitches (some elements outside their bounds) which you can fix later.
+ MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
+
+ // Render 'pcmd->ElemCount/3' indexed triangles.
+ // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits if your engine doesn't support 16-bits indices.
+ MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
+ }
+ idx_buffer += pcmd->ElemCount;
+ }
+ }
+ }
+
+ - The examples/ folders contains many functional implementation of the pseudo-code above.
+ - When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated.
+ They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide
+ mouse inputs from the rest of your application. Read the FAQ below for more information about those flags.
- - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your
- inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information.
API BREAKING CHANGES
@@ -152,6 +213,50 @@
Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
Also read releases logs https://github.com/ocornut/imgui/releases for more details.
+ - 2018/01/11 (1.54) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
+ - 2018/01/11 (1.54) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
+ - 2018/01/03 (1.54) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
+ - 2017/12/29 (1.54) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
+ - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
+ - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
+ - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
+ - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
+ - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
+ - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
+ - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
+ - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
+ - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
+ - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
+ - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
+ Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
+ - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
+ - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
+ - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
+ - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
+ - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
+ - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
+ - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
+ removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
+ - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
+ - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
+ - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
+ - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
+ - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
+ - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
+ - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
+ - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
+ - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
+ - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
+ - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
+ - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
+ - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
+ - 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))'
+ - 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.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
@@ -260,90 +365,80 @@
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
+ ISSUES & TODO-LIST
+ ==================
+ See TODO.txt
+
+
FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
======================================
Q: How can I help?
- A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help!
- - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time.
+ A: - If you are experienced with Dear ImGui and C++, look at the github issues, or TODO.txt and see how you want/can help!
+ - Convince your company to fund development time! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README.
+ - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
+ You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1269). Visuals are ideal as they inspire other programmers.
+ But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
+ - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
- Q: How do I update to a newer version of ImGui?
- A: Overwrite the following files:
- imgui.cpp
- imgui.h
- imgui_demo.cpp
- imgui_draw.cpp
- imgui_internal.h
- stb_rect_pack.h
- stb_textedit.h
- stb_truetype.h
- Don't overwrite imconfig.h if you have made modification to your copy.
- Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name
- in the code, there will likely be a comment about it. Please report any issue to the GitHub page!
-
- Q: What is ImTextureID and how do I display an image?
+ Q: How can I display an image? What is ImTextureID, how does it works?
A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
- ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
+ Dear ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
(c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
- ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
+ Dear ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
+ You may call ImGui::ShowMetricsWindow() to explore active draw lists and visualize/understand how the draw data is generated.
It is your responsibility to get textures uploaded to your GPU.
- Q: I integrated ImGui in my engine and the text or lines are blurry..
- A: 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: Can I have multiple widgets with the same label? Can I have widget without a label?
+ A: Yes. A primer on labels and the ID stack...
- Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
+ - Elements that are typically not clickable, such as Text() items don't need an ID.
- Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes)
- A: Yes. A primer on the use of labels/IDs in ImGui..
+ - Interactive widgets require state to be carried over multiple frames (most typically Dear ImGui often needs to remember what is
+ the "active" widget). to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
- - Elements that are not clickable, such as Text() items don't need an ID.
+ Button("OK"); // Label = "OK", ID = hash of "OK"
+ Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
- - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget).
- to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
-
- 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. so no conflict can happen if you have two buttons called "OK" in two different windows
- or in two different locations of a tree.
+ - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK"
+ in two different windows or in two different locations of a tree.
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
- Button("OK"); // ID collision! Both buttons will be treated as the same.
+ Button("OK"); // ID collision! Both buttons will be treated as the same.
Fear not! this is easy to solve and there are many ways to solve it!
- - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases.
- use "##" to pass a complement to the ID that won't be visible to the end-user:
+ - When passing a label you can optionally specify extra unique 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 which items are going to be created.
- Button("Play"); // Label = "Play", ID = hash of "Play"
- Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
- Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
+ Button("Play"); // Label = "Play", ID = hash of "Play"
+ Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
+ Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
- If you want to completely hide the label, but still need an ID:
- Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
+ Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
- 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 (and windows are uniquely identified by their ID.. obviously)
+ 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)
- sprintf(buf, "My game (%f FPS)###MyGame");
+ sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable label, ID = hash of "MyGame"
- Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
- You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack!
+ You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of _everything_ in the ID stack!
for (int i = 0; i < 100; i++)
{
@@ -389,27 +484,33 @@
- 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 displaying a single object that may change over time (1-1 relationship), 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. experiment and see what makes more sense!
+ e.g. when displaying a single object that may change over time (dynamic 1-1 relationship), 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.
+ experiment and see what makes more sense!
- Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application?
- A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine.
- When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available.
- ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow().
- (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically have 'io.WantcaptureKeyboard=false'.
- Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.)
+ Q: How can I tell when Dear ImGui wants my mouse/keyboard inputs VS when I can pass them to my application?
+ A: You can read the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'ioWantTextInput' flags from the ImGuiIO structure.
+ - When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application.
+ - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
+ Preferably read the flags after calling ImGui::NewFrame() to avoid them lagging by one frame. But reading those flags before calling NewFrame() is
+ also generally ok, as the bool toggles fairly rarely and you don't generally expect to interact with either Dear ImGui or your application during
+ the same frame when that transition occurs. Dear ImGui is tracking dragging and widget activity that may occur outside the boundary of a window,
+ so 'io.WantCaptureMouse' is more accurate and correct than checking if a window is hovered.
+ (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically
+ have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
+ were for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
- A: Use the font atlas to load the TTF file you want:
+ A: Use the font atlas to load the TTF/OTF file you want:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
Q: How can I easily use icons in my application?
- A: 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.
- Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions.
+ A: 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. Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions and useful header files.
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
@@ -427,7 +528,8 @@
ImFontConfig config;
config.OversampleH = 3;
config.OversampleV = 1;
- config.GlyphExtraSpacing.x = 1.0f;
+ config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up
+ config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one (e.g. for icon fonts)
@@ -440,174 +542,54 @@
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
- All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will not work.
- In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
- You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code.
- io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters
- io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
- io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application
+ // Add default Japanese ranges
+ io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
+
+ // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
+ ImVector ranges;
+ ImFontAtlas::GlyphRangesBuilder 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);
- As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that.
+ All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax.
+ Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
+ Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
+
+ Text input: it is up to your application to pass the right character code to io.AddInputCharacter(). The applications in examples/ are doing that.
+ For languages using IME, on Windows you can copy the Hwnd of your application to io.ImeWindowHandle.
+ The default implementation of io.ImeSetInputScreenPosFn() on Windows will set your IME position correctly.
+
+ Q: How can I preserve my Dear ImGui context across reloading a DLL? (loss of the global/static variables)
+ A: Create your own context 'ctx = CreateContext()' + 'SetCurrentContext(ctx)' and your own font atlas 'ctx->GetIO().Fonts = new ImFontAtlas()'
+ so you don't rely on the default globals.
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha,
- then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
+ A: - You can create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag,
+ push a ImGuiCol_WindowBg with zero alpha, then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
+ - You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows.
+ - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData.
- - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code.
- - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug"
- - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings)
+ Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
+ A: 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 some elements are clipping or disappearing when I move windows around..
+ A: You are probably mishandling the clipping rectangles in your render function.
+ Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
+
+
+ - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
+ this is also useful to set yourself in the context of another window (to get/set other settings)
+ - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
+ - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
+ of a deep nested inner loop in your code.
- tip: you can call Render() multiple times (e.g for VR renders).
- - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui!
+ - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
-
- ISSUES & TODO-LIST
- ==================
- Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues
- The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point it usually moves to the github)
-
- - doc: add a proper documentation+regression testing system (#435)
- - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass.
- - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690)
- - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify.
- - window: allow resizing of child windows (possibly given min/max for each axis?)
- - window: background options for child windows, border option (disable rounding)
- - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip)
- - window: resizing from any sides? + mouse cursor directives for app.
-!- window: begin with *p_open == false should return false.
- - window: get size/pos helpers given names (see discussion in #249)
- - window: a collapsed window can be stuck behind the main menu bar?
- - window: when window is small, prioritize resize button over close button.
- - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later.
- - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic.
- - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd.
- - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command).
-!- scrolling: allow immediately effective change of scroll if we haven't appended items yet
- - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319)
- - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc.
- - widgets: clean up widgets internal toward exposing everything.
- - widgets: add disabled and read-only modes (#211)
- - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them.
-!- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows).
- - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes
- - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode?
- - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile.
- - 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: flag to disable live update of the user buffer (also applies to float/int text input)
- - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text?
- - input text: add ImGuiInputTextFlags_EnterToApply? (off #218)
- - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725)
- - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc).
- - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200)
- - input text multi-line: line numbers? status bar? (follow up on #200)
- - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725)
- - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position.
- - input number: optional range min/max for Input*() functions
- - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled)
- - input number: use mouse wheel to step up/down
- - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack.
- - button: provide a button that looks framed.
- - text: proper alignment options
- - 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?
- - layout: horizontal layout helper (#97)
- - layout: horizontal flow until no space left (#404)
- - layout: more generic alignment state (left/right/centered) for single items?
- - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding.
- - layout: BeginGroup() needs a border option.
- - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125)
- - columns: add a conditional parameter to SetColumnOffset() (#513, #125)
- - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125)
- - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125)
- - columns: user specify columns size (#513, #125)
- - columns: flag to add horizontal separator above/below?
- - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets)
- - combo: sparse combo boxes (via function call?) / iterators
- - combo: contents should extends to fit label if combo widget is small
- - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203)
- - listbox: multiple selection
- - listbox: user may want to initial scroll to focus on the one selected value?
- - listbox: keyboard navigation.
- - listbox: scrolling should track modified selection.
-!- 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: add variant using global identifier similar to Begin/End (#402)
- - popups: border options. richer api like BeginChild() perhaps? (#197)
- - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred button" and may teleport when moving mouse
- - menus: local shortcuts, global shortcuts (#456, #126)
- - menus: icons
- - menus: menubars: some sort of priority / effect of main menu-bar on desktop size?
- - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely
- - statusbar: add a per-window status bar helper similar to what menubar does.
- - tabs (#261, #351)
- - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y)
-!- color: the color helpers/typing is a mess and needs sorting out.
- - color: add a better color picker (#346)
- - node/graph editor (#306)
- - pie menus patterns (#434)
- - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479)
- - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals)
- - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots)
- - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value)
- - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID)
- - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt()
- - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar).
- - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate.
- - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign)
- - slider & drag: int data passing through a float
- - drag float: up/down axis
- - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits)
- - tree node / optimization: avoid formatting when clipped.
- - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling.
- - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings?
- - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits?
- - 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)
- - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249)
- - settings: write more decent code to allow saving/loading new fields
- - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file
- - style: add window shadows.
- - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding.
- - style: color-box not always square?
- - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc.
- - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation).
- - style: global scale setting.
- - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle
- - text: simple markup language for color change?
- - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier.
- - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance
- - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback.
- - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize)
- - font: fix AddRemapChar() to work before font has been built.
- - log: LogButtons() options for specifying depth and/or hiding depth slider
- - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope)
- - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard)
- - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs.
- - filters: set a current filter that tree node can automatically query to hide themselves
- - filters: handle wildcards (with implicit leading/trailing *), regexps
- - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus)
-!- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing
- - keyboard: full keyboard navigation and focus. (#323)
- - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622)
- - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame)
- - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71)
- - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style).
- - input: support track pad style scrolling & slider edit.
- - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL)
- - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon?
- - misc: provide HoveredTime and ActivatedTime to ease the creation of animations.
- - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438)
- - style editor: color child window height expressed in multiple of line height.
- - remote: make a system like RemoteImGui first-class citizen/project (#75)
- - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?)
- - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack.
- - examples: directx9: save/restore device state more thoroughly.
- - examples: window minimize, maximize (#583)
- - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335)
- - optimization: use another hash function than crc32, e.g. FNV1a
- - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)?
- - optimization: turn some the various stack vectors into statically-sized arrays
- - optimization: better clipping for multi-component widgets
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
@@ -616,7 +598,6 @@
#include "imgui.h"
#define IMGUI_DEFINE_MATH_OPERATORS
-#define IMGUI_DEFINE_PLACEMENT_NEW
#include "imgui_internal.h"
#include // toupper, isprint
@@ -637,12 +618,14 @@
// Clang warnings with -Weverything
#ifdef __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 ok.
+#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 it.
#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' //
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
@@ -651,53 +634,44 @@
#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 "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
+#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#endif
//-------------------------------------------------------------------------
// Forward Declarations
//-------------------------------------------------------------------------
-static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL);
-
-static void PushMultiItemsWidths(int components, float w_full = 0.0f);
-static float GetDraggedColumnOffset(int column_index);
-
static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
static ImFont* GetDefaultFont();
-static void SetCurrentFont(ImFont* font);
static void SetCurrentWindow(ImGuiWindow* window);
+static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x);
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
-static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond);
-static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond);
-static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond);
-static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs);
+static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
+static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
+static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
+static ImGuiWindow* FindHoveredWindow(ImVec2 pos);
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
-static inline bool IsWindowContentHoverable(ImGuiWindow* window);
-static void ClearSetNextWindowData();
static void CheckStacksSize(ImGuiWindow* window, bool write);
-static void Scrollbar(ImGuiWindow* window, bool horizontal);
+static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
-static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list);
-static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window);
-static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window);
+static void AddDrawListToDrawData(ImVector* out_render_list, ImDrawList* draw_list);
+static void AddWindowToDrawData(ImVector* out_render_list, ImGuiWindow* window);
+static void AddWindowToSortedBuffer(ImVector* out_sorted_windows, ImGuiWindow* window);
+
+static ImGuiWindowSettings* AddWindowSettings(const char* name);
-static ImGuiIniData* FindWindowSettings(const char* name);
-static ImGuiIniData* AddWindowSettings(const char* name);
static void LoadIniSettingsFromDisk(const char* ini_filename);
+static void LoadIniSettingsFromMemory(const char* buf);
static void SaveIniSettingsToDisk(const char* ini_filename);
-static void MarkIniSettingsDirty();
+static void SaveIniSettingsToMemory(ImVector& out_buf);
+static void MarkIniSettingsDirty(ImGuiWindow* window);
-static void PushColumnClipRect(int column_index = -1);
static ImRect GetVisibleRect();
-static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags);
-static void CloseInactivePopups();
+static void CloseInactivePopups(ImGuiWindow* ref_window);
static void ClosePopupToLevel(int remaining);
-static void ClosePopup(ImGuiID id);
-static bool IsPopupOpen(ImGuiID id);
static ImGuiWindow* GetFrontMostModalRootWindow();
-static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid);
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data);
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
@@ -708,6 +682,12 @@ static inline void DataTypeFormatString(ImGuiDataType data_type, void* data
static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2);
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
+namespace ImGui
+{
+static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
+static void FocusFrontMostActiveWindow(ImGuiWindow* ignore_window);
+}
+
//-----------------------------------------------------------------------------
// Platform dependent default implementations
//-----------------------------------------------------------------------------
@@ -720,12 +700,13 @@ static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
// Context
//-----------------------------------------------------------------------------
-// Default font atlas storage .
+// Default font atlas storage.
// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable.
static ImFontAtlas GImDefaultFontAtlas;
// Default context storage + current context pointer.
// Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext()
+// If you are hot-reloading this code in a DLL you will lose the static/global variables. Create your own context+font atlas instead of relying on those default (see FAQ entry "How can I preserve my ImGui context across reloading a DLL?").
// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by:
// - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
// - or: Changing this variable to be TLS. You may #define GImGui in imconfig.h for further custom hackery. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
@@ -742,12 +723,17 @@ 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
+ WindowBorderSize = 0.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
- WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
- ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
+ ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
+ ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
+ PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
+ PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
+ FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
@@ -761,52 +747,34 @@ ImGuiStyle::ImGuiStyle()
DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
DisplaySafeAreaPadding = ImVec2(4,4); // 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.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
- AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
- CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
+ AntiAliasedFill = true; // Enable anti-aliasing on 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.
- Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
- Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
- Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f);
- Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
- Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
- Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f);
- Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
- Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
- Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f);
- Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f);
- Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
- Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
- Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
- Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
- Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
- Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
- Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
- Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f);
- Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f);
- Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
- Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
- Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
- Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f);
- Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f);
- Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
- Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
- Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
- Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);
- Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
- Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f);
- Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f);
- Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
- Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
- Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
- Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
- Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
- Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
- Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
- Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
- Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
- Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
- Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
- Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
+ ImGui::StyleColorsClassic(this);
+}
+
+// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
+// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
+void ImGuiStyle::ScaleAllSizes(float scale_factor)
+{
+ WindowPadding = ImFloor(WindowPadding * scale_factor);
+ WindowRounding = ImFloor(WindowRounding * scale_factor);
+ WindowMinSize = ImFloor(WindowMinSize * scale_factor);
+ ChildRounding = ImFloor(ChildRounding * scale_factor);
+ PopupRounding = ImFloor(PopupRounding * scale_factor);
+ FramePadding = ImFloor(FramePadding * scale_factor);
+ FrameRounding = ImFloor(FrameRounding * scale_factor);
+ ItemSpacing = ImFloor(ItemSpacing * scale_factor);
+ ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
+ TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
+ IndentSpacing = ImFloor(IndentSpacing * scale_factor);
+ ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
+ ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
+ ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
+ GrabMinSize = ImFloor(GrabMinSize * scale_factor);
+ GrabRounding = ImFloor(GrabRounding * scale_factor);
+ DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
+ DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
}
ImGuiIO::ImGuiIO()
@@ -814,31 +782,36 @@ ImGuiIO::ImGuiIO()
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
+ // Settings
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
- Fonts = &GImDefaultFontAtlas;
- FontGlobalScale = 1.0f;
- FontDefault = NULL;
- DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
- MousePos = ImVec2(-1,-1);
- MousePosPrev = ImVec2(-1,-1);
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
- MouseDragThreshold = 6.0f;
- for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++)
- MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
- for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++)
- KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.250f;
KeyRepeatRate = 0.050f;
UserData = NULL;
- // User functions
+ Fonts = &GImDefaultFontAtlas;
+ FontGlobalScale = 1.0f;
+ FontDefault = NULL;
+ FontAllowUserScaling = false;
+ DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
+ DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f);
+
+ // Advanced/subtle behaviors
+#ifdef __APPLE__
+ OptMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
+#else
+ OptMacOSXBehaviors = false;
+#endif
+ OptCursorBlink = true;
+
+ // Settings (User Functions)
RenderDrawListsFn = NULL;
MemAllocFn = malloc;
MemFreeFn = free;
@@ -846,11 +819,14 @@ ImGuiIO::ImGuiIO()
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
+ ImeWindowHandle = NULL;
- // Set OS X style defaults based on __APPLE__ compile time flag
-#ifdef __APPLE__
- OSXBehaviors = true;
-#endif
+ // Input (NB: we already have memset zero the entire structure)
+ MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
+ MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
+ MouseDragThreshold = 6.0f;
+ for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
+ for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
@@ -890,7 +866,21 @@ void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
#define IM_NEWLINE "\n"
#endif
-bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c)
+ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
+{
+ ImVec2 ap = p - a;
+ ImVec2 ab_dir = b - a;
+ float ab_len = sqrtf(ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y);
+ ab_dir *= 1.0f / ab_len;
+ float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
+ if (dot < 0.0f)
+ return a;
+ if (dot > ab_len)
+ return b;
+ return a + ab_dir * dot;
+}
+
+bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
@@ -898,6 +888,33 @@ bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, cons
return ((b1 == b2) && (b2 == b3));
}
+void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
+{
+ ImVec2 v0 = b - a;
+ ImVec2 v1 = c - a;
+ ImVec2 v2 = p - a;
+ const float denom = v0.x * v1.y - v1.x * v0.y;
+ out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
+ out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
+ out_u = 1.0f - out_v - out_w;
+}
+
+ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
+{
+ ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
+ ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
+ ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
+ float dist2_ab = ImLengthSqr(p - proj_ab);
+ float dist2_bc = ImLengthSqr(p - proj_bc);
+ float dist2_ca = ImLengthSqr(p - proj_ca);
+ float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
+ if (m == dist2_ab)
+ return proj_ab;
+ if (m == dist2_bc)
+ return proj_bc;
+ return proj_ca;
+}
+
int ImStricmp(const char* str1, const char* str2)
{
int d;
@@ -905,25 +922,33 @@ int ImStricmp(const char* str1, const char* str2)
return d;
}
-int ImStrnicmp(const char* str1, const char* str2, int count)
+int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
-void ImStrncpy(char* dst, const char* src, int count)
+void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1) return;
- strncpy(dst, src, (size_t)count);
+ strncpy(dst, src, count);
dst[count-1] = 0;
}
char* ImStrdup(const char *str)
{
size_t len = strlen(str) + 1;
- void* buff = ImGui::MemAlloc(len);
- return (char*)memcpy(buff, (const void*)str, len);
+ void* buf = ImGui::MemAlloc(len);
+ return (char*)memcpy(buf, (const void*)str, len);
+}
+
+char* ImStrchrRange(const char* str, const char* str_end, char c)
+{
+ for ( ; str < str_end; str++)
+ if (*str == c)
+ return (char*)str;
+ return NULL;
}
int ImStrlenW(const ImWchar* str)
@@ -962,31 +987,47 @@ const char* ImStristr(const char* haystack, const char* haystack_end, const char
return NULL;
}
-
-// MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
-// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
-int ImFormatString(char* buf, int buf_size, const char* fmt, ...)
+static const char* ImAtoi(const char* src, int* output)
+{
+ int negative = 0;
+ if (*src == '-') { negative = 1; src++; }
+ if (*src == '+') { src++; }
+ int v = 0;
+ while (*src >= '0' && *src <= '9')
+ v = (v * 10) + (*src++ - '0');
+ *output = negative ? -v : v;
+ return src;
+}
+
+// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
+// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
+// B) When buf==NULL vsnprintf() will return the output size.
+#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
+int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
- IM_ASSERT(buf_size > 0);
va_list args;
va_start(args, fmt);
int w = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
- if (w == -1 || w >= buf_size)
- w = buf_size - 1;
+ if (buf == NULL)
+ return w;
+ if (w == -1 || w >= (int)buf_size)
+ w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
-int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args)
+int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
- IM_ASSERT(buf_size > 0);
int w = vsnprintf(buf, buf_size, fmt, args);
- if (w == -1 || w >= buf_size)
- w = buf_size - 1;
+ if (buf == NULL)
+ return w;
+ if (w == -1 || w >= (int)buf_size)
+ w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
+#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
// Pass data_size==0 for zero-terminated strings
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
@@ -1230,18 +1271,36 @@ ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
- ImVec4 c = GImGui->Style.Colors[idx];
- c.w *= GImGui->Style.Alpha * alpha_mul;
+ ImGuiStyle& style = GImGui->Style;
+ ImVec4 c = style.Colors[idx];
+ c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
+ ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
- c.w *= GImGui->Style.Alpha;
+ c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
+const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
+{
+ ImGuiStyle& style = GImGui->Style;
+ return style.Colors[idx];
+}
+
+ImU32 ImGui::GetColorU32(ImU32 col)
+{
+ float style_alpha = GImGui->Style.Alpha;
+ if (style_alpha >= 1.0f)
+ return col;
+ int a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
+ a = (int)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
+ return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
+}
+
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
@@ -1249,12 +1308,12 @@ void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float&
float K = 0.f;
if (g < b)
{
- const float tmp = g; g = b; b = tmp;
+ ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
- const float tmp = r; r = g; g = tmp;
+ ImSwap(r, g);
K = -2.f / 6.f - K;
}
@@ -1353,23 +1412,18 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int*
//-----------------------------------------------------------------------------
// ImGuiStorage
-//-----------------------------------------------------------------------------
-
// Helper: Key->value storage
-void ImGuiStorage::Clear()
-{
- Data.clear();
-}
+//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImVector::iterator LowerBound(ImVector& data, ImGuiID key)
{
ImVector::iterator first = data.begin();
ImVector::iterator last = data.end();
- int count = (int)(last - first);
+ size_t count = (size_t)(last - first);
while (count > 0)
{
- int count2 = count / 2;
+ size_t count2 = count >> 1;
ImVector::iterator mid = first + count2;
if (mid->key < key)
{
@@ -1384,6 +1438,23 @@ static ImVector::iterator LowerBound(ImVectorkey > ((const Pair*)rhs)->key) return +1;
+ if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
+ return 0;
+ }
+ };
+ if (Data.Size > 1)
+ qsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
+}
+
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImVector::iterator it = LowerBound(const_cast&>(Data), key);
@@ -1599,12 +1670,12 @@ bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
#endif
// Helper: Text buffer for logging/accumulating text
-void ImGuiTextBuffer::appendv(const char* fmt, va_list args)
+void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
- int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
+ int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
return;
@@ -1617,22 +1688,22 @@ void ImGuiTextBuffer::appendv(const char* fmt, va_list args)
}
Buf.resize(needed_sz);
- ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy);
+ ImFormatStringV(&Buf[write_off - 1], len + 1, fmt, args_copy);
}
-void ImGuiTextBuffer::append(const char* fmt, ...)
+void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
- appendv(fmt, args);
+ appendfv(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
-// ImGuiSimpleColumns
+// ImGuiSimpleColumns (internal use only)
//-----------------------------------------------------------------------------
-ImGuiSimpleColumns::ImGuiSimpleColumns()
+ImGuiMenuColumns::ImGuiMenuColumns()
{
Count = 0;
Spacing = Width = NextWidth = 0.0f;
@@ -1640,7 +1711,7 @@ ImGuiSimpleColumns::ImGuiSimpleColumns()
memset(NextWidths, 0, sizeof(NextWidths));
}
-void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
+void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
{
IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
Count = count;
@@ -1657,7 +1728,7 @@ void ImGuiSimpleColumns::Update(int count, float spacing, bool clear)
}
}
-float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
+float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
{
NextWidth = 0.0f;
NextWidths[0] = ImMax(NextWidths[0], w0);
@@ -1668,7 +1739,7 @@ float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using
return ImMax(Width, NextWidth);
}
-float ImGuiSimpleColumns::CalcExtraSpace(float avail_w)
+float ImGuiMenuColumns::CalcExtraSpace(float avail_w)
{
return ImMax(0.0f, avail_w - Width);
}
@@ -1685,8 +1756,8 @@ static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage.
window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
- if (window->DC.ColumnsCount > 1)
- window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
+ if (window->DC.ColumnsSet)
+ window->DC.ColumnsSet->CellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
@@ -1760,48 +1831,51 @@ bool ImGuiListClipper::Step()
// ImGuiWindow
//-----------------------------------------------------------------------------
-ImGuiWindow::ImGuiWindow(const char* name)
+ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
{
Name = ImStrdup(name);
ID = ImHash(name, 0);
IDStack.push_back(ID);
- MoveId = GetID("#MOVE");
-
Flags = 0;
- IndexWithinParent = 0;
PosFloat = Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
+ WindowRounding = 0.0f;
+ WindowBorderSize = 0.0f;
+ MoveId = GetID("#MOVE");
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarX = ScrollbarY = false;
ScrollbarSizes = ImVec2(0.0f, 0.0f);
- BorderSize = 0.0f;
Active = WasActive = false;
- Accessed = false;
+ WriteAccessed = false;
Collapsed = false;
SkipItems = false;
+ Appearing = false;
+ CloseButton = false;
+ BeginOrderWithinParent = -1;
+ BeginOrderWithinContext = -1;
BeginCount = 0;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitOnlyGrows = false;
- AutoPosLastDirection = -1;
+ AutoFitChildAxises = 0x00;
+ AutoPosLastDirection = ImGuiDir_None;
HiddenFrames = 0;
- SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing;
- SetWindowPosCenterWanted = false;
+ SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
+ SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
LastFrameActive = -1;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
- DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList));
- IM_PLACEMENT_NEW(DrawList) ImDrawList();
+ DrawList = IM_NEW(ImDrawList)(&context->DrawListSharedData);
DrawList->_OwnerName = Name;
+ ParentWindow = NULL;
RootWindow = NULL;
RootNonPopupWindow = NULL;
- ParentWindow = NULL;
FocusIdxAllCounter = FocusIdxTabCounter = -1;
FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
@@ -1810,11 +1884,10 @@ ImGuiWindow::ImGuiWindow(const char* name)
ImGuiWindow::~ImGuiWindow()
{
- DrawList->~ImDrawList();
- ImGui::MemFree(DrawList);
- DrawList = NULL;
- ImGui::MemFree(Name);
- Name = NULL;
+ IM_DELETE(DrawList);
+ IM_DELETE(Name);
+ for (int i = 0; i != ColumnsStorage.Size; i++)
+ ColumnsStorage[i].~ImGuiColumnsSet();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
@@ -1839,6 +1912,16 @@ ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
}
+// This is only used in rare/specific situations to manufacture an ID out of nowhere.
+ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
+{
+ ImGuiID seed = IDStack.back();
+ const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
+ ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed);
+ ImGui::KeepAliveID(id);
+ return id;
+}
+
//-----------------------------------------------------------------------------
// Internal API exposed in imgui_internal.h
//-----------------------------------------------------------------------------
@@ -1848,24 +1931,18 @@ static void SetCurrentWindow(ImGuiWindow* window)
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
- g.FontSize = window->CalcFontSize();
-}
-
-ImGuiWindow* ImGui::GetParentWindow()
-{
- ImGuiContext& g = *GImGui;
- IM_ASSERT(g.CurrentWindowStack.Size >= 2);
- return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2];
+ g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
+ g.ActiveIdIsJustActivated = (g.ActiveId != id);
+ if (g.ActiveIdIsJustActivated)
+ g.ActiveIdTimer = 0.0f;
g.ActiveId = id;
g.ActiveIdAllowOverlap = false;
- g.ActiveIdIsJustActivated = true;
- if (id)
- g.ActiveIdIsAlive = true;
+ g.ActiveIdIsAlive |= (id != 0);
g.ActiveIdWindow = window;
}
@@ -1879,6 +1956,13 @@ void ImGui::SetHoveredID(ImGuiID id)
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
+ g.HoveredIdTimer = (id != 0 && g.HoveredIdPreviousFrame == id) ? (g.HoveredIdTimer + g.IO.DeltaTime) : 0.0f;
+}
+
+ImGuiID ImGui::GetHoveredID()
+{
+ ImGuiContext& g = *GImGui;
+ return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
@@ -1888,27 +1972,51 @@ void ImGui::KeepAliveID(ImGuiID id)
g.ActiveIdIsAlive = true;
}
+static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
+{
+ // An active popup disable hovering on other windows (apart from its own children)
+ // FIXME-OPT: This could be cached/stored within the window.
+ ImGuiContext& g = *GImGui;
+ if (g.NavWindow)
+ if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
+ if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
+ {
+ // For the purpose of those flags we differentiate "standard popup" from "modal popup"
+ // NB: The order of those two tests is important because Modal windows are also Popups.
+ if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
+ return false;
+ if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
+ return false;
+ }
+
+ return true;
+}
+
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// Always align ourselves on pixel boundaries
- ImGuiContext& g = *GImGui;
const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
+ //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y));
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
- window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
-
- //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug
+ window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
+ //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineHeight = line_height;
window->DC.PrevLineTextBaseOffset = text_base_offset;
window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
+
+ // Horizontal layout mode
+ if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
+ SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
@@ -1919,74 +2027,110 @@ void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
-bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id)
+bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id)
{
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.LastItemId = id ? *id : 0;
- window->DC.LastItemRect = bb;
- window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false;
- if (IsClippedEx(bb, id, false))
- return false;
-
- // This is a sensible default, but widgets are free to override it after calling ItemAdd()
ImGuiContext& g = *GImGui;
- if (IsMouseHoveringRect(bb.Min, bb.Max))
- {
- // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background)
- // So that clicking on items with no active id such as Text() still returns true with IsItemHovered()
- window->DC.LastItemHoveredRect = true;
- if (g.HoveredRootWindow == window->RootWindow)
- if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId))
- if (IsWindowContentHoverable(window))
- window->DC.LastItemHoveredAndUsable = true;
- }
+ ImGuiWindow* window = g.CurrentWindow;
+ const bool is_clipped = IsClippedEx(bb, id, false);
+ window->DC.LastItemId = id;
+ window->DC.LastItemRect = bb;
+ window->DC.LastItemRectHoveredRect = false;
+ if (is_clipped)
+ return false;
+ //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
+ // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
+ window->DC.LastItemRectHoveredRect = IsMouseHoveringRect(bb.Min, bb.Max);
return true;
}
-bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged)
+// This is roughly matching the behavior of internal-facing ItemHoverable()
+// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
+// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
+bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
+ // Test for bounding box overlap, as updated as ItemAdd()
+ if (!window->DC.LastItemRectHoveredRect)
+ return false;
+ IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
+
+ // Test if we are hovering the right window (our window could be behind another window)
+ // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
+ // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
+ //if (g.HoveredWindow != window)
+ // return false;
+ if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
+ return false;
+
+ // Test if another item is active (e.g. being dragged)
+ if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
+ if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
+ return false;
+
+ // Test if interactions on this window are blocked by an active popup or modal
+ if (!IsWindowContentHoverable(window, flags))
+ return false;
+
+ // Test if the item is disabled
+ if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
+ return false;
+
+ // Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case.
+ if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
+ return false;
+ return true;
+}
+
+// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
+bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
+ return false;
+
+ ImGuiWindow* window = g.CurrentWindow;
+ if (g.HoveredWindow != window)
+ return false;
+ if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
+ return false;
+ if (!IsMouseHoveringRect(bb.Min, bb.Max))
+ return false;
+ if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_Default))
+ return false;
+ if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
+ return false;
+
+ SetHoveredID(id);
+ return true;
+}
+
+bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
- if (!id || *id != GImGui->ActiveId)
+ if (id == 0 || id != g.ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
-// NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic.
-bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs)
-{
- ImGuiContext& g = *GImGui;
- if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap)
- {
- ImGuiWindow* window = GetCurrentWindowRead();
- if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow))
- if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max))
- if (IsWindowContentHoverable(g.HoveredRootWindow))
- return true;
- }
- return false;
-}
-
-bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop)
+bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
{
ImGuiContext& g = *GImGui;
- const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus;
+ const bool allow_keyboard_focus = (window->DC.ItemFlags & (ImGuiItemFlags_AllowKeyboardFocus | ImGuiItemFlags_Disabled)) == ImGuiItemFlags_AllowKeyboardFocus;
window->FocusIdxAllCounter++;
if (allow_keyboard_focus)
window->FocusIdxTabCounter++;
- // Process keyboard input at this point: TAB, Shift-TAB switch focus
- // We can always TAB out of a widget that doesn't allow tabbing in.
- if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab))
- {
- // Modulo on index will be applied at the end of frame once we've got the total counter of items.
- window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1);
- }
+ // Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
+ // Note that we can always TAB out of a widget that doesn't allow tabbing in.
+ if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
+ window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
return true;
@@ -2109,7 +2253,7 @@ ImGuiStyle& ImGui::GetStyle()
// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
- return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL;
+ return GImGui->DrawData.Valid ? &GImGui->DrawData : NULL;
}
float ImGui::GetTime()
@@ -2122,50 +2266,92 @@ int ImGui::GetFrameCount()
return GImGui->FrameCount;
}
+ImDrawList* ImGui::GetOverlayDrawList()
+{
+ return &GImGui->OverlayDrawList;
+}
+
+ImDrawListSharedData* ImGui::GetDrawListSharedData()
+{
+ return &GImGui->DrawListSharedData;
+}
+
void ImGui::NewFrame()
{
ImGuiContext& g = *GImGui;
// Check user data
- IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues)
- IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f);
- IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
- IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
- IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting
+ // (We pass an error message in the assert expression as a trick to get it visible to programmers who are not using a debugger, as most assert handlers display their argument)
+ IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
+ IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
+ IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
+ IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
+ IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
+ IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)");
+ IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
+ for (int n = 0; n < ImGuiKey_COUNT; n++)
+ IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
+ // Initialize on first frame
if (!g.Initialized)
- {
- // Initialize on first frame
- g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer));
- IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer();
-
- IM_ASSERT(g.Settings.empty());
- LoadIniSettingsFromDisk(g.IO.IniFilename);
- g.Initialized = true;
- }
-
- SetCurrentFont(GetDefaultFont());
- IM_ASSERT(g.Font->IsLoaded());
+ Initialize();
g.Time += g.IO.DeltaTime;
g.FrameCount += 1;
- g.Tooltip[0] = '\0';
+ g.TooltipOverrideCount = 0;
+ g.WindowsActiveCount = 0;
+
+ SetCurrentFont(GetDefaultFont());
+ IM_ASSERT(g.Font->IsLoaded());
+ g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
+ g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
+
g.OverlayDrawList.Clear();
g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
g.OverlayDrawList.PushClipRectFullScreen();
+ g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
// Mark rendering data as invalid to prevent user who may have a handle on it to use it
- g.RenderDrawData.Valid = false;
- g.RenderDrawData.CmdLists = NULL;
- g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0;
+ g.DrawData.Clear();
- // Update inputs state
- if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0)
- g.IO.MousePos = ImVec2(-9999.0f, -9999.0f);
- if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta
- g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
- else
+ // Clear reference to active widget if the widget isn't alive anymore
+ if (!g.HoveredIdPreviousFrame)
+ g.HoveredIdTimer = 0.0f;
+ g.HoveredIdPreviousFrame = g.HoveredId;
+ g.HoveredId = 0;
+ g.HoveredIdAllowOverlap = false;
+ if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
+ ClearActiveID();
+ if (g.ActiveId)
+ g.ActiveIdTimer += g.IO.DeltaTime;
+ g.ActiveIdPreviousFrame = g.ActiveId;
+ g.ActiveIdIsAlive = false;
+ g.ActiveIdIsJustActivated = false;
+ if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
+ g.ScalarAsInputTextId = 0;
+
+ // Elapse drag & drop payload
+ if (g.DragDropActive && g.DragDropPayload.DataFrameCount + 1 < g.FrameCount)
+ {
+ ClearDragDrop();
+ g.DragDropPayloadBufHeap.clear();
+ memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
+ }
+ g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
+ g.DragDropAcceptIdCurr = 0;
+ g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
+
+ // Update keyboard input state
+ memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
+ for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
+ g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
+
+ // Update mouse input state
+ // If mouse just appeared or disappeared (usually denoted by -FLT_MAX component, but in reality we test for -256000.0f) we cancel out movement in MouseDelta
+ if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
+ else
+ g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
@@ -2187,16 +2373,17 @@ void ImGui::NewFrame()
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
+ g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
- g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]));
+ ImVec2 mouse_delta = g.IO.MousePos - g.IO.MouseClickedPos[i];
+ g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, mouse_delta.x < 0.0f ? -mouse_delta.x : mouse_delta.x);
+ g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, mouse_delta.y < 0.0f ? -mouse_delta.y : mouse_delta.y);
+ g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(mouse_delta));
}
}
- memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
- for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
- g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
@@ -2204,43 +2391,39 @@ void ImGui::NewFrame()
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
- // Clear reference to active widget if the widget isn't alive anymore
- g.HoveredIdPreviousFrame = g.HoveredId;
- g.HoveredId = 0;
- g.HoveredIdAllowOverlap = false;
- if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
- ClearActiveID();
- g.ActiveIdPreviousFrame = g.ActiveId;
- g.ActiveIdIsAlive = false;
- g.ActiveIdIsJustActivated = false;
-
- // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows.
- if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId)
+ // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering).
+ if (g.MovingWindow && g.MovingWindow->MoveId == g.ActiveId)
{
- KeepAliveID(g.MovedWindowMoveId);
- IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow);
- IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId);
+ KeepAliveID(g.ActiveId);
+ IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
if (g.IO.MouseDown[0])
{
- if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove))
+ // MovingWindow = window we clicked on, could be a child window. We track it to preserve Focus and so that ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
+ ImGuiWindow* actually_moving_window = g.MovingWindow->RootWindow;
+ ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
+ if (actually_moving_window->PosFloat.x != pos.x || actually_moving_window->PosFloat.y != pos.y)
{
- g.MovedWindow->PosFloat += g.IO.MouseDelta;
- if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings) && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f))
- MarkIniSettingsDirty();
+ MarkIniSettingsDirty(actually_moving_window);
+ actually_moving_window->PosFloat = pos;
}
- FocusWindow(g.MovedWindow);
+ FocusWindow(g.MovingWindow);
}
else
{
ClearActiveID();
- g.MovedWindow = NULL;
- g.MovedWindowMoveId = 0;
+ g.MovingWindow = NULL;
}
}
else
{
- g.MovedWindow = NULL;
- g.MovedWindowMoveId = 0;
+ // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
+ if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
+ {
+ KeepAliveID(g.ActiveId);
+ if (!g.IO.MouseDown[0])
+ ClearActiveID();
+ }
+ g.MovingWindow = NULL;
}
// Delay saving settings so we don't spam disk too much
@@ -2251,20 +2434,18 @@ void ImGui::NewFrame()
SaveIniSettingsToDisk(g.IO.IniFilename);
}
- // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow
- g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false);
- if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow))
- g.HoveredRootWindow = g.HoveredWindow->RootWindow;
- else
- g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true);
+ // Find the window we are hovering
+ // - 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.
+ // - 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.
+ g.HoveredWindow = (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs)) ? g.MovingWindow : FindHoveredWindow(g.IO.MousePos);
+ g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
- if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow())
+ ImGuiWindow* modal_window = GetFrontMostModalRootWindow();
+ if (modal_window != NULL)
{
g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
- ImGuiWindow* window = g.HoveredRootWindow;
- while (window && window != modal_window)
- window = window->ParentWindow;
- if (!window)
+ if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
}
else
@@ -2272,7 +2453,7 @@ void ImGui::NewFrame()
g.ModalWindowDarkeningRatio = 0.0f;
}
- // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application.
+ // Update the WantCaptureMouse/WantCAptureKeyboard flags, so user can capture/discard the inputs away from the rest of their application.
// When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
@@ -2282,35 +2463,46 @@ void ImGui::NewFrame()
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
- if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i])
+ if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
- if (g.CaptureMouseNextFrame != -1)
- g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0);
+ 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.ActiveId != 0) || (!g.OpenPopupStack.empty());
- g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0);
- g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId);
+ g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
+ if (g.WantCaptureKeyboardNextFrame != -1)
+ g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
+ else
+ g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
+ g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : 0;
g.MouseCursor = ImGuiMouseCursor_Arrow;
- g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1;
+ g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
- if (!mouse_avail_to_imgui)
+ // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
+ bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
+ if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = NULL;
- // Scale & Scrolling
- if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed)
+ // Mouse wheel scrolling, scale
+ if (g.HoveredWindow && !g.HoveredWindow->Collapsed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f))
{
+ // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
ImGuiWindow* window = g.HoveredWindow;
- if (g.IO.KeyCtrl)
+ ImGuiWindow* scroll_window = window;
+ while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs) && scroll_window->ParentWindow)
+ scroll_window = scroll_window->ParentWindow;
+ const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs);
+
+ if (g.IO.MouseWheel != 0.0f)
{
- if (g.IO.FontAllowUserScaling)
+ if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
// Zoom / Scale window
- float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
- float scale = new_font_scale / window->FontWindowScale;
+ const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
+ const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
@@ -2319,19 +2511,26 @@ void ImGui::NewFrame()
window->Size *= scale;
window->SizeFull *= scale;
}
+ else if (!g.IO.KeyCtrl && scroll_allowed)
+ {
+ // Mouse wheel vertical scrolling
+ float scroll_amount = 5 * scroll_window->CalcFontSize();
+ scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
+ SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
+ }
}
- else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
+ if (g.IO.MouseWheelH != 0.0f && scroll_allowed)
{
- // Scroll
- const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5;
- SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines);
+ // Mouse wheel horizontal scrolling (for hardware that supports it)
+ float scroll_amount = scroll_window->CalcFontSize();
+ if (!g.IO.KeyCtrl && !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
+ SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
}
}
// Pressing TAB activate widget focus
- // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus.
- if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
- g.FocusedWindow->FocusIdxTabRequestNext = 0;
+ if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false))
+ g.NavWindow->FocusIdxTabRequestNext = 0;
// Mark all windows as not visible
for (int i = 0; i != g.Windows.Size; i++)
@@ -2339,30 +2538,100 @@ void ImGui::NewFrame()
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->Active = false;
- window->Accessed = false;
+ window->WriteAccessed = false;
}
// Closing the focused window restore focus to the first active root window in descending z-order
- if (g.FocusedWindow && !g.FocusedWindow->WasActive)
- for (int i = g.Windows.Size-1; i >= 0; i--)
- if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
- {
- FocusWindow(g.Windows[i]);
- break;
- }
+ if (g.NavWindow && !g.NavWindow->WasActive)
+ FocusFrontMostActiveWindow(NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.CurrentPopupStack.resize(0);
- CloseInactivePopups();
+ CloseInactivePopups(g.NavWindow);
// Create implicit window - we will only render it if the user has added something to it.
- ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver);
- ImGui::Begin("Debug");
+ // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
+ SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
+ Begin("Debug##Default");
}
-// NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations.
+static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
+{
+ ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
+ if (!settings)
+ settings = AddWindowSettings(name);
+ return (void*)settings;
+}
+
+static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
+{
+ ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
+ float x, y;
+ int i;
+ if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y);
+ else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize);
+ else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
+}
+
+static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
+{
+ // Gather data from windows that were active during this session
+ ImGuiContext& g = *imgui_ctx;
+ for (int i = 0; i != g.Windows.Size; i++)
+ {
+ ImGuiWindow* window = g.Windows[i];
+ if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
+ continue;
+ ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID);
+ if (!settings)
+ settings = AddWindowSettings(window->Name);
+ settings->Pos = window->Pos;
+ settings->Size = window->SizeFull;
+ settings->Collapsed = window->Collapsed;
+ }
+
+ // Write a buffer
+ // If a window wasn't opened in this session we preserve its settings
+ buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
+ for (int i = 0; i != g.SettingsWindows.Size; i++)
+ {
+ const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
+ if (settings->Pos.x == FLT_MAX)
+ continue;
+ const char* name = settings->Name;
+ if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
+ name = p;
+ buf->appendf("[%s][%s]\n", handler->TypeName, name);
+ buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
+ buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
+ buf->appendf("Collapsed=%d\n", settings->Collapsed);
+ buf->appendf("\n");
+ }
+}
+
+void ImGui::Initialize()
+{
+ ImGuiContext& g = *GImGui;
+ g.LogClipboard = IM_NEW(ImGuiTextBuffer)();
+
+ // Add .ini handle for ImGuiWindow type
+ ImGuiSettingsHandler ini_handler;
+ ini_handler.TypeName = "Window";
+ ini_handler.TypeHash = ImHash("Window", 0, 0);
+ ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
+ ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
+ ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
+ g.SettingsHandlers.push_front(ini_handler);
+
+ // Load .ini file
+ IM_ASSERT(g.SettingsWindows.empty());
+ LoadIniSettingsFromDisk(g.IO.IniFilename);
+ g.Initialized = true;
+}
+
+// This function is merely here to free heap allocations.
void ImGui::Shutdown()
{
ImGuiContext& g = *GImGui;
@@ -2371,133 +2640,142 @@ void ImGui::Shutdown()
if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky.
g.IO.Fonts->Clear();
- // Cleanup of other data are conditional on actually having used ImGui.
+ // Cleanup of other data are conditional on actually having initialize ImGui.
if (!g.Initialized)
return;
SaveIniSettingsToDisk(g.IO.IniFilename);
for (int i = 0; i < g.Windows.Size; i++)
- {
- g.Windows[i]->~ImGuiWindow();
- ImGui::MemFree(g.Windows[i]);
- }
+ IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
- g.FocusedWindow = NULL;
+ g.WindowsById.Clear();
+ g.NavWindow = NULL;
g.HoveredWindow = NULL;
g.HoveredRootWindow = NULL;
g.ActiveIdWindow = NULL;
- g.MovedWindow = NULL;
- for (int i = 0; i < g.Settings.Size; i++)
- ImGui::MemFree(g.Settings[i].Name);
- g.Settings.clear();
+ g.MovingWindow = NULL;
+ for (int i = 0; i < g.SettingsWindows.Size; i++)
+ IM_DELETE(g.SettingsWindows[i].Name);
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.CurrentPopupStack.clear();
- g.SetNextWindowSizeConstraintCallback = NULL;
- g.SetNextWindowSizeConstraintCallbackUserData = NULL;
- for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- g.RenderDrawLists[i].clear();
+ g.DrawDataBuilder.ClearFreeMemory();
g.OverlayDrawList.ClearFreeMemory();
- g.ColorEditModeStorage.Clear();
- if (g.PrivateClipboard)
- {
- ImGui::MemFree(g.PrivateClipboard);
- g.PrivateClipboard = NULL;
- }
+ g.PrivateClipboard.clear();
g.InputTextState.Text.clear();
g.InputTextState.InitialText.clear();
g.InputTextState.TempTextBuffer.clear();
+ g.SettingsWindows.clear();
+ g.SettingsHandlers.clear();
+
if (g.LogFile && g.LogFile != stdout)
{
fclose(g.LogFile);
g.LogFile = NULL;
}
if (g.LogClipboard)
- {
- g.LogClipboard->~ImGuiTextBuffer();
- ImGui::MemFree(g.LogClipboard);
- }
+ IM_DELETE(g.LogClipboard);
g.Initialized = false;
}
-static ImGuiIniData* FindWindowSettings(const char* name)
+ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
- ImGuiID id = ImHash(name, 0);
- for (int i = 0; i != g.Settings.Size; i++)
- {
- ImGuiIniData* ini = &g.Settings[i];
- if (ini->Id == id)
- return ini;
- }
+ for (int i = 0; i != g.SettingsWindows.Size; i++)
+ if (g.SettingsWindows[i].Id == id)
+ return &g.SettingsWindows[i];
return NULL;
}
-static ImGuiIniData* AddWindowSettings(const char* name)
-{
- GImGui->Settings.resize(GImGui->Settings.Size + 1);
- ImGuiIniData* ini = &GImGui->Settings.back();
- ini->Name = ImStrdup(name);
- ini->Id = ImHash(name, 0);
- ini->Collapsed = false;
- ini->Pos = ImVec2(FLT_MAX,FLT_MAX);
- ini->Size = ImVec2(0,0);
- return ini;
-}
-
-// Zero-tolerance, poor-man .ini parsing
-// FIXME: Write something less rubbish
-static void LoadIniSettingsFromDisk(const char* ini_filename)
+static ImGuiWindowSettings* AddWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
+ g.SettingsWindows.push_back(ImGuiWindowSettings());
+ ImGuiWindowSettings* settings = &g.SettingsWindows.back();
+ settings->Name = ImStrdup(name);
+ settings->Id = ImHash(name, 0);
+ return settings;
+}
+
+static void LoadIniSettingsFromDisk(const char* ini_filename)
+{
if (!ini_filename)
return;
-
- int file_size;
- char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_size, 1);
+ char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", NULL, +1);
if (!file_data)
return;
+ LoadIniSettingsFromMemory(file_data);
+ ImGui::MemFree(file_data);
+}
- ImGuiIniData* settings = NULL;
- const char* buf_end = file_data + file_size;
- for (const char* line_start = file_data; line_start < buf_end; )
+ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
+{
+ ImGuiContext& g = *GImGui;
+ const ImGuiID type_hash = ImHash(type_name, 0, 0);
+ for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
+ if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
+ return &g.SettingsHandlers[handler_n];
+ return NULL;
+}
+
+// Zero-tolerance, no error reporting, cheap .ini parsing
+static void LoadIniSettingsFromMemory(const char* buf_readonly)
+{
+ // For convenience and to make the code simpler, we'll write zero terminators inside the buffer. So let's create a writable copy.
+ char* buf = ImStrdup(buf_readonly);
+ char* buf_end = buf + strlen(buf);
+
+ ImGuiContext& g = *GImGui;
+ void* entry_data = NULL;
+ ImGuiSettingsHandler* entry_handler = NULL;
+
+ char* line_end = NULL;
+ for (char* line = buf; line < buf_end; line = line_end + 1)
{
- const char* line_end = line_start;
+ // Skip new lines markers, then find end of the line
+ while (*line == '\n' || *line == '\r')
+ line++;
+ line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
+ line_end[0] = 0;
- if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']')
+ if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
- char name[64];
- ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1);
- settings = FindWindowSettings(name);
- if (!settings)
- settings = AddWindowSettings(name);
+ // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
+ line_end[-1] = 0;
+ const char* name_end = line_end - 1;
+ const char* type_start = line + 1;
+ char* type_end = ImStrchrRange(type_start, name_end, ']');
+ const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
+ if (!type_end || !name_start)
+ {
+ name_start = type_start; // Import legacy entries that have no type
+ type_start = "Window";
+ }
+ else
+ {
+ *type_end = 0; // Overwrite first ']'
+ name_start++; // Skip second '['
+ }
+ entry_handler = ImGui::FindSettingsHandler(type_start);
+ entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
- else if (settings)
+ else if (entry_handler != NULL && entry_data != NULL)
{
- float x, y;
- int i;
- if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2)
- settings->Pos = ImVec2(x, y);
- else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2)
- settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
- else if (sscanf(line_start, "Collapsed=%d", &i) == 1)
- settings->Collapsed = (i != 0);
+ // Let type handler parse the line
+ entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
-
- line_start = line_end+1;
}
-
- ImGui::MemFree(file_data);
+ ImGui::MemFree(buf);
}
static void SaveIniSettingsToDisk(const char* ini_filename)
@@ -2507,48 +2785,47 @@ static void SaveIniSettingsToDisk(const char* ini_filename)
if (!ini_filename)
return;
- // Gather data from windows that were active during this session
- for (int i = 0; i != g.Windows.Size; i++)
- {
- ImGuiWindow* window = g.Windows[i];
- if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
- continue;
- ImGuiIniData* settings = FindWindowSettings(window->Name);
- settings->Pos = window->Pos;
- settings->Size = window->SizeFull;
- settings->Collapsed = window->Collapsed;
- }
+ ImVector buf;
+ SaveIniSettingsToMemory(buf);
- // Write .ini file
- // If a window wasn't opened in this session we preserve its settings
FILE* f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
- for (int i = 0; i != g.Settings.Size; i++)
- {
- const ImGuiIniData* settings = &g.Settings[i];
- if (settings->Pos.x == FLT_MAX)
- continue;
- const char* name = settings->Name;
- if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
- name = p;
- fprintf(f, "[%s]\n", name);
- fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
- fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
- fprintf(f, "Collapsed=%d\n", settings->Collapsed);
- fprintf(f, "\n");
- }
-
+ fwrite(buf.Data, sizeof(char), (size_t)buf.Size, f);
fclose(f);
}
-static void MarkIniSettingsDirty()
+static void SaveIniSettingsToMemory(ImVector& out_buf)
+{
+ ImGuiContext& g = *GImGui;
+ g.SettingsDirtyTimer = 0.0f;
+
+ ImGuiTextBuffer buf;
+ for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
+ {
+ ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
+ handler->WriteAllFn(&g, handler, &buf);
+ }
+
+ buf.Buf.pop_back(); // Remove extra zero-terminator used by ImGuiTextBuffer
+ out_buf.swap(buf.Buf);
+}
+
+void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
+static void MarkIniSettingsDirty(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
+ if (g.SettingsDirtyTimer <= 0.0f)
+ g.SettingsDirtyTimer = g.IO.IniSavingRate;
+}
+
// FIXME: Add a more explicit sort order in the window structure.
static int ChildWindowComparer(const void* lhs, const void* rhs)
{
@@ -2558,9 +2835,7 @@ static int ChildWindowComparer(const void* lhs, const void* rhs)
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
- if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox))
- return d;
- return (a->IndexWithinParent - b->IndexWithinParent);
+ return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window)
@@ -2580,7 +2855,7 @@ static void AddWindowToSortedBuffer(ImVector& out_sorted_windows,
}
}
-static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list)
+static void AddDrawListToDrawData(ImVector* out_render_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
@@ -2594,31 +2869,74 @@ static void AddDrawListToRenderList(ImVector& out_render_list, ImDr
return;
}
- // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
+ // 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);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
- // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices)
- // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly.
- IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above.
-
- out_render_list.push_back(draw_list);
- GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size;
- GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size;
+ // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
+ // If this assert triggers because you are drawing lots of stuff manually:
+ // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
+ // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
+ // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
+ // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
+ // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
+ // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
+ if (sizeof(ImDrawIdx) == 2)
+ IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
+
+ out_render_list->push_back(draw_list);
}
-static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window)
+static void AddWindowToDrawData(ImVector* out_render_list, ImGuiWindow* window)
{
- AddDrawListToRenderList(out_render_list, window->DrawList);
+ AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
- if (!child->Active) // clipped children may have been marked not active
+ if (child->Active && child->HiddenFrames <= 0) // clipped children may have been marked not active
+ AddWindowToDrawData(out_render_list, child);
+ }
+}
+
+static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ g.IO.MetricsActiveWindows++;
+ if (window->Flags & ImGuiWindowFlags_Tooltip)
+ AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
+ else
+ AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
+}
+
+void ImDrawDataBuilder::FlattenIntoSingleLayer()
+{
+ int n = Layers[0].Size;
+ int size = n;
+ for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
+ size += Layers[i].Size;
+ Layers[0].resize(size);
+ for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
+ {
+ ImVector& layer = Layers[layer_n];
+ if (layer.empty())
continue;
- if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0)
- continue;
- AddWindowToRenderList(out_render_list, child);
+ memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
+ n += layer.Size;
+ layer.resize(0);
+ }
+}
+
+static void SetupDrawData(ImVector* draw_lists, ImDrawData* out_draw_data)
+{
+ out_draw_data->Valid = true;
+ out_draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
+ out_draw_data->CmdListsCount = draw_lists->Size;
+ out_draw_data->TotalVtxCount = out_draw_data->TotalIdxCount = 0;
+ for (int n = 0; n < draw_lists->Size; n++)
+ {
+ out_draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
+ out_draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
@@ -2642,15 +2960,8 @@ void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
- IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again
-
- // Render tooltip
- if (g.Tooltip[0])
- {
- ImGui::BeginTooltip();
- ImGui::TextUnformatted(g.Tooltip);
- ImGui::EndTooltip();
- }
+ if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
+ return;
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
@@ -2661,29 +2972,52 @@ void ImGui::EndFrame()
// Hide implicit "Debug" window if it hasn't been used
IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
- if (g.CurrentWindow && !g.CurrentWindow->Accessed)
+ if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
- ImGui::End();
+ End();
- // Click to focus window and start moving (after we're done with all our widgets)
- if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0])
+ if (g.ActiveId == 0 && g.HoveredId == 0)
{
- if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear
+ if (!g.NavWindow || !g.NavWindow->Appearing) // Unless we just made a window/popup appear
{
- if (g.HoveredRootWindow != NULL)
+ // Click to focus window and start moving (after we're done with all our widgets)
+ if (g.IO.MouseClicked[0])
{
- FocusWindow(g.HoveredWindow);
- if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove))
+ if (g.HoveredRootWindow != NULL)
{
- g.MovedWindow = g.HoveredWindow;
- g.MovedWindowMoveId = g.HoveredRootWindow->MoveId;
- SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow);
+ // Set ActiveId even if the _NoMove flag is set, without it dragging away from a window with _NoMove would activate hover on other windows.
+ FocusWindow(g.HoveredWindow);
+ SetActiveID(g.HoveredWindow->MoveId, g.HoveredWindow);
+ g.ActiveIdClickOffset = g.IO.MousePos - g.HoveredRootWindow->Pos;
+ if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove) && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoMove))
+ g.MovingWindow = g.HoveredWindow;
+ }
+ else if (g.NavWindow != NULL && GetFrontMostModalRootWindow() == NULL)
+ {
+ // Clicking on void disable focus
+ FocusWindow(NULL);
}
}
- else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL)
+
+ // With right mouse button we close popups without changing focus
+ // (The left mouse button path calls FocusWindow which will lead NewFrame->CloseInactivePopups to trigger)
+ if (g.IO.MouseClicked[1])
{
- // Clicking on void disable focus
- FocusWindow(NULL);
+ // Find the top-most window between HoveredWindow and the front most Modal Window.
+ // This is where we can trim the popup stack.
+ ImGuiWindow* modal = GetFrontMostModalRootWindow();
+ bool hovered_window_above_modal = false;
+ if (modal == NULL)
+ hovered_window_above_modal = true;
+ for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
+ {
+ ImGuiWindow* window = g.Windows[i];
+ if (window == modal)
+ break;
+ if (window == g.HoveredWindow)
+ hovered_window_above_modal = true;
+ }
+ CloseInactivePopups(hovered_window_above_modal ? g.HoveredWindow : modal);
}
}
}
@@ -2699,11 +3033,12 @@ void ImGui::EndFrame()
continue;
AddWindowToSortedBuffer(g.WindowsSortBuffer, window);
}
+
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
g.Windows.swap(g.WindowsSortBuffer);
// Clear Input data for next frame
- g.IO.MouseWheel = 0.0f;
+ g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
g.FrameCountEnded = g.FrameCount;
@@ -2724,66 +3059,39 @@ void ImGui::Render()
{
// Gather windows to render
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
- for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- g.RenderDrawLists[i].resize(0);
- for (int i = 0; i != g.Windows.Size; i++)
+ g.DrawDataBuilder.Clear();
+ for (int n = 0; n != g.Windows.Size; n++)
{
- ImGuiWindow* window = g.Windows[i];
+ ImGuiWindow* window = g.Windows[n];
if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0)
- {
- // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, ..
- g.IO.MetricsActiveWindows++;
- if (window->Flags & ImGuiWindowFlags_Popup)
- AddWindowToRenderList(g.RenderDrawLists[1], window);
- else if (window->Flags & ImGuiWindowFlags_Tooltip)
- AddWindowToRenderList(g.RenderDrawLists[2], window);
- else
- AddWindowToRenderList(g.RenderDrawLists[0], window);
- }
- }
-
- // Flatten layers
- int n = g.RenderDrawLists[0].Size;
- int flattened_size = n;
- for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- flattened_size += g.RenderDrawLists[i].Size;
- g.RenderDrawLists[0].resize(flattened_size);
- for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++)
- {
- ImVector& layer = g.RenderDrawLists[i];
- if (layer.empty())
- continue;
- memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
- n += layer.Size;
+ AddWindowToDrawDataSelectLayer(window);
}
+ g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
- if (g.IO.MouseDrawCursor)
+ ImVec2 offset, size, uv[4];
+ if (g.IO.MouseDrawCursor && g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &offset, &size, &uv[0], &uv[2]))
{
- const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor];
- const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset;
- const ImVec2 size = cursor_data.Size;
+ const ImVec2 pos = g.IO.MousePos - offset;
const ImTextureID tex_id = g.IO.Fonts->TexID;
g.OverlayDrawList.PushTextureID(tex_id);
- g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow
- g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow
- g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border
- g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill
+ g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
+ g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
+ g.OverlayDrawList.AddImage(tex_id, pos, pos + size, uv[2], uv[3], IM_COL32(0,0,0,255)); // Black border
+ g.OverlayDrawList.AddImage(tex_id, pos, pos + size, uv[0], uv[1], IM_COL32(255,255,255,255)); // White fill
g.OverlayDrawList.PopTextureID();
}
if (!g.OverlayDrawList.VtxBuffer.empty())
- AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList);
+ AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList);
- // Setup draw data
- g.RenderDrawData.Valid = true;
- g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL;
- g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size;
- g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices;
- g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices;
+ // Setup ImDrawData structure for end-user
+ SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
+ g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
+ g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
// Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
- if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
- g.IO.RenderDrawListsFn(&g.RenderDrawData);
+ if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
+ g.IO.RenderDrawListsFn(&g.DrawData);
}
}
@@ -2813,23 +3121,24 @@ void ImGui::LogText(const char* fmt, ...)
}
else
{
- g.LogClipboard->appendv(fmt, args);
+ g.LogClipboard->appendfv(fmt, args);
}
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
-static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end)
+static void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = ImGui::GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = ImGui::FindRenderedTextEnd(text, text_end);
- const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1;
- window->DC.LogLinePosY = ref_pos.y;
+ const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1);
+ if (ref_pos)
+ window->DC.LogLinePosY = ref_pos->y;
const char* text_remaining = text;
if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
@@ -2874,7 +3183,7 @@ static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char*
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
@@ -2894,14 +3203,14 @@ void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
if (g.LogEnabled)
- LogRenderedText(pos, text, text_display_end);
+ LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
@@ -2911,7 +3220,7 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
- LogRenderedText(pos, text, text_end);
+ LogRenderedText(&pos, text, text_end);
}
}
@@ -2926,7 +3235,7 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons
return;
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = g.CurrentWindow;
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
@@ -2953,75 +3262,96 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
if (g.LogEnabled)
- LogRenderedText(pos, text, text_display_end);
+ LogRenderedText(&pos, text, text_display_end);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
- ImGuiWindow* window = GetCurrentWindow();
-
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
- if (border && (window->Flags & ImGuiWindowFlags_ShowBorders))
+ 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);
- window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding);
+ 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);
+ }
+}
+
+void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ 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, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
// Render a triangle to denote expanded/collapsed state
-void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale)
+void ImGui::RenderTriangle(ImVec2 p_min, ImGuiDir dir, float scale)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = g.CurrentWindow;
const float h = g.FontSize * 1.00f;
- const float r = h * 0.40f * scale;
- ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale);
+ float r = h * 0.40f * scale;
+ ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
ImVec2 a, b, c;
- if (is_open)
+ switch (dir)
{
- center.y -= r*0.25f;
- a = center + ImVec2(0,1)*r;
- b = center + ImVec2(-0.866f,-0.5f)*r;
- c = center + ImVec2(0.866f,-0.5f)*r;
- }
- else
- {
- a = center + ImVec2(1,0)*r;
- b = center + ImVec2(-0.500f,0.866f)*r;
- c = center + ImVec2(-0.500f,-0.866f)*r;
+ case ImGuiDir_Up:
+ case ImGuiDir_Down:
+ if (dir == ImGuiDir_Up) r = -r;
+ center.y -= r * 0.25f;
+ a = ImVec2(0,1) * r;
+ b = ImVec2(-0.866f,-0.5f) * r;
+ c = ImVec2(+0.866f,-0.5f) * r;
+ break;
+ case ImGuiDir_Left:
+ case ImGuiDir_Right:
+ if (dir == ImGuiDir_Left) r = -r;
+ center.x -= r * 0.25f;
+ a = ImVec2(1,0) * r;
+ b = ImVec2(-0.500f,+0.866f) * r;
+ c = ImVec2(-0.500f,-0.866f) * r;
+ break;
+ case ImGuiDir_None:
+ case ImGuiDir_Count_:
+ IM_ASSERT(0);
+ break;
}
- window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text));
+ window->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
}
void ImGui::RenderBullet(ImVec2 pos)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
}
-void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col)
+void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = g.CurrentWindow;
- ImVec2 a, b, c;
- float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f);
- float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f);
- a.x = pos.x + 0.5f + start_x;
- b.x = a.x + rem_third;
- c.x = a.x + rem_third * 3.0f;
- b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y);
- a.y = b.y - rem_third;
- c.y = b.y - rem_third * 2.0f;
+ float thickness = ImMax(sz / 5.0f, 1.0f);
+ sz -= thickness*0.5f;
+ pos += ImVec2(thickness*0.25f, thickness*0.25f);
- window->DrawList->PathLineTo(a);
- window->DrawList->PathLineTo(b);
- window->DrawList->PathLineTo(c);
- window->DrawList->PathStroke(col, false);
+ float third = sz / 3.0f;
+ float bx = pos.x + third;
+ float by = pos.y + sz - third*0.5f;
+ window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
+ window->DrawList->PathLineTo(ImVec2(bx, by));
+ window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
+ window->DrawList->PathStroke(col, false, thickness);
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
@@ -3042,7 +3372,7 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
- // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field)
+ // Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field)
const float font_scale = font_size / font->FontSize;
const float character_spacing_x = 1.0f * font_scale;
if (text_size.x > 0.0f)
@@ -3058,7 +3388,7 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
@@ -3083,20 +3413,18 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items
// Find window given position, search front-to-back
// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via 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 thankfully isn't affected.
-static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs)
+static ImGuiWindow* FindHoveredWindow(ImVec2 pos)
{
ImGuiContext& g = *GImGui;
- for (int i = g.Windows.Size-1; i >= 0; i--)
+ for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active)
continue;
if (window->Flags & ImGuiWindowFlags_NoInputs)
continue;
- if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0)
- continue;
- // Using the clipped AABB so a child window will typically be clipped by its parent.
+ // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
if (bb.Contains(pos))
return window;
@@ -3110,80 +3438,76 @@ static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
- rect_clipped.Clip(window->ClipRect);
+ rect_clipped.ClipWith(window->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
return rect_for_touch.Contains(g.IO.MousePos);
}
-bool ImGui::IsMouseHoveringWindow()
-{
- ImGuiContext& g = *GImGui;
- return g.HoveredWindow == g.CurrentWindow;
-}
-
-bool ImGui::IsMouseHoveringAnyWindow()
-{
- ImGuiContext& g = *GImGui;
- return g.HoveredWindow != NULL;
-}
-
-bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos)
-{
- return FindHoveredWindow(pos, false) != NULL;
-}
-
static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
{
const int key_index = GImGui->IO.KeyMap[key];
- return ImGui::IsKeyPressed(key_index, repeat);
+ return (key_index >= 0) ? ImGui::IsKeyPressed(key_index, repeat) : false;
}
-int ImGui::GetKeyIndex(ImGuiKey key)
+int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
- IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT);
- return GImGui->IO.KeyMap[key];
+ IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
+ return GImGui->IO.KeyMap[imgui_key];
}
-bool ImGui::IsKeyDown(int key_index)
+// Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]!
+bool ImGui::IsKeyDown(int user_key_index)
{
- if (key_index < 0) return false;
- IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
- return GImGui->IO.KeysDown[key_index];
+ if (user_key_index < 0) return false;
+ IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
+ return GImGui->IO.KeysDown[user_key_index];
}
-bool ImGui::IsKeyPressed(int key_index, bool repeat)
+int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
+{
+ if (t == 0.0f)
+ return 1;
+ if (t <= repeat_delay || repeat_rate <= 0.0f)
+ return 0;
+ const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
+ return (count > 0) ? count : 0;
+}
+
+int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0) return false;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
+ return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
+}
+
+bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
+{
+ ImGuiContext& g = *GImGui;
+ if (user_key_index < 0) return false;
+ IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
+ const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
-
if (repeat && t > g.IO.KeyRepeatDelay)
- {
- float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
- if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
- return true;
- }
+ return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
-bool ImGui::IsKeyReleased(int key_index)
+bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
- if (key_index < 0) return false;
- IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
- if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index])
- return true;
- return false;
+ if (user_key_index < 0) return false;
+ IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
+ return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(int button)
@@ -3246,10 +3570,20 @@ ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.CurrentPopupStack.Size > 0)
- return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen;
+ return g.OpenPopupStack[g.CurrentPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
+// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position
+bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
+{
+ if (mouse_pos == NULL)
+ mouse_pos = &GImGui->IO.MousePos;
+ const float MOUSE_INVALID = -256000.0f;
+ return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
+}
+
+// NB: This is only valid if IsMousePosValid(). Backends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
@@ -3282,24 +3616,12 @@ void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
void ImGui::CaptureKeyboardFromApp(bool capture)
{
- GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0;
+ GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
- GImGui->CaptureMouseNextFrame = capture ? 1 : 0;
-}
-
-bool ImGui::IsItemHovered()
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->DC.LastItemHoveredAndUsable;
-}
-
-bool ImGui::IsItemHoveredRect()
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->DC.LastItemHoveredRect;
+ GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
@@ -3307,7 +3629,7 @@ bool ImGui::IsItemActive()
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
@@ -3315,12 +3637,13 @@ bool ImGui::IsItemActive()
bool ImGui::IsItemClicked(int mouse_button)
{
- return IsMouseClicked(mouse_button) && IsItemHovered();
+ return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_Default);
}
bool ImGui::IsAnyItemHovered()
{
- return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0;
+ ImGuiContext& g = *GImGui;
+ return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
@@ -3331,8 +3654,7 @@ bool ImGui::IsAnyItemActive()
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
- ImRect r(window->ClipRect);
- return r.Overlaps(window->DC.LastItemRect);
+ return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
@@ -3363,19 +3685,37 @@ ImVec2 ImGui::GetItemRectSize()
return window->DC.LastItemRect.GetSize();
}
-ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward)
-{
- ImGuiWindow* window = GetCurrentWindowRead();
- ImRect rect = window->DC.LastItemRect;
- rect.Expand(outward);
- return rect.GetClosestPoint(pos, on_edge);
-}
-
-// Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value.
-void ImGui::SetTooltipV(const char* fmt, va_list args)
+static ImRect GetVisibleRect()
{
ImGuiContext& g = *GImGui;
- ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args);
+ if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
+ return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
+ return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
+}
+
+// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
+void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
+{
+ ImGuiContext& g = *GImGui;
+ char window_name[16];
+ ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
+ if (override_previous_tooltip)
+ if (ImGuiWindow* window = FindWindowByName(window_name))
+ if (window->Active)
+ {
+ // Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one.
+ window->HiddenFrames = 1;
+ ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
+ }
+ ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
+ Begin(window_name, NULL, flags | extra_flags);
+}
+
+void ImGui::SetTooltipV(const char* fmt, va_list args)
+{
+ BeginTooltipEx(0, true);
+ TextV(fmt, args);
+ EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
@@ -3386,67 +3726,75 @@ void ImGui::SetTooltip(const char* fmt, ...)
va_end(args);
}
-static ImRect GetVisibleRect()
-{
- ImGuiContext& g = *GImGui;
- if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
- return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
- return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
-}
-
void ImGui::BeginTooltip()
{
- ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
- ImGui::Begin("##Tooltip", NULL, flags);
+ BeginTooltipEx(0, false);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
- ImGui::End();
-}
-
-static bool IsPopupOpen(ImGuiID id)
-{
- ImGuiContext& g = *GImGui;
- return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
+ End();
}
// 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(const char* str_id, bool reopen_existing)
+void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- ImGuiID id = window->GetID(str_id);
+ ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.CurrentPopupStack.Size;
- ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here)
+ ImGuiPopupRef 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;
+ popup_ref.ParentWindow = parent_window;
+ popup_ref.OpenFrameCount = g.FrameCount;
+ popup_ref.OpenParentId = parent_window->IDStack.back();
+ popup_ref.OpenMousePos = g.IO.MousePos;
+ popup_ref.OpenPopupPos = g.IO.MousePos; // NB: In the Navigation branch OpenPopupPos doesn't use the mouse position, hence the separation here.
+
if (g.OpenPopupStack.Size < current_stack_size + 1)
- g.OpenPopupStack.push_back(popup_ref);
- else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id)
{
- g.OpenPopupStack.resize(current_stack_size+1);
- g.OpenPopupStack[current_stack_size] = popup_ref;
+ g.OpenPopupStack.push_back(popup_ref);
+ }
+ else
+ {
+ // Close child popups if any
+ g.OpenPopupStack.resize(current_stack_size + 1);
+
+ // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
+ // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
+ // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
+ if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
+ g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
+ else
+ g.OpenPopupStack[current_stack_size] = popup_ref;
+
+ // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by CloseInactivePopups().
+ // This is equivalent to what ClosePopupToLevel() does.
+ //if (g.OpenPopupStack[current_stack_size].PopupId == id)
+ // FocusWindow(parent_window);
}
}
void ImGui::OpenPopup(const char* str_id)
{
- ImGui::OpenPopupEx(str_id, false);
+ ImGuiContext& g = *GImGui;
+ OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
-static void CloseInactivePopups()
+static void CloseInactivePopups(ImGuiWindow* ref_window)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
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
+ // Don't close our own child popup windows.
int n = 0;
- if (g.FocusedWindow)
+ if (ref_window)
{
for (n = 0; n < g.OpenPopupStack.Size; n++)
{
@@ -3457,24 +3805,25 @@ static void CloseInactivePopups()
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
+ // Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow)
bool has_focus = false;
for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
- has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow);
+ has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow);
if (!has_focus)
break;
}
}
- if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below
- g.OpenPopupStack.resize(n);
+ if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the block below
+ ClosePopupToLevel(n);
}
static ImGuiWindow* GetFrontMostModalRootWindow()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
- if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window)
- if (front_most_popup->Flags & ImGuiWindowFlags_Modal)
- return front_most_popup;
+ if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
+ if (popup->Flags & ImGuiWindowFlags_Modal)
+ return popup;
return NULL;
}
@@ -3488,7 +3837,7 @@ static void ClosePopupToLevel(int remaining)
g.OpenPopupStack.resize(remaining);
}
-static void ClosePopup(ImGuiID id)
+void ImGui::ClosePopup(ImGuiID id)
{
if (!IsPopupOpen(id))
return;
@@ -3501,75 +3850,78 @@ void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.CurrentPopupStack.Size - 1;
- if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
+ if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
popup_idx--;
ClosePopupToLevel(popup_idx);
}
-static inline void ClearSetNextWindowData()
+bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0;
- g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false;
-}
-
-static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags)
-{
- ImGuiContext& g = *GImGui;
- ImGuiWindow* window = g.CurrentWindow;
- const ImGuiID id = window->GetID(str_id);
if (!IsPopupOpen(id))
{
- ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
- ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
- ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
-
char name[20];
- if (flags & ImGuiWindowFlags_ChildMenu)
- ImFormatString(name, IM_ARRAYSIZE(name), "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth
+ if (extra_flags & ImGuiWindowFlags_ChildMenu)
+ ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
else
- ImFormatString(name, IM_ARRAYSIZE(name), "##popup_%08x", id); // Not recycling, so we can close/open during the same frame
+ ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
- bool is_open = ImGui::Begin(name, NULL, flags);
- if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
- g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders;
- if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
- ImGui::EndPopup();
+ bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
+ if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
+ EndPopup();
return is_open;
}
-bool ImGui::BeginPopup(const char* str_id)
+bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
- if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance
+ ImGuiContext& g = *GImGui;
+ if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance
{
- ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
- return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders);
+ return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
-bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags)
+bool ImGui::IsPopupOpen(ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
+}
+
+bool ImGui::IsPopupOpen(const char* str_id)
+{
+ ImGuiContext& g = *GImGui;
+ return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
+}
+
+bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
- ClearSetNextWindowData(); // We behave like Begin() and need to consume those values
+ g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
- ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings;
- bool is_open = ImGui::Begin(name, p_open, flags);
+ // Center modal windows by default
+ // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
+ if (g.NextWindowData.PosCond == 0)
+ SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+
+ bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
- ImGui::EndPopup();
+ EndPopup();
if (is_open)
ClosePopup(id);
return false;
@@ -3580,79 +3932,90 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags ext
void ImGui::EndPopup()
{
- ImGuiWindow* window = GetCurrentWindow();
- IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
- IM_ASSERT(GImGui->CurrentPopupStack.Size > 0);
- ImGui::End();
- if (!(window->Flags & ImGuiWindowFlags_Modal))
- ImGui::PopStyleVar();
+ ImGuiContext& g = *GImGui; (void)g;
+ IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
+ IM_ASSERT(g.CurrentPopupStack.Size > 0);
+ End();
}
-// This is a helper to handle the most simple case of associating one named popup to one given widget.
-// 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling
-// this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers.
-// 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect()
-// and passing true to the OpenPopupEx().
-// Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that
-// the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu
-// driven by click position.
+bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
+{
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ 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); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
+ OpenPopupEx(id);
+ 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, int mouse_button)
{
- if (IsItemHovered() && IsMouseClicked(mouse_button))
- OpenPopupEx(str_id, false);
- return BeginPopup(str_id);
+ ImGuiWindow* window = GImGui->CurrentWindow;
+ 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); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
+ if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
+ OpenPopupEx(id);
+ return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
-bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button)
+bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
{
- if (!str_id) str_id = "window_context_menu";
- if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button))
+ if (!str_id)
+ str_id = "window_context";
+ ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
+ if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (also_over_items || !IsAnyItemHovered())
- OpenPopupEx(str_id, true);
- return BeginPopup(str_id);
+ OpenPopupEx(id);
+ return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
{
- if (!str_id) str_id = "void_context_menu";
- if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button))
- OpenPopupEx(str_id, true);
- return BeginPopup(str_id);
+ if (!str_id)
+ str_id = "void_context";
+ ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
+ if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
+ OpenPopupEx(id);
+ return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
- ImGuiWindow* window = ImGui::GetCurrentWindow();
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* parent_window = ImGui::GetCurrentWindow();
ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
+ flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
const ImVec2 content_avail = ImGui::GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
+ const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
- {
- if (size.x == 0.0f)
- flags |= ImGuiWindowFlags_ChildWindowAutoFitX;
- size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues)
- }
+ size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
- {
- if (size.y == 0.0f)
- flags |= ImGuiWindowFlags_ChildWindowAutoFitY;
- size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y);
- }
- if (border)
- flags |= ImGuiWindowFlags_ShowBorders;
+ size.y = ImMax(content_avail.y + size.y, 4.0f);
+
+ const float backup_border_size = g.Style.ChildBorderSize;
+ if (!border)
+ g.Style.ChildBorderSize = 0.0f;
flags |= extra_flags;
char title[256];
if (name)
- ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", window->Name, name, id);
+ ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
- ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", window->Name, id);
+ ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
- bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags);
-
- if (!(window->Flags & ImGuiWindowFlags_ShowBorders))
- ImGui::GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders;
+ ImGui::SetNextWindowSize(size);
+ bool ret = ImGui::Begin(title, NULL, flags);
+ ImGuiWindow* child_window = ImGui::GetCurrentWindow();
+ child_window->AutoFitChildAxises = auto_fit_axises;
+ g.Style.ChildBorderSize = backup_border_size;
return ret;
}
@@ -3673,25 +4036,24 @@ void ImGui::EndChild()
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
- if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1)
+ if (window->BeginCount > 1)
{
- ImGui::End();
+ End();
}
else
{
// When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting.
ImVec2 sz = GetWindowSize();
- if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
+ if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
- if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY)
+ if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
+ End();
- ImGui::End();
-
- window = GetCurrentWindow();
- ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz);
+ ImGuiWindow* parent_window = GetCurrentWindow();
+ ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
- ItemAdd(bb, NULL);
+ ItemAdd(bb, 0);
}
}
@@ -3700,17 +4062,18 @@ bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags ext
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
- ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]);
- ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding);
- ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
- return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
+ PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
+ PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
+ PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
+ PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
+ return BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
}
void ImGui::EndChildFrame()
{
- ImGui::EndChild();
- ImGui::PopStyleVar(2);
- ImGui::PopStyleColor();
+ EndChild();
+ PopStyleVar(3);
+ PopStyleColor();
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
@@ -3719,52 +4082,93 @@ static void CheckStacksSize(ImGuiWindow* window, bool write)
// NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
ImGuiContext& g = *GImGui;
int* p_backup = &window->DC.StackSizesBackup[0];
- { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID Mismatch!"); p_backup++; } // User forgot PopID()
- { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // User forgot EndGroup()
- { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++; }// User forgot EndPopup()/EndMenu()
- { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // User forgot PopStyleColor()
- { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // User forgot PopStyleVar()
- { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // User forgot PopFont()
+ { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
+ { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
+ { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
+ { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
+ { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
+ { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
-static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner)
+enum ImGuiPopupPositionPolicy
+{
+ ImGuiPopupPositionPolicy_Default,
+ ImGuiPopupPositionPolicy_ComboBox
+};
+
+static ImVec2 FindBestWindowPosForPopup(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default)
{
const ImGuiStyle& style = GImGui->Style;
- // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it.
+ // 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.)
+ // r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 safe_padding = style.DisplaySafeAreaPadding;
ImRect r_outer(GetVisibleRect());
- r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f));
- ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size);
+ r_outer.Expand(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? -safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? -safe_padding.y : 0.0f));
+ ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
+ //GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
+ //GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
- for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction).
+ // Combo Box policy (we want a connecting edge)
+ if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
- const int dir = (n == -1) ? *last_dir : n;
- ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y);
- if (rect.GetWidth() < size.x || rect.GetHeight() < size.y)
+ const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
+ for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++)
+ {
+ const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
+ if (n != -1 && dir == *last_dir) // Already tried this direction?
+ continue;
+ ImVec2 pos;
+ if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
+ if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
+ if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
+ if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
+ if (!r_outer.Contains(ImRect(pos, pos + size)))
+ continue;
+ *last_dir = dir;
+ return pos;
+ }
+ }
+
+ // Default popup policy
+ const ImGuiDir dir_prefered_order[ImGuiDir_Count_] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
+ for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_Count_; n++)
+ {
+ const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
+ if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
+ float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
+ float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
+ if (avail_w < size.x || avail_h < size.y)
+ continue;
+ ImVec2 pos;
+ pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
+ pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
- return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y);
+ return pos;
}
// Fallback, try to keep within display
- *last_dir = -1;
- ImVec2 pos = base_pos;
+ *last_dir = ImGuiDir_None;
+ ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
+static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
+{
+ window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
+ window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
+ window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
+}
+
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
- // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block
ImGuiContext& g = *GImGui;
ImGuiID id = ImHash(name, 0);
- for (int i = 0; i < g.Windows.Size; i++)
- if (g.Windows[i]->ID == id)
- return g.Windows[i];
- return NULL;
+ return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
@@ -3772,45 +4176,28 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
ImGuiContext& g = *GImGui;
// Create window the first time
- ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow));
- IM_PLACEMENT_NEW(window) ImGuiWindow(name);
+ ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
+ g.WindowsById.SetVoidPtr(window->ID, window);
- if (flags & ImGuiWindowFlags_NoSavedSettings)
- {
- // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
- window->Size = window->SizeFull = size;
- }
- else
+ // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
+ if (!(flags & ImGuiWindowFlags_NoSavedSettings))
{
// Retrieve settings from .ini file
// Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
- window->PosFloat = ImVec2(60, 60);
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = window->PosFloat = ImVec2(60, 60);
- ImGuiIniData* settings = FindWindowSettings(name);
- if (!settings)
- {
- settings = AddWindowSettings(name);
- }
- else
- {
- window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver;
- window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver;
- window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver;
- }
-
- if (settings->Pos.x != FLT_MAX)
+ if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
+ SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->PosFloat = settings->Pos;
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = ImFloor(window->PosFloat);
window->Collapsed = settings->Collapsed;
+ if (ImLengthSqr(settings->Size) > 0.00001f)
+ size = settings->Size;
}
-
- if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize))
- size = settings->Size;
- window->Size = window->SizeFull = size;
}
+ window->Size = window->SizeFull = window->SizeFullAtLastBegin = size;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
@@ -3833,46 +4220,240 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl
return window;
}
-static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size)
+static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
- if (g.SetNextWindowSizeConstraint)
+ if (g.NextWindowData.SizeConstraintCond != 0)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
- ImRect cr = g.SetNextWindowSizeConstraintRect;
+ ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
- if (g.SetNextWindowSizeConstraintCallback)
+ if (g.NextWindowData.SizeCallback)
{
- ImGuiSizeConstraintCallbackData data;
- data.UserData = g.SetNextWindowSizeConstraintCallbackUserData;
+ ImGuiSizeCallbackData data;
+ data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
- g.SetNextWindowSizeConstraintCallback(&data);
+ g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
}
+
+ // Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
+ {
new_size = ImMax(new_size, g.Style.WindowMinSize);
- window->SizeFull = new_size;
+ new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
+ }
+ return new_size;
+}
+
+static ImVec2 CalcSizeContents(ImGuiWindow* window)
+{
+ ImVec2 sz;
+ sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
+ sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
+ return sz + window->WindowPadding;
+}
+
+static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiStyle& style = g.Style;
+ ImGuiWindowFlags flags = window->Flags;
+ ImVec2 size_auto_fit;
+ if ((flags & ImGuiWindowFlags_Tooltip) != 0)
+ {
+ // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
+ size_auto_fit = size_contents;
+ }
+ else
+ {
+ // When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
+ size_auto_fit = ImClamp(size_contents, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
+ ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
+ if (size_auto_fit_after_constraint.x < size_contents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
+ size_auto_fit.y += style.ScrollbarSize;
+ if (size_auto_fit_after_constraint.y < size_contents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
+ size_auto_fit.x += style.ScrollbarSize;
+ }
+ return size_auto_fit;
+}
+
+static float GetScrollMaxX(ImGuiWindow* window)
+{
+ return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
+}
+
+static float GetScrollMaxY(ImGuiWindow* window)
+{
+ return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
+}
+
+static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
+{
+ ImVec2 scroll = window->Scroll;
+ float cr_x = window->ScrollTargetCenterRatio.x;
+ float cr_y = window->ScrollTargetCenterRatio.y;
+ if (window->ScrollTarget.x < FLT_MAX)
+ scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
+ if (window->ScrollTarget.y < FLT_MAX)
+ scroll.y = window->ScrollTarget.y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
+ scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
+ if (!window->Collapsed && !window->SkipItems)
+ {
+ scroll.x = ImMin(scroll.x, GetScrollMaxX(window));
+ scroll.y = ImMin(scroll.y, GetScrollMaxY(window));
+ }
+ return scroll;
+}
+
+static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
+{
+ if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
+ return ImGuiCol_PopupBg;
+ if (flags & ImGuiWindowFlags_ChildWindow)
+ return ImGuiCol_ChildBg;
+ return ImGuiCol_WindowBg;
+}
+
+static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
+{
+ ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
+ ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
+ ImVec2 size_expected = pos_max - pos_min;
+ ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
+ *out_pos = pos_min;
+ if (corner_norm.x == 0.0f)
+ out_pos->x -= (size_constrained.x - size_expected.x);
+ if (corner_norm.y == 0.0f)
+ out_pos->y -= (size_constrained.y - size_expected.y);
+ *out_size = size_constrained;
+}
+
+struct ImGuiResizeGripDef
+{
+ ImVec2 CornerPos;
+ ImVec2 InnerDir;
+ int AngleMin12, AngleMax12;
+};
+
+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
+ { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
+};
+
+static ImRect GetBorderRect(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, rect.Max.x - perp_padding, rect.Min.y + thickness);
+ if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x, rect.Max.y - perp_padding);
+ if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y);
+ if (border_n == 3) return ImRect(rect.Min.x, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding);
+ IM_ASSERT(0);
+ return ImRect();
+}
+
+// Handle resize for: Resize Grips, Borders, Gamepad
+static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindowFlags flags = window->Flags;
+ if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
+ return;
+
+ const int resize_border_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 4 : 0;
+ const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
+ const float grip_hover_size = (float)(int)(grip_draw_size * 0.75f);
+
+ ImVec2 pos_target(FLT_MAX, FLT_MAX);
+ ImVec2 size_target(FLT_MAX, FLT_MAX);
+
+ // Manual resize grips
+ PushID("#RESIZE");
+ for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
+ {
+ const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
+ const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
+
+ // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
+ ImRect resize_rect(corner, corner + grip.InnerDir * grip_hover_size);
+ resize_rect.FixInverted();
+ bool hovered, held;
+ ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
+ if (hovered || held)
+ g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
+
+ if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
+ {
+ // Manual auto-fit when double-clicking
+ size_target = CalcSizeAfterConstraint(window, size_auto_fit);
+ ClearActiveID();
+ }
+ else if (held)
+ {
+ // 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 + resize_rect.GetSize() * grip.CornerPos; // Corner of the window corresponding to our corner grip
+ CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target);
+ }
+ if (resize_grip_n == 0 || held || hovered)
+ resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
+ }
+ for (int border_n = 0; border_n < resize_border_count; border_n++)
+ {
+ const float BORDER_SIZE = 5.0f; // FIXME: Only works _inside_ window because of HoveredWindow check.
+ const float BORDER_APPEAR_TIMER = 0.05f; // Reduce visual noise
+ bool hovered, held;
+ ImRect border_rect = GetBorderRect(window, border_n, grip_hover_size, BORDER_SIZE);
+ ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
+ if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held)
+ {
+ g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
+ if (held) *border_held = border_n;
+ }
+ if (held)
+ {
+ ImVec2 border_target = window->Pos;
+ ImVec2 border_posn;
+ if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y); }
+ if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + BORDER_SIZE); }
+ if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + BORDER_SIZE); }
+ if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x); }
+ CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
+ }
+ }
+ PopID();
+
+ // Apply back modified position/size to window
+ if (size_target.x != FLT_MAX)
+ {
+ window->SizeFull = size_target;
+ MarkIniSettingsDirty(window);
+ }
+ if (pos_target.x != FLT_MAX)
+ {
+ window->Pos = window->PosFloat = ImFloor(pos_target);
+ MarkIniSettingsDirty(window);
+ }
+
+ window->Size = window->SizeFull;
}
// Push a new ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
-// - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
-// - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin().
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
-{
- return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags);
-}
-
-bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
@@ -3880,130 +4461,140 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
- if (flags & ImGuiWindowFlags_NoInputs)
- flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
-
// Find or create
- bool window_is_new = false;
ImGuiWindow* window = FindWindowByName(name);
if (!window)
{
+ ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? 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_is_new = true;
}
- const int current_frame = ImGui::GetFrameCount();
+ // Automatically disable manual moving/resizing when NoInputs is set
+ if (flags & ImGuiWindowFlags_NoInputs)
+ flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
+ //if (flags & ImGuiWindowFlags_NavFlattened)
+ // IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
+
+ const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
if (first_begin_of_the_frame)
window->Flags = (ImGuiWindowFlags)flags;
else
flags = window->Flags;
- // Add to stack
- ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL;
- g.CurrentWindowStack.push_back(window);
- SetCurrentWindow(window);
- CheckStacksSize(window, true);
- IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
-
- bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
+ // Update the Appearing flag
+ bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
+ const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames == 1);
+ if (flags & ImGuiWindowFlags_Popup)
+ {
+ ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
+ window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
+ window_just_activated_by_user |= (window != popup_ref.Window);
+ }
+ window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
+ window->CloseButton = (p_open != NULL);
+ if (window->Appearing)
+ SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
+
+ // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
+ ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
+ ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
+ IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
+
+ // Add to stack
+ g.CurrentWindowStack.push_back(window);
+ SetCurrentWindow(window);
+ CheckStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
- window_was_active &= (window->PopupId == popup_ref.PopupId);
- window_was_active &= (window == popup_ref.Window);
popup_ref.Window = window;
g.CurrentPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
- const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1);
-
// Process SetNextWindow***() calls
- bool window_pos_set_by_api = false, window_size_set_by_api = false;
- if (g.SetNextWindowPosCond)
+ bool window_pos_set_by_api = false;
+ bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
+ if (g.NextWindowData.PosCond)
{
- const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that.
- if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing;
- window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0;
- if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f)
+ window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
+ if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
- window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size
- window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
+ // May be processed on the next frame if this is our first frame and we are measuring size
+ // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
+ window->SetWindowPosVal = g.NextWindowData.PosVal;
+ window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
+ window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
- SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond);
+ SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
- window->DC.CursorPos = backup_cursor_pos;
- g.SetNextWindowPosCond = 0;
+ g.NextWindowData.PosCond = 0;
}
- if (g.SetNextWindowSizeCond)
+ if (g.NextWindowData.SizeCond)
{
- if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing;
- window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0;
- SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond);
- g.SetNextWindowSizeCond = 0;
+ window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
+ window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
+ SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
+ g.NextWindowData.SizeCond = 0;
}
- if (g.SetNextWindowContentSizeCond)
+ if (g.NextWindowData.ContentSizeCond)
{
- window->SizeContentsExplicit = g.SetNextWindowContentSizeVal;
- g.SetNextWindowContentSizeCond = 0;
+ // Adjust passed "client size" to become a "window size"
+ window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
+ if (window->SizeContentsExplicit.y != 0.0f)
+ window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
+ g.NextWindowData.ContentSizeCond = 0;
}
else if (first_begin_of_the_frame)
{
window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
}
- if (g.SetNextWindowCollapsedCond)
+ if (g.NextWindowData.CollapsedCond)
{
- if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing;
- SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond);
- g.SetNextWindowCollapsedCond = 0;
+ SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
+ g.NextWindowData.CollapsedCond = 0;
}
- if (g.SetNextWindowFocus)
+ if (g.NextWindowData.FocusCond)
{
- ImGui::SetWindowFocus();
- g.SetNextWindowFocus = false;
+ SetWindowFocus();
+ g.NextWindowData.FocusCond = 0;
}
-
- // Update known root window (if we are a child window, otherwise window == window->RootWindow)
- int root_idx, root_non_popup_idx;
- for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--)
- if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow))
- break;
- for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--)
- if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
- break;
- window->ParentWindow = parent_window;
- window->RootWindow = g.CurrentWindowStack[root_idx];
- window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color.
+ if (window->Appearing)
+ SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
+ const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
+
+ // Initialize
+ window->ParentWindow = parent_window;
+ window->RootWindow = window->RootNonPopupWindow = window;
+ if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !window_is_child_tooltip)
+ window->RootWindow = parent_window->RootWindow;
+ if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
+ window->RootNonPopupWindow = parent_window->RootNonPopupWindow;
+ //window->RootNavWindow = window;
+ //while (window->RootNavWindow->Flags & ImGuiWindowFlags_NavFlattened)
+ // window->RootNavWindow = window->RootNavWindow->ParentWindow;
+
window->Active = true;
- window->IndexWithinParent = 0;
+ window->BeginOrderWithinParent = 0;
+ window->BeginOrderWithinContext = g.WindowsActiveCount++;
window->BeginCount = 0;
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->LastFrameActive = current_frame;
window->IDStack.resize(1);
- // Clear draw list, setup texture, outer clipping rectangle
- window->DrawList->Clear();
- window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
- ImRect fullscreen_rect(GetVisibleRect());
- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup)))
- PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
- else
- PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
-
- if (!window_was_active)
- {
- // Popup first latch mouse position, will position itself when it appears next frame
- window->AutoPosLastDirection = -1;
- if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
- window->PosFloat = g.IO.MousePos;
- }
+ // Lock window rounding, border size and rounding so that altering the border sizes for children doesn't have side-effects.
+ window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
+ window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
+ window->WindowPadding = style.WindowPadding;
+ if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
+ window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
@@ -4013,8 +4604,7 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
{
window->Collapsed = !window->Collapsed;
- if (!(flags & ImGuiWindowFlags_NoSavedSettings))
- MarkIniSettingsDirty();
+ MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
@@ -4025,123 +4615,120 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
// SIZE
- // Save contents size from last frame for auto-fitting (unless explicitly specified)
- window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x));
- window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y));
+ // Update contents size from last frame for auto-fitting (unless explicitly specified)
+ window->SizeContents = CalcSizeContents(window);
- // Hide popup/tooltip window when first appearing while we measure size (because we recycle them)
+ // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
if (window->HiddenFrames > 0)
window->HiddenFrames--;
- if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active)
+ if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && window_just_activated_by_user)
{
window->HiddenFrames = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
- if (!window_size_set_by_api)
- window->Size = window->SizeFull = ImVec2(0.f, 0.f);
+ if (!window_size_x_set_by_api)
+ window->Size.x = window->SizeFull.x = 0.f;
+ if (!window_size_y_set_by_api)
+ window->Size.y = window->SizeFull.y = 0.f;
window->SizeContents = ImVec2(0.f, 0.f);
}
}
- // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects.
- window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding;
-
- // Calculate auto-fit size
- ImVec2 size_auto_fit;
- if ((flags & ImGuiWindowFlags_Tooltip) != 0)
+ // Calculate auto-fit size, handle automatic resize
+ const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
+ ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
+ if (flags & ImGuiWindowFlags_AlwaysAutoResize && !window->Collapsed)
{
- // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
- size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y);
+ // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
+ if (!window_size_x_set_by_api)
+ window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
+ if (!window_size_y_set_by_api)
+ window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
}
- else
+ else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
- size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
-
- // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
- if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
- size_auto_fit.y += style.ScrollbarSize;
- if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
- size_auto_fit.x += style.ScrollbarSize;
- size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f);
- }
-
- // Handle automatic resize
- if (window->Collapsed)
- {
- // We still process initial auto-fit on collapsed windows to get a window width,
- // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
- if (window->AutoFitFramesX > 0)
- window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
- if (window->AutoFitFramesY > 0)
- window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
- }
- else
- {
- if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api)
- {
- window->SizeFull = size_auto_fit;
- }
- else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api)
- {
- // Auto-fit only grows during the first few frames
- if (window->AutoFitFramesX > 0)
- window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
- if (window->AutoFitFramesY > 0)
- window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
- if (!(flags & ImGuiWindowFlags_NoSavedSettings))
- MarkIniSettingsDirty();
- }
+ // Auto-fit only grows during the first few frames
+ // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
+ if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
+ window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
+ if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
+ window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
+ if (!window->Collapsed)
+ MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
- ApplySizeFullWithConstraint(window, window->SizeFull);
- window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull;
-
+ window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
+ window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
+
+ // SCROLLBAR STATUS
+
+ // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
+ if (!window->Collapsed)
+ {
+ // When reading the current size we need to read it after size constraints have been applied
+ float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
+ float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
+ window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
+ window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
+ if (window->ScrollbarX && !window->ScrollbarY)
+ window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars + style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
+ window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
+ }
+
// POSITION
+ // Popup latch its initial position, will position itself when it appears next frame
+ if (window_just_activated_by_user)
+ {
+ window->AutoPosLastDirection = ImGuiDir_None;
+ if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
+ window->Pos = window->PosFloat = g.CurrentPopupStack.back().OpenPopupPos;
+ }
+
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
- window->IndexWithinParent = parent_window->DC.ChildWindows.Size;
+ window->BeginOrderWithinParent = parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
- }
- if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup))
- {
- window->Pos = window->PosFloat = parent_window->DC.CursorPos;
- window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin().
+ if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
+ window->Pos = window->PosFloat = parent_window->DC.CursorPos;
}
- bool window_pos_center = false;
- window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0);
- window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden);
- if (window_pos_center)
+ const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFrames == 0);
+ if (window_pos_with_pivot)
{
- // Center (any sort of window)
- SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f), 0);
+ // Position given a pivot (e.g. for centering)
+ SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0);
}
else if (flags & ImGuiWindowFlags_ChildMenu)
{
+ // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds.
+ // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(window_pos_set_by_api);
+ float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value).
+ ImGuiWindow* parent_menu = parent_window_in_stack;
ImRect rect_to_avoid;
- if (parent_window->DC.MenuBarAppending)
- rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
+ if (parent_menu->DC.MenuBarAppending)
+ rect_to_avoid = ImRect(-FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight(), FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight() + parent_menu->MenuBarHeight());
else
- rect_to_avoid = ImRect(parent_window->Pos.x + style.ItemSpacing.x, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - style.ItemSpacing.x - parent_window->ScrollbarSizes.x, FLT_MAX); // We want some overlap to convey the relative depth of each popup (here hard-coded to 4)
- window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
+ rect_to_avoid = ImRect(parent_menu->Pos.x + horizontal_overlap, -FLT_MAX, parent_menu->Pos.x + parent_menu->Size.x - horizontal_overlap - parent_menu->ScrollbarSizes.x, FLT_MAX);
+ window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
}
- else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden)
+ else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
{
ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
- window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
+ window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
}
// Position tooltip (always follows mouse)
- if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api)
+ if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
{
- ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead?
- window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
- if (window->AutoPosLastDirection == -1)
- window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
+ ImVec2 ref_pos = g.IO.MousePos;
+ ImRect rect_to_avoid(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24, ref_pos.y + 24); // FIXME: Completely hard-coded. Store boxes in mouse cursor data? Scale? Center on cursor hit-point?
+ window->PosFloat = FindBestWindowPosForPopup(ref_pos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
+ if (window->AutoPosLastDirection == ImGuiDir_None)
+ window->PosFloat = ref_pos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
}
// Clamp position so it stays visible
@@ -4154,7 +4741,7 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
}
}
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = ImFloor(window->PosFloat);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
@@ -4169,131 +4756,112 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
// Apply scrolling
- if (window->ScrollTarget.x < FLT_MAX)
- {
- window->Scroll.x = window->ScrollTarget.x;
- window->ScrollTarget.x = FLT_MAX;
- }
- if (window->ScrollTarget.y < FLT_MAX)
- {
- float center_ratio = window->ScrollTargetCenterRatio.y;
- window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y);
- window->ScrollTarget.y = FLT_MAX;
- }
- window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f));
- if (!window->Collapsed && !window->SkipItems)
- window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes));
+ window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
+ window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
- // Modal window darkens what is behind them
+ // Apply focus, new windows appears in front
+ bool want_focus = false;
+ if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
+ if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
+ want_focus = true;
+
+ // Handle manual resize: Resize Grips, Borders, Gamepad
+ int border_held = -1;
+ ImU32 resize_grip_col[4] = { 0 };
+ const int resize_grip_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 2 : 1; // 4
+ const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
+ if (!window->Collapsed)
+ UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
+
+ // DRAWING
+
+ // Setup draw list and outer clipping rectangle
+ window->DrawList->Clear();
+ window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
+ window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
+ ImRect fullscreen_rect(GetVisibleRect());
+ if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
+ PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
+ else
+ PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true);
+
+ // Draw modal window background (darkens what is behind them)
if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
// Draw window + handle manual resize
+ const float window_rounding = window->WindowRounding;
+ const float window_border_size = window->WindowBorderSize;
ImRect title_bar_rect = window->TitleBarRect();
- const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
+ const bool window_is_focused = want_focus || (g.NavWindow && window->RootNonPopupWindow == g.NavWindow->RootNonPopupWindow);
if (window->Collapsed)
{
- // Draw title bar only
- RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
+ // Title bar only
+ float backup_border_size = style.FrameBorderSize;
+ g.Style.FrameBorderSize = window->WindowBorderSize;
+ RenderFrame(title_bar_rect.Min, title_bar_rect.Max, GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding);
+ g.Style.FrameBorderSize = backup_border_size;
}
else
{
- ImU32 resize_col = 0;
- const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f);
- if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize))
+ // Window background
+ ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
+ if (g.NextWindowData.BgAlphaCond != 0)
{
- // Manual resize
- const ImVec2 br = window->Rect().GetBR();
- const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br);
- const ImGuiID resize_id = window->GetID("#RESIZE");
- bool hovered, held;
- ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds);
- resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
-
- if (hovered || held)
- g.MouseCursor = ImGuiMouseCursor_ResizeNWSE;
-
- if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0])
- {
- // Manual auto-fit when double-clicking
- ApplySizeFullWithConstraint(window, size_auto_fit);
- if (!(flags & ImGuiWindowFlags_NoSavedSettings))
- MarkIniSettingsDirty();
- ClearActiveID();
- }
- else if (held)
- {
- // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
- ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos);
- if (!(flags & ImGuiWindowFlags_NoSavedSettings))
- MarkIniSettingsDirty();
- }
-
- window->Size = window->SizeFull;
- title_bar_rect = window->TitleBarRect();
+ bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
+ g.NextWindowData.BgAlphaCond = 0;
}
-
- // Scrollbars
- window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar));
- window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
- window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
- window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f;
-
- // Window background, Default Alpha
- ImGuiCol bg_color_idx = ImGuiCol_WindowBg;
- if ((flags & ImGuiWindowFlags_ComboBox) != 0)
- bg_color_idx = ImGuiCol_ComboBg;
- else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0)
- bg_color_idx = ImGuiCol_PopupBg;
- else if ((flags & ImGuiWindowFlags_ChildWindow) != 0)
- bg_color_idx = ImGuiCol_ChildWindowBg;
- ImVec4 bg_color = style.Colors[bg_color_idx];
- if (bg_alpha >= 0.0f)
- bg_color.w = bg_alpha;
- bg_color.w *= style.Alpha;
- if (bg_color.w > 0.0f)
- window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImGuiCorner_All : ImGuiCorner_BottomLeft|ImGuiCorner_BottomRight);
+ window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
- window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImGuiCorner_TopLeft|ImGuiCorner_TopRight);
+ window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImDrawCornerFlags_Top);
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
- if (flags & ImGuiWindowFlags_ShowBorders)
- window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border));
- window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImGuiCorner_TopLeft|ImGuiCorner_TopRight);
+ menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
+ window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
+ if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
+ window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Scrollbars
if (window->ScrollbarX)
- Scrollbar(window, true);
+ Scrollbar(ImGuiLayoutType_Horizontal);
if (window->ScrollbarY)
- Scrollbar(window, false);
+ Scrollbar(ImGuiLayoutType_Vertical);
- // Render resize grip
- // (after the input handling so we don't have a frame of latency)
+ // Render resize grips (after their input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
- const ImVec2 br = window->Rect().GetBR();
- window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize));
- window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size));
- window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3);
- window->DrawList->PathFill(resize_col);
+ for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
+ {
+ const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
+ const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
+ window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size)));
+ window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size)));
+ window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
+ window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
+ }
}
// Borders
- if (flags & ImGuiWindowFlags_ShowBorders)
+ if (window_border_size > 0.0f)
+ window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size);
+ if (border_held != -1)
{
- window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding);
- window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding);
- if (!(flags & ImGuiWindowFlags_NoTitleBar))
- window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border));
+ ImRect border = GetBorderRect(window, border_held, grip_draw_size, 0.0f);
+ window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size));
}
+ if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar))
+ window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize,-1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
+ // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
+ window->SizeFullAtLastBegin = window->SizeFull;
+
// Update ContentsRegionMax. All the variable it depends on are set above in this function.
window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
@@ -4301,6 +4869,7 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
// Setup drawing context
+ // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffsetX = 0.0f;
window->DC.ColumnsOffsetX = 0.0f;
@@ -4315,65 +4884,67 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
window->DC.ChildWindows.resize(0);
window->DC.LayoutType = ImGuiLayoutType_Vertical;
+ window->DC.ItemFlags = ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
- window->DC.AllowKeyboardFocus = true;
- window->DC.ButtonRepeat = false;
+ window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
- window->DC.AllowKeyboardFocusStack.resize(0);
- window->DC.ButtonRepeatStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
- window->DC.ColumnsCurrent = 0;
- window->DC.ColumnsCount = 1;
- window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
- window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY;
+ window->DC.ColumnsSet = NULL;
window->DC.TreeDepth = 0;
window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
- window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect;
- window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active);
+ window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
+
+ if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
+ {
+ window->DC.ItemFlags = parent_window->DC.ItemFlags;
+ window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
+ }
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
- // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
- if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
- if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
- FocusWindow(window);
+ // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
+ if (want_focus)
+ FocusWindow(window);
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
+ // Collapse button
+ if (!(flags & ImGuiWindowFlags_NoCollapse))
+ {
+ RenderTriangle(window->Pos + style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
+ }
+
+ // Close button
if (p_open != NULL)
{
- const float pad = 2.0f;
- const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f;
- if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad))
+ const float PAD = 2.0f;
+ const float rad = (window->TitleBarHeight() - PAD*2.0f) * 0.5f;
+ if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-PAD - rad, PAD + rad), rad))
*p_open = false;
}
- const ImVec2 text_size = CalcTextSize(name, NULL, true);
- if (!(flags & ImGuiWindowFlags_NoCollapse))
- RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f);
-
- ImVec2 text_min = window->Pos;
- ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y);
- ImRect clip_rect;
- clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton()
+ // Title text (FIXME: refactor text alignment facilities along with RenderText helpers)
+ ImVec2 text_size = CalcTextSize(name, NULL, true);
+ ImRect text_r = title_bar_rect;
float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
- text_min.x += pad_left;
- text_max.x -= pad_right;
- clip_rect.Min = ImVec2(text_min.x, window->Pos.y);
- RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
+ text_r.Min.x += pad_left;
+ text_r.Max.x -= pad_right;
+ ImRect clip_rect = text_r;
+ clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
+ RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
}
// Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
window->WindowRectClipped = window->Rect();
- window->WindowRectClipped.Clip(window->ClipRect);
+ window->WindowRectClipped.ClipWith(window->ClipRect);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
@@ -4383,25 +4954,38 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
ImGui::LogToClipboard();
*/
+
+ // Inner rectangle
+ // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
+ // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
+ window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
+ window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
+ window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize;
+ window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
+ //window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
+
+ // After Begin() we fill the last item / hovered data using the title bar data. Make that a standard behavior (to allow usage of context menus on title bar only, etc.).
+ window->DC.LastItemId = window->MoveId;
+ window->DC.LastItemRect = title_bar_rect;
+ window->DC.LastItemRectHoveredRect = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false);
}
// Inner clipping rectangle
- // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
- // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
- const ImRect title_bar_rect = window->TitleBarRect();
- const float border_size = window->BorderSize;
- ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
- clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
- clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size);
- clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f)));
- clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size);
+ // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
+ const float border_size = window->WindowBorderSize;
+ ImRect clip_rect;
+ clip_rect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size)));
+ clip_rect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y);
+ clip_rect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - border_size)));
+ clip_rect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y);
PushClipRect(clip_rect.Min, clip_rect.Max, true);
- // Clear 'accessed' flag last thing
+ // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
- window->Accessed = false;
+ window->WriteAccessed = false;
+
window->BeginCount++;
- g.SetNextWindowSizeConstraint = false;
+ g.NextWindowData.SizeConstraintCond = 0;
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
@@ -4426,12 +5010,29 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
return !window->SkipItems;
}
+// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
+{
+ // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
+ if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
+ ImGui::SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
+
+ // Old API feature: override the window background alpha with a parameter.
+ if (bg_alpha_override >= 0.0f)
+ ImGui::SetNextWindowBgAlpha(bg_alpha_override);
+
+ return ImGui::Begin(name, p_open, flags);
+}
+#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
- Columns(1, "#CloseColumns");
+ if (window->DC.ColumnsSet != NULL)
+ EndColumns();
PopClipRect(); // inner window clip rectangle
// Stop logging
@@ -4452,9 +5053,12 @@ void ImGui::End()
// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
-static void Scrollbar(ImGuiWindow* window, bool horizontal)
+void ImGui::Scrollbar(ImGuiLayoutType direction)
{
ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ const bool horizontal = (direction == ImGuiLayoutType_Horizontal);
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
@@ -4462,38 +5066,41 @@ static void Scrollbar(ImGuiWindow* window, bool horizontal)
bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
const ImRect window_rect = window->Rect();
- const float border_size = window->BorderSize;
+ const float border_size = window->WindowBorderSize;
ImRect bb = horizontal
? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size)
: ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size);
if (!horizontal)
bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
+ if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f)
+ return;
- float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding;
int window_rounding_corners;
if (horizontal)
- window_rounding_corners = ImGuiCorner_BottomLeft | (other_scrollbar ? 0 : ImGuiCorner_BottomRight);
+ window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
else
- window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImGuiCorner_TopRight : 0) | (other_scrollbar ? 0 : ImGuiCorner_BottomRight);
- window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners);
- bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
+ window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
+ window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners);
+ bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
- // V denote the main axis of the scrollbar
+ // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
- float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w;
+ float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w;
float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
- // The grabable box size generally represent the amount visible (vs the total scrollable amount)
+ // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
- const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v);
+ IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
+ const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f);
+ const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
// Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
bool held = false;
bool hovered = false;
const bool previously_held = (g.ActiveId == id);
- ImGui::ButtonBehavior(bb, id, &hovered, &held);
+ ButtonBehavior(bb, id, &hovered, &held);
float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
float scroll_ratio = ImSaturate(scroll_v / scroll_max);
@@ -4506,7 +5113,7 @@ static void Scrollbar(ImGuiWindow* window, bool horizontal)
// Click position in scrollbar normalized space (0.0f->1.0f)
const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
- ImGui::SetHoveredID(id);
+ SetHoveredID(id);
bool seek_absolute = false;
if (!previously_held)
@@ -4542,26 +5149,56 @@ static void Scrollbar(ImGuiWindow* window, bool horizontal)
}
// Render
- const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
+ const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
+ ImRect grab_rect;
if (horizontal)
- window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding);
+ grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y);
else
- window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding);
+ grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y));
+ window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
}
-// Moving window to front of display (which happens to be back of our sorted list)
+void ImGui::BringWindowToFront(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.Windows.back() == window)
+ return;
+ for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
+ if (g.Windows[i] == window)
+ {
+ g.Windows.erase(g.Windows.Data + i);
+ g.Windows.push_back(window);
+ break;
+ }
+}
+
+void ImGui::BringWindowToBack(ImGuiWindow* window)
+{
+ ImGuiContext& g = *GImGui;
+ if (g.Windows[0] == window)
+ return;
+ for (int i = 0; i < g.Windows.Size; i++)
+ if (g.Windows[i] == window)
+ {
+ memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
+ g.Windows[0] = window;
+ break;
+ }
+}
+
+// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
// Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing.
- g.FocusedWindow = window;
+ g.NavWindow = window;
// Passing NULL allow to disable keyboard focus
if (!window)
return;
- // And move its root window to the top of the pile
+ // Move the root window to the top of the pile
if (window->RootWindow)
window = window->RootWindow;
@@ -4571,15 +5208,19 @@ void ImGui::FocusWindow(ImGuiWindow* window)
ClearActiveID();
// Bring to front
- if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window)
- return;
- for (int i = 0; i < g.Windows.Size; i++)
- if (g.Windows[i] == window)
+ if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
+ BringWindowToFront(window);
+}
+
+void ImGui::FocusFrontMostActiveWindow(ImGuiWindow* ignore_window)
+{
+ ImGuiContext& g = *GImGui;
+ for (int i = g.Windows.Size - 1; i >= 0; i--)
+ if (g.Windows[i] != ignore_window && g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
{
- g.Windows.erase(g.Windows.begin() + i);
- break;
+ FocusWindow(g.Windows[i]);
+ return;
}
- g.Windows.push_back(window);
}
void ImGui::PushItemWidth(float item_width)
@@ -4589,12 +5230,12 @@ void ImGui::PushItemWidth(float item_width)
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
}
-static void PushMultiItemsWidths(int components, float w_full)
+void ImGui::PushMultiItemsWidths(int components, float w_full)
{
- ImGuiWindow* window = ImGui::GetCurrentWindow();
+ ImGuiWindow* window = GetCurrentWindow();
const ImGuiStyle& style = GImGui->Style;
if (w_full <= 0.0f)
- w_full = ImGui::CalcItemWidth();
+ w_full = CalcItemWidth();
const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
@@ -4630,7 +5271,7 @@ static ImFont* GetDefaultFont()
return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0];
}
-static void SetCurrentFont(ImFont* font)
+void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
@@ -4638,7 +5279,11 @@ static void SetCurrentFont(ImFont* font)
g.Font = font;
g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
- g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel;
+
+ ImFontAtlas* atlas = g.Font->ContainerAtlas;
+ g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
+ g.DrawListSharedData.Font = g.Font;
+ g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
@@ -4659,32 +5304,41 @@ void ImGui::PopFont()
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
-void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
+void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
- window->DC.AllowKeyboardFocus = allow_keyboard_focus;
- window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus);
+ if (enabled)
+ window->DC.ItemFlags |= option;
+ else
+ window->DC.ItemFlags &= ~option;
+ window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
+}
+
+void ImGui::PopItemFlag()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ window->DC.ItemFlagsStack.pop_back();
+ window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
+}
+
+void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
+{
+ PushItemFlag(ImGuiItemFlags_AllowKeyboardFocus, allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.AllowKeyboardFocusStack.pop_back();
- window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back();
+ PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.ButtonRepeat = repeat;
- window->DC.ButtonRepeatStack.push_back(repeat);
+ PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
- ImGuiWindow* window = GetCurrentWindow();
- window->DC.ButtonRepeatStack.pop_back();
- window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back();
+ PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
@@ -4701,6 +5355,17 @@ void ImGui::PopTextWrapPos()
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
+// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
+void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiColMod backup;
+ backup.Col = idx;
+ backup.BackupValue = g.Style.Colors[idx];
+ g.ColorModifiers.push_back(backup);
+ g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
+}
+
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
@@ -4727,28 +5392,38 @@ struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Offset;
- void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); }
+ void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
-static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] =
+static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) },
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },
- { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },
- { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
+ { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
+ { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
+ { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
+ { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
+ { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
+ { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
+ { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
+ { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_);
+ IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_Count_);
return &GStyleVarInfo[idx];
}
@@ -4757,8 +5432,9 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float)
{
- float* pvar = (float*)var_info->GetVarPtr();
- GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
+ ImGuiContext& g = *GImGui;
+ float* pvar = (float*)var_info->GetVarPtr(&g.Style);
+ g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
@@ -4770,8 +5446,9 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float2)
{
- ImVec2* pvar = (ImVec2*)var_info->GetVarPtr();
- GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
+ ImGuiContext& g = *GImGui;
+ ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
+ g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
@@ -4785,15 +5462,15 @@ void ImGui::PopStyleVar(int count)
{
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
- if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0];
- else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]);
- else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0];
+ if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr(&g.Style)) = backup.BackupFloat[0];
+ else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr(&g.Style)) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]);
+ else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr(&g.Style)) = backup.BackupInt[0];
g.StyleModifiers.pop_back();
count--;
}
}
-const char* ImGui::GetStyleColName(ImGuiCol idx)
+const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
@@ -4801,7 +5478,7 @@ const char* ImGui::GetStyleColName(ImGuiCol idx)
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
- case ImGuiCol_ChildWindowBg: return "ChildWindowBg";
+ case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
@@ -4809,14 +5486,13 @@ const char* ImGui::GetStyleColName(ImGuiCol idx)
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
- case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
+ case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
- case ImGuiCol_ComboBg: return "ComboBg";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
@@ -4826,9 +5502,9 @@ const char* ImGui::GetStyleColName(ImGuiCol idx)
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
- case ImGuiCol_Column: return "Column";
- case ImGuiCol_ColumnHovered: return "ColumnHovered";
- case ImGuiCol_ColumnActive: return "ColumnActive";
+ case ImGuiCol_Separator: return "Separator";
+ case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
+ case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
@@ -4841,39 +5517,85 @@ const char* ImGui::GetStyleColName(ImGuiCol idx)
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
+ case ImGuiCol_DragDropTarget: return "DragDropTarget";
}
IM_ASSERT(0);
return "Unknown";
}
-bool ImGui::IsWindowHovered()
+bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
- ImGuiContext& g = *GImGui;
- return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow);
+ if (window->RootWindow == potential_parent)
+ return true;
+ while (window != NULL)
+ {
+ if (window == potential_parent)
+ return true;
+ window = window->ParentWindow;
+ }
+ return false;
}
-bool ImGui::IsWindowFocused()
+bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
+ IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
- return g.FocusedWindow == g.CurrentWindow;
+
+ if (flags & ImGuiHoveredFlags_AnyWindow)
+ {
+ if (g.HoveredWindow == NULL)
+ return false;
+ }
+ else
+ {
+ switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
+ {
+ case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
+ if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
+ return false;
+ break;
+ case ImGuiHoveredFlags_RootWindow:
+ if (g.HoveredWindow != g.CurrentWindow->RootWindow)
+ return false;
+ break;
+ case ImGuiHoveredFlags_ChildWindows:
+ if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
+ return false;
+ break;
+ default:
+ if (g.HoveredWindow != g.CurrentWindow)
+ return false;
+ break;
+ }
+ }
+
+ if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
+ return false;
+ if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
+ if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
+ return false;
+ return true;
}
-bool ImGui::IsRootWindowFocused()
+bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
- return g.FocusedWindow == g.CurrentWindow->RootWindow;
-}
+ IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
-bool ImGui::IsRootWindowOrAnyChildFocused()
-{
- ImGuiContext& g = *GImGui;
- return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow;
-}
+ if (flags & ImGuiFocusedFlags_AnyWindow)
+ return g.NavWindow != NULL;
-bool ImGui::IsRootWindowOrAnyChildHovered()
-{
- ImGuiContext& g = *GImGui;
- return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow);
+ switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
+ {
+ case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
+ return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
+ case ImGuiFocusedFlags_RootWindow:
+ return g.NavWindow == g.CurrentWindow->RootWindow;
+ case ImGuiFocusedFlags_ChildWindows:
+ return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
+ default:
+ return g.NavWindow == g.CurrentWindow;
+ }
}
float ImGui::GetWindowWidth()
@@ -4895,36 +5617,43 @@ ImVec2 ImGui::GetWindowPos()
return window->Pos;
}
+static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
+{
+ window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
+ window->Scroll.x = new_scroll_x;
+ window->DC.CursorMaxPos.x -= window->Scroll.x;
+}
+
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
{
- window->DC.CursorMaxPos.y += window->Scroll.y;
+ window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
window->Scroll.y = new_scroll_y;
window->DC.CursorMaxPos.y -= window->Scroll.y;
}
-static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond)
+static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
- window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
- window->SetWindowPosCenterWanted = false;
+ window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
+ window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->PosFloat = pos;
- window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);
+ window->Pos = ImFloor(pos);
window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
}
-void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond)
+void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
-void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond)
+void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
@@ -4936,12 +5665,12 @@ ImVec2 ImGui::GetWindowSize()
return window->Size;
}
-static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond)
+static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
- window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
+ window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
@@ -4966,43 +5695,48 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond
}
}
-void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond)
+void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
-void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond)
+void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
- ImGuiWindow* window = FindWindowByName(name);
- if (window)
+ if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
-static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond)
+static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
- window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing);
+ window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
-void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond)
+void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
- return GImGui->CurrentWindow->Collapsed;
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->Collapsed;
}
-void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond)
+bool ImGui::IsWindowAppearing()
{
- ImGuiWindow* window = FindWindowByName(name);
- if (window)
+ ImGuiWindow* window = GetCurrentWindowRead();
+ return window->Appearing;
+}
+
+void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
+{
+ if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
@@ -5024,61 +5758,55 @@ void ImGui::SetWindowFocus(const char* name)
}
}
-void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond)
+void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowPosVal = pos;
- g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
+ g.NextWindowData.PosVal = pos;
+ g.NextWindowData.PosPivotVal = pivot;
+ g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
-void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond)
+void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX);
- g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always;
+ g.NextWindowData.SizeVal = size;
+ g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
-void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond)
+void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowSizeVal = size;
- g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always;
-}
-
-void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data)
-{
- ImGuiContext& g = *GImGui;
- g.SetNextWindowSizeConstraint = true;
- g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max);
- g.SetNextWindowSizeConstraintCallback = custom_callback;
- g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data;
+ g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
+ g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
+ g.NextWindowData.SizeCallback = custom_callback;
+ g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowContentSizeVal = size;
- g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
+ g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
+ g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
}
-void ImGui::SetNextWindowContentWidth(float width)
+void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f);
- g.SetNextWindowContentSizeCond = ImGuiSetCond_Always;
-}
-
-void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond)
-{
- ImGuiContext& g = *GImGui;
- g.SetNextWindowCollapsedVal = collapsed;
- g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always;
+ g.NextWindowData.CollapsedVal = collapsed;
+ g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
- g.SetNextWindowFocus = true;
+ g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
+}
+
+void ImGui::SetNextWindowBgAlpha(float alpha)
+{
+ ImGuiContext& g = *GImGui;
+ g.NextWindowData.BgAlphaVal = alpha;
+ g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
// In window space (not screen space!)
@@ -5086,8 +5814,8 @@ ImVec2 ImGui::GetContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImVec2 mx = window->ContentsRegionRect.Max;
- if (window->DC.ColumnsCount != 1)
- mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x;
+ if (window->DC.ColumnsSet)
+ mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x;
return mx;
}
@@ -5133,7 +5861,13 @@ float ImGui::GetTextLineHeightWithSpacing()
return g.FontSize + g.Style.ItemSpacing.y;
}
-float ImGui::GetItemsLineHeightWithSpacing()
+float ImGui::GetFrameHeight()
+{
+ ImGuiContext& g = *GImGui;
+ return g.FontSize + g.Style.FramePadding.y * 2.0f;
+}
+
+float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
@@ -5157,7 +5891,7 @@ float ImGui::GetFontSize()
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
- return GImGui->FontTexUvWhitePixel;
+ return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
@@ -5165,7 +5899,7 @@ void ImGui::SetWindowFontScale(float scale)
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
- g.FontSize = window->CalcFontSize();
+ g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
@@ -5240,14 +5974,12 @@ float ImGui::GetScrollY()
float ImGui::GetScrollMaxX()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x;
+ return GetScrollMaxX(GImGui->CurrentWindow);
}
float ImGui::GetScrollMaxY()
{
- ImGuiWindow* window = GetCurrentWindowRead();
- return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y;
+ return GetScrollMaxY(GImGui->CurrentWindow);
}
void ImGui::SetScrollX(float scroll_x)
@@ -5270,21 +6002,36 @@ void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
- if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y)
- window->ScrollTarget.y = 0.0f;
window->ScrollTargetCenterRatio.y = center_y_ratio;
+
+ // Minor hack to to make scrolling to top/bottom of window take account of WindowPadding, it looks more right to the user this way
+ if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y)
+ window->ScrollTarget.y = 0.0f;
+ else if (center_y_ratio >= 1.0f && window->ScrollTarget.y >= window->SizeContents.y - window->WindowPadding.y + GImGui->Style.ItemSpacing.y)
+ window->ScrollTarget.y = window->SizeContents.y;
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHere(float center_y_ratio)
{
ImGuiWindow* window = GetCurrentWindow();
- float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
- SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio);
+ float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
+ target_y += (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->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);
+}
+
+// FIXME-NAV: This function is a placeholder for the upcoming Navigation branch + Focusing features.
+// In the current branch this function will only set the scrolling, in the navigation branch it will also set your navigation cursor.
+// Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHere()" when applicable.
+void ImGui::SetItemDefaultFocus()
+{
+ if (IsWindowAppearing())
+ SetScrollHere();
}
void ImGui::SetKeyboardFocusHere(int offset)
{
+ IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiWindow* window = GetCurrentWindow();
window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
window->FocusIdxTabRequestNext = INT_MAX;
@@ -5379,6 +6126,7 @@ void ImGui::TextUnformatted(const char* text, const char* text_end)
if (text_end == NULL)
text_end = text + strlen(text); // FIXME-OPT
+ const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
const float wrap_pos_x = window->DC.TextWrapPos;
const bool wrap_enabled = wrap_pos_x >= 0.0f;
if (text_end - text > 2000 && !wrap_enabled)
@@ -5389,7 +6137,6 @@ void ImGui::TextUnformatted(const char* text, const char* text_end)
// We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
const char* line = text;
const float line_height = GetTextLineHeight();
- const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset);
const ImRect clip_rect = window->ClipRect;
ImVec2 text_size(0,0);
@@ -5423,7 +6170,7 @@ void ImGui::TextUnformatted(const char* text, const char* text_end)
while (line < text_end)
{
const char* line_end = strchr(line, '\n');
- if (IsClippedEx(line_rect, NULL, false))
+ if (IsClippedEx(line_rect, 0, false))
break;
const ImVec2 line_size = CalcTextSize(line, line_end, false);
@@ -5455,7 +6202,7 @@ void ImGui::TextUnformatted(const char* text, const char* text_end)
ImRect bb(text_pos, text_pos + text_size);
ItemSize(bb);
- ItemAdd(bb, NULL);
+ ItemAdd(bb, 0);
}
else
{
@@ -5463,10 +6210,9 @@ void ImGui::TextUnformatted(const char* text, const char* text_end)
const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
// Account of baseline offset
- ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size);
- if (!ItemAdd(bb, NULL))
+ if (!ItemAdd(bb, 0))
return;
// Render (we don't hide text after ## in this end-user function)
@@ -5474,16 +6220,15 @@ void ImGui::TextUnformatted(const char* text, const char* text_end)
}
}
-void ImGui::AlignFirstTextHeightToWidgets()
+void ImGui::AlignTextToFramePadding()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
- // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height.
ImGuiContext& g = *GImGui;
- ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y);
- SameLine(0, 0);
+ window->DC.CurrentLineHeight = ImMax(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y * 2);
+ window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
}
// Add a label+text combo aligned to other label+value widgets
@@ -5501,7 +6246,7 @@ void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
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, NULL))
+ if (!ItemAdd(total_bb, 0))
return;
// Render
@@ -5520,18 +6265,6 @@ void ImGui::LabelText(const char* label, const char* fmt, ...)
va_end(args);
}
-static inline bool IsWindowContentHoverable(ImGuiWindow* window)
-{
- // An active popup disable hovering on other windows (apart from its own children)
- ImGuiContext& g = *GImGui;
- if (ImGuiWindow* focused_window = g.FocusedWindow)
- if (ImGuiWindow* focused_root_window = focused_window->RootWindow)
- if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow)
- return false;
-
- return true;
-}
-
bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
@@ -5545,14 +6278,39 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
return false;
}
+ // Default behavior requires click+release on same spot
if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
flags |= ImGuiButtonFlags_PressedOnClickRelease;
+ ImGuiWindow* backup_hovered_window = g.HoveredWindow;
+ if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
+ g.HoveredWindow = window;
+
bool pressed = false;
- bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0);
+ bool hovered = ItemHoverable(bb, id);
+
+ // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
+ if ((flags & ImGuiButtonFlags_PressedOnDragDropHold) && g.DragDropActive && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
+ if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
+ {
+ hovered = true;
+ SetHoveredID(id);
+ if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy
+ {
+ pressed = true;
+ FocusWindow(window);
+ }
+ }
+
+ if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
+ g.HoveredWindow = backup_hovered_window;
+
+ // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
+ if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
+ hovered = false;
+
if (hovered)
{
- SetHoveredID(id);
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
// | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
@@ -5564,12 +6322,14 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
{
SetActiveID(id, window); // Hold on ID
FocusWindow(window);
- g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
}
if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
{
pressed = true;
- ClearActiveID();
+ if (flags & ImGuiButtonFlags_NoHoldingActiveID)
+ ClearActiveID();
+ else
+ SetActiveID(id, window); // Hold on ID
FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
@@ -5589,6 +6349,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
bool held = false;
if (g.ActiveId == id)
{
+ if (g.ActiveIdIsJustActivated)
+ g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
if (g.IO.MouseDown[0])
{
held = true;
@@ -5597,15 +6359,12 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
{
if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps
- pressed = true;
+ if (!g.DragDropActive)
+ pressed = true;
ClearActiveID();
}
}
- // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
- if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
- hovered = pressed = held = false;
-
if (out_hovered) *out_hovered = hovered;
if (out_held) *out_held = held;
@@ -5630,10 +6389,11 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags
const ImRect bb(pos, pos + size);
ItemSize(bb, style.FramePadding.y);
- if (!ItemAdd(bb, &id))
+ if (!ItemAdd(bb, id))
return false;
- if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;
+ if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
+ flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
@@ -5677,7 +6437,7 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb);
- if (!ItemAdd(bb, &id))
+ if (!ItemAdd(bb, id))
return false;
bool hovered, held;
@@ -5711,6 +6471,34 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
return pressed;
}
+// [Internal]
+bool ImGui::ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ if (window->SkipItems)
+ return false;
+
+ const ImGuiStyle& style = g.Style;
+
+ const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + padding.x * 2.0f, g.FontSize + padding.y * 2.0f));
+ ItemSize(bb, style.FramePadding.y);
+ if (!ItemAdd(bb, id))
+ return false;
+
+ bool hovered, held;
+ bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
+
+ const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
+#ifdef IMGUI_HAS_NAV
+ RenderNavHighlight(bb, id);
+#endif
+ RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
+ RenderTriangle(bb.Min + padding, dir, 1.0f);
+
+ return pressed;
+}
+
void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
{
ImGuiWindow* window = GetCurrentWindow();
@@ -5721,7 +6509,7 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2&
if (border_col.w > 0.0f)
bb.Max += ImVec2(2,2);
ItemSize(bb);
- if (!ItemAdd(bb, NULL))
+ if (!ItemAdd(bb, 0))
return;
if (border_col.w > 0.0f)
@@ -5758,7 +6546,7 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I
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))
+ if (!ItemAdd(bb, id))
return false;
bool hovered, held;
@@ -5780,7 +6568,7 @@ void ImGui::LogToTTY(int max_depth)
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
g.LogEnabled = true;
g.LogFile = stdout;
@@ -5795,7 +6583,7 @@ void ImGui::LogToFile(int max_depth, const char* filename)
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
if (!filename)
{
@@ -5822,7 +6610,7 @@ void ImGui::LogToClipboard(int max_depth)
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
- ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
g.LogEnabled = true;
g.LogFile = NULL;
@@ -5890,20 +6678,20 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
ImGuiStorage* storage = window->DC.StateStorage;
bool is_open;
- if (g.SetNextTreeNodeOpenCond != 0)
+ if (g.NextTreeNodeOpenCond != 0)
{
- if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always)
+ if (g.NextTreeNodeOpenCond & ImGuiCond_Always)
{
- is_open = g.SetNextTreeNodeOpenVal;
+ is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
{
- // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently.
+ // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
const int stored_value = storage->GetInt(id, -1);
if (stored_value == -1)
{
- is_open = g.SetNextTreeNodeOpenVal;
+ is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
@@ -5911,7 +6699,7 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
is_open = stored_value != 0;
}
}
- g.SetNextTreeNodeOpenCond = 0;
+ g.NextTreeNodeOpenCond = 0;
}
else
{
@@ -5935,14 +6723,14 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
- const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
+ const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
if (!label_end)
label_end = FindRenderedTextEnd(label);
const ImVec2 label_size = CalcTextSize(label, label_end, false);
// We vertically grow up to current line height up the typical widget height.
- const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it
+ const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
if (display_frame)
@@ -5957,10 +6745,10 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
- // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not)
+ // (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
- if (!ItemAdd(interact_bb, &id))
+ if (!ItemAdd(interact_bb, id))
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
@@ -5972,9 +6760,12 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
// - OpenOnDoubleClick .............. double-click anywhere to open
// - OpenOnArrow .................... single-click on arrow to open
// - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
- ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0);
+ ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0);
+ if (!(flags & ImGuiTreeNodeFlags_Leaf))
+ button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
+
bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf))
{
@@ -5983,31 +6774,33 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y));
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
toggled |= g.IO.MouseDoubleClicked[0];
+ if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
+ toggled = false;
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
}
}
- if (flags & ImGuiTreeNodeFlags_AllowOverlapMode)
+ if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
SetItemAllowOverlap();
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
- const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y);
+ const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, text_base_offset_y);
if (display_frame)
{
// Framed type
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
- RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f);
+ RenderTriangle(bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
if (g.LogEnabled)
{
// 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, bb.Max, label, label_end, &label_size);
- LogRenderedText(text_pos, log_suffix+1, log_suffix+3);
+ LogRenderedText(&text_pos, log_suffix+1, log_suffix+3);
}
else
{
@@ -6023,9 +6816,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
else if (!(flags & ImGuiTreeNodeFlags_Leaf))
- RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f);
+ RenderTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
if (g.LogEnabled)
- LogRenderedText(text_pos, ">");
+ LogRenderedText(&text_pos, ">");
RenderText(text_pos, label, label_end, false);
}
@@ -6055,14 +6848,16 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags
return false;
ImGuiID id = window->GetID(label);
- bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label);
+ bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label);
if (p_open)
{
// Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
ImGuiContext& g = *GImGui;
float button_sz = g.FontSize * 0.5f;
+ ImGuiItemHoveredDataBackup last_item_backup;
if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz))
*p_open = false;
+ last_item_backup.Restore();
}
return is_open;
@@ -6166,41 +6961,43 @@ float ImGui::GetTreeNodeToLabelSpacing()
return g.FontSize + (g.Style.FramePadding.x * 2.0f);
}
-void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond)
+void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
- g.SetNextTreeNodeOpenVal = is_open;
- g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always;
+ if (g.CurrentWindow->SkipItems)
+ return;
+ g.NextTreeNodeOpenVal = is_open;
+ g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::PushID(const char* str_id)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(ptr_id));
}
void ImGui::PushID(int int_id)
{
const void* ptr_id = (void*)(intptr_t)int_id;
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(ptr_id));
}
void ImGui::PopID()
{
- ImGuiWindow* window = GetCurrentWindow();
+ ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.pop_back();
}
@@ -6230,7 +7027,7 @@ void ImGui::Bullet()
const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, 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, NULL))
+ if (!ItemAdd(bb, 0))
{
SameLine(0, style.FramePadding.x*2);
return;
@@ -6258,7 +7055,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args)
const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding
ItemSize(bb);
- if (!ItemAdd(bb, NULL))
+ if (!ItemAdd(bb, 0))
return;
// Render
@@ -6346,16 +7143,16 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b
scalar_format = "%d";
int* v = (int*)data_ptr;
const int old_v = *v;
- int arg0 = *v;
- if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1)
+ int arg0i = *v;
+ if (op && sscanf(initial_value_buf, scalar_format, &arg0i) < 1)
return false;
// Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
- float arg1 = 0.0f;
- if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract)
- else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply
- else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide
- else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant
+ float arg1f = 0.0f;
+ if (op == '+') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i + arg1f); } // Add (use "+-" to subtract)
+ else if (op == '*') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i * arg1f); } // Multiply
+ else if (op == '/') { if (sscanf(buf, "%f", &arg1f) == 1 && arg1f != 0.0f) *v = (int)(arg0i / arg1f); }// Divide
+ else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign constant (read as integer so big values are not lossy)
return (old_v != *v);
}
else if (data_type == ImGuiDataType_Float)
@@ -6364,17 +7161,17 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b
scalar_format = "%f";
float* v = (float*)data_ptr;
const float old_v = *v;
- float arg0 = *v;
- if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1)
+ float arg0f = *v;
+ if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
return false;
- float arg1 = 0.0f;
- if (sscanf(buf, scalar_format, &arg1) < 1)
+ float arg1f = 0.0f;
+ if (sscanf(buf, scalar_format, &arg1f) < 1)
return false;
- if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract)
- else if (op == '*') { *v = arg0 * arg1; } // Multiply
- else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide
- else { *v = arg1; } // Assign constant
+ if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
+ else if (op == '*') { *v = arg0f * arg1f; } // Multiply
+ else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
+ else { *v = arg1f; } // Assign constant
return (old_v != *v);
}
@@ -6382,12 +7179,14 @@ static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_b
}
// Create text input in place of a slider (when CTRL+Clicking on slider)
+// FIXME: Logic is messy and confusing.
bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
// Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
+ // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id
SetActiveID(g.ScalarAsInputTextId, window);
SetHoveredID(0);
FocusableItemUnregister(window);
@@ -6395,18 +7194,12 @@ bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label
char buf[32];
DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
- if (g.ScalarAsInputTextId == 0)
+ if (g.ScalarAsInputTextId == 0) // First frame we started displaying the InputText widget
{
- // First frame
IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible)
g.ScalarAsInputTextId = g.ActiveId;
SetHoveredID(id);
}
- else if (g.ActiveId != g.ScalarAsInputTextId)
- {
- // Release
- g.ScalarAsInputTextId = 0;
- }
if (text_value_changed)
return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
return false;
@@ -6424,22 +7217,31 @@ int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
fmt++;
if (*fmt == '.')
{
- precision = atoi(fmt + 1);
+ fmt = ImAtoi(fmt + 1, &precision);
if (precision < 0 || precision > 10)
precision = default_precision;
}
+ if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
+ precision = -1;
break;
}
return precision;
}
+static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
+{
+ static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
+ return (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
+}
+
float ImGui::RoundScalar(float value, int decimal_precision)
{
// Round past decimal precision
// So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
// FIXME: Investigate better rounding methods
- static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
- float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
+ if (decimal_precision < 0)
+ return value;
+ const float min_step = GetMinimumStepAtDecimalPrecision(decimal_precision);
bool negative = value < 0.0f;
value = fabsf(value);
float remainder = fmodf(value, min_step);
@@ -6490,7 +7292,7 @@ bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v
const float grab_padding = 2.0f;
const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
float grab_sz;
- if (decimal_precision > 0)
+ if (decimal_precision != 0)
grab_sz = ImMin(style.GrabMinSize, slider_sz);
else
grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
@@ -6517,13 +7319,23 @@ bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v
bool value_changed = false;
if (g.ActiveId == id)
{
+ bool set_new_value = false;
+ float clicked_t = 0.0f;
if (g.IO.MouseDown[0])
{
const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
- float clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
+ clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
if (!is_horizontal)
clicked_t = 1.0f - clicked_t;
+ set_new_value = true;
+ }
+ else
+ {
+ ClearActiveID();
+ }
+ if (set_new_value)
+ {
float new_value;
if (is_non_linear)
{
@@ -6561,16 +7373,10 @@ bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v
value_changed = true;
}
}
- else
- {
- ClearActiveID();
- }
}
- // Calculate slider grab positioning
- float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
-
// Draw
+ float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
if (!is_horizontal)
grab_t = 1.0f - grab_t;
const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
@@ -6605,15 +7411,12 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c
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));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
- if (!ItemAdd(total_bb, &id))
+ if (!ItemAdd(total_bb, id))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
}
-
- const bool hovered = IsHovered(frame_bb, id);
- if (hovered)
- SetHoveredID(id);
+ const bool hovered = ItemHoverable(frame_bb, id);
if (!display_format)
display_format = "%.3f";
@@ -6621,12 +7424,11 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c
// Tabbing or CTRL-clicking on Slider turns it into an input box
bool start_text_input = false;
- const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
+ const bool tab_focus_requested = FocusableItemRegister(window, id);
if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]))
{
SetActiveID(id, window);
FocusWindow(window);
-
if (tab_focus_requested || g.IO.KeyCtrl)
{
start_text_input = true;
@@ -6636,9 +7438,8 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c
if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
- ItemSize(total_bb, style.FramePadding.y);
-
// Actual slider behavior + render grab
+ ItemSize(total_bb, style.FramePadding.y);
const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
@@ -6667,12 +7468,9 @@ bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float
const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(bb, style.FramePadding.y);
- if (!ItemAdd(frame_bb, &id))
+ if (!ItemAdd(frame_bb, id))
return false;
-
- const bool hovered = IsHovered(frame_bb, id);
- if (hovered)
- SetHoveredID(id);
+ const bool hovered = ItemHoverable(frame_bb, id);
if (!display_format)
display_format = "%.3f";
@@ -6834,34 +7632,42 @@ bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_s
g.DragLastMouseDelta = ImVec2(0.f, 0.f);
}
+ if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
+ v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
+
float v_cur = g.DragCurrentValue;
const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
- if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f)
+ float adjust_delta = 0.0f;
+ if (IsMousePosValid())
{
- float speed = v_speed;
- if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
- speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
- if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
- speed = speed * g.DragSpeedScaleFast;
- if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
- speed = speed * g.DragSpeedScaleSlow;
+ //if (g.ActiveIdSource == ImGuiInputSource_Mouse)
+ {
+ adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x;
+ if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
+ adjust_delta *= g.DragSpeedScaleFast;
+ if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
+ adjust_delta *= g.DragSpeedScaleSlow;
+ }
+ g.DragLastMouseDelta.x = mouse_drag_delta.x;
+ }
+ adjust_delta *= v_speed;
- float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed;
+ if (fabsf(adjust_delta) > 0.0f)
+ {
if (fabsf(power - 1.0f) > 0.001f)
{
// Logarithmic curve on both side of 0.0
float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
- float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign);
+ float v1 = powf(v0_abs, 1.0f / power) + (adjust_delta * v0_sign);
float v1_abs = v1 >= 0.0f ? v1 : -v1;
float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
}
else
{
- v_cur += delta;
+ v_cur += adjust_delta;
}
- g.DragLastMouseDelta.x = mouse_drag_delta.x;
// Clamp
if (v_min < v_max)
@@ -6903,15 +7709,12 @@ bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, f
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));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
- if (!ItemAdd(total_bb, &id))
+ if (!ItemAdd(total_bb, id))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
}
-
- const bool hovered = IsHovered(frame_bb, id);
- if (hovered)
- SetHoveredID(id);
+ const bool hovered = ItemHoverable(frame_bb, id);
if (!display_format)
display_format = "%.3f";
@@ -6919,12 +7722,11 @@ bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, f
// Tabbing or CTRL-clicking on Drag turns it into an input box
bool start_text_input = false;
- const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id);
- if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0])))
+ const bool tab_focus_requested = FocusableItemRegister(window, id);
+ if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])))
{
SetActiveID(id, window);
FocusWindow(window);
-
if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0])
{
start_text_input = true;
@@ -7113,8 +7915,9 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge
const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
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));
ItemSize(total_bb, style.FramePadding.y);
- if (!ItemAdd(total_bb, NULL))
+ if (!ItemAdd(total_bb, 0))
return;
+ const bool hovered = ItemHoverable(inner_bb, 0);
// Determine scale from values if not specified
if (scale_min == FLT_MAX || scale_max == FLT_MAX)
@@ -7142,7 +7945,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge
// Tooltip on hover
int v_hovered = -1;
- if (IsHovered(inner_bb, 0))
+ if (hovered)
{
const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
const int v_idx = (int)(t * item_count);
@@ -7161,7 +7964,8 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge
float v0 = values_getter(data, (0 + values_offset) % values_count);
float t0 = 0.0f;
- ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
+ ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle
+ float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min / (scale_max - scale_min)) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
@@ -7176,7 +7980,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge
// NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
- ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f));
+ ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
if (plot_type == ImGuiPlotType_Lines)
{
window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
@@ -7251,15 +8055,15 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over
ImVec2 pos = window->DC.CursorPos;
ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
ItemSize(bb, style.FramePadding.y);
- if (!ItemAdd(bb, NULL))
+ if (!ItemAdd(bb, 0))
return;
// Render
fraction = ImSaturate(fraction);
RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
- bb.Reduce(ImVec2(window->BorderSize, window->BorderSize));
+ bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
- RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding);
+ RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
// Default displaying the fraction as percentage string, but user can override it
char overlay_buf[32];
@@ -7285,7 +8089,7 @@ bool ImGui::Checkbox(const char* label, bool* v)
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
- const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2));
+ const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); // We want a square shape to we use Y twice
ItemSize(check_bb, style.FramePadding.y);
ImRect total_bb = check_bb;
@@ -7298,7 +8102,7 @@ bool ImGui::Checkbox(const char* label, bool* v)
total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
}
- if (!ItemAdd(total_bb, &id))
+ if (!ItemAdd(total_bb, id))
return false;
bool hovered, held;
@@ -7311,13 +8115,13 @@ bool ImGui::Checkbox(const char* label, bool* v)
{
const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
- window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding);
+ RenderCheckMark(check_bb.Min + ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad*2.0f);
}
if (g.LogEnabled)
- LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]");
+ LogRenderedText(&text_bb.Min, *v ? "[x]" : "[ ]");
if (label_size.x > 0.0f)
- RenderText(text_bb.GetTL(), label);
+ RenderText(text_bb.Min, label);
return pressed;
}
@@ -7361,7 +8165,7 @@ bool ImGui::RadioButton(const char* label, bool active)
total_bb.Add(text_bb);
}
- if (!ItemAdd(total_bb, &id))
+ if (!ItemAdd(total_bb, id))
return false;
ImVec2 center = check_bb.GetCenter();
@@ -7380,16 +8184,16 @@ bool ImGui::RadioButton(const char* label, bool active)
window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16);
}
- if (window->Flags & ImGuiWindowFlags_ShowBorders)
+ if (style.FrameBorderSize > 0.0f)
{
- window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16);
- window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16);
+ 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);
}
if (g.LogEnabled)
- LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )");
+ LogRenderedText(&text_bb.Min, active ? "(x)" : "( )");
if (label_size.x > 0.0f)
- RenderText(text_bb.GetTL(), label);
+ RenderText(text_bb.Min, label);
return pressed;
}
@@ -7675,6 +8479,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
+ const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn
BeginGroup();
@@ -7699,14 +8504,17 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
else
{
ItemSize(total_bb, style.FramePadding.y);
- if (!ItemAdd(total_bb, &id))
+ if (!ItemAdd(total_bb, id))
return false;
}
+ const bool hovered = ItemHoverable(frame_bb, id);
+ if (hovered)
+ g.MouseCursor = ImGuiMouseCursor_TextInput;
// Password pushes a temporary font with only a fallback glyph
if (is_password)
{
- const ImFont::Glyph* glyph = g.Font->FindGlyph('*');
+ const ImFontGlyph* glyph = g.Font->FindGlyph('*');
ImFont* password_font = &g.InputTextPasswordFont;
password_font->FontSize = g.Font->FontSize;
password_font->Scale = g.Font->Scale;
@@ -7715,27 +8523,23 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
password_font->Descent = g.Font->Descent;
password_font->ContainerAtlas = g.Font->ContainerAtlas;
password_font->FallbackGlyph = glyph;
- password_font->FallbackXAdvance = glyph->XAdvance;
- IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty());
+ password_font->FallbackAdvanceX = glyph->AdvanceX;
+ IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
PushFont(password_font);
}
// NB: we are only allowed to access 'edit_state' if we are the active widget.
ImGuiTextEditState& edit_state = g.InputTextState;
- const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
+ const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
- const bool hovered = IsHovered(frame_bb, id);
- if (hovered)
- {
- SetHoveredID(id);
- g.MouseCursor = ImGuiMouseCursor_TextInput;
- }
const bool user_clicked = hovered && io.MouseClicked[0];
const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
+ bool clear_active_id = false;
+
bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0;
if (focus_requested || user_clicked || user_scrolled)
{
@@ -7781,8 +8585,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
else if (io.MouseClicked[0])
{
// Release focus when we click outside
- if (g.ActiveId == id)
- ClearActiveID();
+ clear_active_id = true;
}
bool value_changed = false;
@@ -7805,12 +8608,13 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
// Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
// Down the line we should have a cleaner library-wide concept of Selected vs Active.
g.ActiveIdAllowOverlap = !io.MouseDown[0];
+ g.WantTextInputNextFrame = 1;
// Edit in progress
const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
- const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
+ const bool osx_double_click_selects_words = io.OptMacOSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0]))
{
edit_state.SelectAll();
@@ -7824,8 +8628,11 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
}
else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
{
- stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
- edit_state.CursorAnimReset();
+ if (hovered)
+ {
+ stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
+ edit_state.CursorAnimReset();
+ }
}
else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
{
@@ -7855,13 +8662,22 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
// Consume characters
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
}
+ }
- // Handle various key-presses
- bool cancel_edit = false;
+ bool cancel_edit = false;
+ if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
+ {
+ // Handle key-presses
const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
- const bool is_shortcut_key_only = (io.OSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
- const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
- const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
+ const bool is_shortcut_key_only = (io.OptMacOSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
+ const bool is_wordmove_key_down = io.OptMacOSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
+ const bool is_startend_key_down = io.OptMacOSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
+ const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper;
+ const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
+
+ const bool is_cut = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection());
+ const bool is_copy = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection());
+ const bool is_paste = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable;
if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
@@ -7875,7 +8691,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
if (!edit_state.HasSelection())
{
if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
- else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
+ else if (io.OptMacOSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
}
edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
}
@@ -7884,8 +8700,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
{
- ClearActiveID();
- enter_pressed = true;
+ enter_pressed = clear_active_id = true;
}
else if (is_editable)
{
@@ -7900,17 +8715,13 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
if (InputTextFilterCharacter(&c, flags, callback, user_data))
edit_state.OnKeyPressed((int)c);
}
- else if (IsKeyPressedMap(ImGuiKey_Escape)) { ClearActiveID(); cancel_edit = true; }
- else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
- else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
- else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
- else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection()))
+ else if (IsKeyPressedMap(ImGuiKey_Escape)) { clear_active_id = cancel_edit = true; }
+ else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
+ else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
+ else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
+ else if (is_cut || is_copy)
{
// Cut, Copy
- const bool cut = IsKeyPressedMap(ImGuiKey_X);
- if (cut && !edit_state.HasSelection())
- edit_state.SelectAll();
-
if (io.SetClipboardTextFn)
{
const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
@@ -7920,13 +8731,15 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
SetClipboardText(edit_state.TempTextBuffer.Data);
}
- if (cut)
+ if (is_cut)
{
+ if (!edit_state.HasSelection())
+ edit_state.SelectAll();
edit_state.CursorFollow = true;
stb_textedit_cut(&edit_state, &edit_state.StbState);
}
}
- else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable)
+ else if (is_paste)
{
// Paste
if (const char* clipboard = GetClipboardText())
@@ -7954,7 +8767,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
ImGui::MemFree(clipboard_filtered);
}
}
+ }
+ if (g.ActiveId == id)
+ {
if (cancel_edit)
{
// Restore initial value
@@ -7964,7 +8780,11 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
value_changed = true;
}
}
- else
+
+ // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
+ // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage.
+ bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
+ if (apply_edit_back_to_user_buffer)
{
// Apply new value immediately - copy modified buffer back
// Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
@@ -8052,6 +8872,10 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
}
}
+ // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
+ if (clear_active_id && g.ActiveId == id)
+ ClearActiveID();
+
// Render
// Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on.
const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
@@ -8114,7 +8938,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
select_start_offset.y = searches_result_line_number[1] * g.FontSize;
}
- // Calculate text height
+ // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
if (is_multiline)
text_size = ImVec2(size.x, line_count * g.FontSize);
}
@@ -8177,7 +9001,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines
ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
- rect.Clip(clip_rect);
+ rect.ClipWith(clip_rect);
if (rect.Overlaps(clip_rect))
draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
}
@@ -8189,7 +9013,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
// Draw blinking cursor
- bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
+ bool cursor_is_visible = (!g.IO.OptCursorBlink) || (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll;
ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f);
if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
@@ -8220,7 +9044,7 @@ bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2
// Log as text
if (g.LogEnabled && !is_password)
- LogRenderedText(render_pos, buf_display, NULL);
+ LogRenderedText(&render_pos, buf_display, NULL);
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
@@ -8255,7 +9079,7 @@ bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data
BeginGroup();
PushID(label);
- const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f;
+ const ImVec2 button_sz = ImVec2(GetFrameHeight(), GetFrameHeight());
if (step_ptr)
PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
@@ -8337,7 +9161,6 @@ bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal
}
PopID();
- window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
@@ -8380,7 +9203,6 @@ bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextF
}
PopID();
- window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
@@ -8402,6 +9224,157 @@ bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_fla
return InputIntN(label, v, 4, extra_flags);
}
+static float CalcMaxPopupHeightFromItemCount(int items_count)
+{
+ ImGuiContext& g = *GImGui;
+ if (items_count <= 0)
+ return FLT_MAX;
+ return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
+}
+
+bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
+{
+ // Always consume the SetNextWindowSizeConstraint() call in our early return paths
+ ImGuiContext& g = *GImGui;
+ ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond;
+ g.NextWindowData.SizeConstraintCond = 0;
+
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return false;
+
+ 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 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))
+ return false;
+
+ bool hovered, held;
+ bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
+ bool popup_open = IsPopupOpen(id);
+
+ const float arrow_size = GetFrameHeight();
+ const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
+ RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
+ RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
+ RenderTriangle(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down);
+ if (preview_value != NULL)
+ RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, 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);
+
+ if (pressed && !popup_open)
+ {
+ OpenPopupEx(id);
+ popup_open = true;
+ }
+
+ if (!popup_open)
+ return false;
+
+ if (backup_next_window_size_constraint)
+ {
+ g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint;
+ g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
+ }
+ else
+ {
+ if ((flags & ImGuiComboFlags_HeightMask_) == 0)
+ flags |= ImGuiComboFlags_HeightRegular;
+ IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
+ int popup_max_height_in_items = -1;
+ if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
+ else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
+ else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
+ SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
+ }
+
+ char name[16];
+ ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
+
+ // Peak into expected window size so we can position it
+ if (ImGuiWindow* popup_window = FindWindowByName(name))
+ if (popup_window->WasActive)
+ {
+ ImVec2 size_contents = CalcSizeContents(popup_window);
+ ImVec2 size_expected = CalcSizeAfterConstraint(popup_window, CalcSizeAutoFit(popup_window, size_contents));
+ if (flags & ImGuiComboFlags_PopupAlignLeft)
+ popup_window->AutoPosLastDirection = ImGuiDir_Left;
+ ImVec2 pos = FindBestWindowPosForPopup(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
+ SetNextWindowPos(pos);
+ }
+
+ ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
+ if (!Begin(name, NULL, window_flags))
+ {
+ EndPopup();
+ IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
+ return false;
+ }
+
+ // Horizontally align ourselves with the framed text
+ if (style.FramePadding.x != style.WindowPadding.x)
+ Indent(style.FramePadding.x - style.WindowPadding.x);
+
+ return true;
+}
+
+void ImGui::EndCombo()
+{
+ const ImGuiStyle& style = GImGui->Style;
+ if (style.FramePadding.x != style.WindowPadding.x)
+ Unindent(style.FramePadding.x - style.WindowPadding.x);
+ EndPopup();
+}
+
+// Old API, prefer using BeginCombo() nowadays if you can.
+bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)
+{
+ ImGuiContext& g = *GImGui;
+
+ const char* preview_text = NULL;
+ if (*current_item >= 0 && *current_item < items_count)
+ items_getter(data, *current_item, &preview_text);
+
+ // The old Combo() API exposed "popup_max_height_in_items", however the new more general BeginCombo() API doesn't, so we emulate it here.
+ if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond)
+ {
+ float popup_max_height = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
+ SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, popup_max_height));
+ }
+
+ if (!BeginCombo(label, preview_text, 0))
+ return false;
+
+ // Display items
+ // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)
+ bool value_changed = false;
+ for (int i = 0; i < items_count; i++)
+ {
+ PushID((void*)(intptr_t)i);
+ const bool item_selected = (i == *current_item);
+ const char* item_text;
+ if (!items_getter(data, i, &item_text))
+ item_text = "*Unknown item*";
+ if (Selectable(item_text, item_selected))
+ {
+ value_changed = true;
+ *current_item = i;
+ }
+ if (item_selected)
+ SetItemDefaultFocus();
+ PopID();
+ }
+
+ EndCombo();
+ return value_changed;
+}
+
static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
{
const char* const* items = (const char* const*)data;
@@ -8431,7 +9404,7 @@ static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
}
// Combo box helper allowing to pass an array of strings.
-bool ImGui::Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items)
+bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
{
const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
return value_changed;
@@ -8451,114 +9424,6 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa
return value_changed;
}
-// Combo box function.
-bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
-{
- ImGuiWindow* window = GetCurrentWindow();
- if (window->SkipItems)
- return false;
-
- 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 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))
- return false;
-
- const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f);
- const bool hovered = IsHovered(frame_bb, id);
- bool popup_open = IsPopupOpen(id);
- bool popup_opened_now = false;
-
- const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
- RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
- RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING
- RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true);
-
- if (*current_item >= 0 && *current_item < items_count)
- {
- const char* item_text;
- if (items_getter(data, *current_item, &item_text))
- RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, 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);
-
- if (hovered)
- {
- SetHoveredID(id);
- if (g.IO.MouseClicked[0])
- {
- ClearActiveID();
- if (IsPopupOpen(id))
- {
- ClosePopup(id);
- }
- else
- {
- FocusWindow(window);
- OpenPopup(label);
- popup_open = popup_opened_now = true;
- }
- }
- }
-
- bool value_changed = false;
- if (IsPopupOpen(id))
- {
- // Size default to hold ~7 items
- if (height_in_items < 0)
- height_in_items = 7;
-
- float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3);
- float popup_y1 = frame_bb.Max.y;
- float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y);
- if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y))
- {
- // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement)
- popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y);
- popup_y2 = frame_bb.Min.y;
- }
- ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2));
- SetNextWindowPos(popup_rect.Min);
- SetNextWindowSize(popup_rect.GetSize());
- PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
-
- const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0);
- if (BeginPopupEx(label, flags))
- {
- // Display items
- Spacing();
- for (int i = 0; i < items_count; i++)
- {
- PushID((void*)(intptr_t)i);
- const bool item_selected = (i == *current_item);
- const char* item_text;
- if (!items_getter(data, i, &item_text))
- item_text = "*Unknown item*";
- if (Selectable(item_text, item_selected))
- {
- ClearActiveID();
- value_changed = true;
- *current_item = i;
- }
- if (item_selected && popup_opened_now)
- SetScrollHere();
- PopID();
- }
- EndPopup();
- }
- PopStyleVar();
- }
- return value_changed;
-}
-
// Tip: pass an empty label (e.g. "##dummy") 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.
bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
@@ -8570,7 +9435,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
- if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
+ if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped.
PopClipRect();
ImGuiID id = window->GetID(label);
@@ -8599,16 +9464,16 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
bb_with_spacing.Min.y -= spacing_U;
bb_with_spacing.Max.x += spacing_R;
bb_with_spacing.Max.y += spacing_D;
- if (!ItemAdd(bb_with_spacing, &id))
+ if (!ItemAdd(bb_with_spacing, id))
{
- if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
+ if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
PushColumnClipRect();
return false;
}
ImGuiButtonFlags button_flags = 0;
- if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick;
- if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease;
+ if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_NoHoldingActiveID;
+ if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnRelease;
if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
bool hovered, held;
@@ -8623,7 +9488,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
}
- if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1)
+ if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
{
PushColumnClipRect();
bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
@@ -8634,7 +9499,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl
if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
// Automatically close popups
- if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
+ if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
CloseCurrentPopup();
return pressed;
}
@@ -8694,7 +9559,7 @@ bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_item
void ImGui::ListBoxFooter()
{
- ImGuiWindow* parent_window = GetParentWindow();
+ ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow;
const ImRect bb = parent_window->DC.LastItemRect;
const ImGuiStyle& style = GetStyle();
@@ -8708,7 +9573,7 @@ void ImGui::ListBoxFooter()
EndGroup();
}
-bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items)
+bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
{
const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
return value_changed;
@@ -8721,7 +9586,7 @@ bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(v
// Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
bool value_changed = false;
- ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing());
+ ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
{
@@ -8749,23 +9614,38 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, boo
return false;
ImGuiContext& g = *GImGui;
+ ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImVec2 label_size = CalcTextSize(label, NULL, true);
- ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
- float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
- float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
- bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f));
- if (shortcut_size.x > 0.0f)
+ ImGuiSelectableFlags flags = ImGuiSelectableFlags_MenuItem | (enabled ? 0 : ImGuiSelectableFlags_Disabled);
+ bool pressed;
+ if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
- PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
- RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
- PopStyleColor();
+ // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
+ // Note that in this situation we render neither the shortcut neither the selected tick mark
+ float w = label_size.x;
+ window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
+ PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
+ pressed = Selectable(label, false, flags, ImVec2(w, 0.0f));
+ PopStyleVar();
+ window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
+ }
+ else
+ {
+ ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
+ float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
+ float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
+ pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f));
+ if (shortcut_size.x > 0.0f)
+ {
+ PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
+ RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
+ PopStyleColor();
+ }
+ if (selected)
+ RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f);
}
-
- if (selected)
- RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled));
-
return pressed;
}
@@ -8816,12 +9696,18 @@ bool ImGui::BeginMenuBar()
IM_ASSERT(!window->DC.MenuBarAppending);
BeginGroup(); // Save position
PushID("##menubar");
- ImRect rect = window->MenuBarRect();
- PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false);
- window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y);
+
+ // We don't clip with regular window clipping rectangle as it is already set to the area below. However we clip with window full rect.
+ // We remove 1 worth of rounding to Max.x to that text in long menus don't tend to display over the lower-right rounded area, which looks particularly glitchy.
+ ImRect bar_rect = window->MenuBarRect();
+ ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f));
+ clip_rect.ClipWith(window->WindowRectClipped);
+ PushClipRect(clip_rect.Min, clip_rect.Max, false);
+
+ window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffsetX, bar_rect.Min.y);// + g.Style.FramePadding.y);
window->DC.LayoutType = ImGuiLayoutType_Horizontal;
window->DC.MenuBarAppending = true;
- AlignFirstTextHeightToWidgets();
+ AlignTextToFramePadding();
return true;
}
@@ -8853,43 +9739,47 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
const ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
- ImGuiWindow* backed_focused_window = g.FocusedWindow;
bool pressed;
bool menu_is_open = IsPopupOpen(id);
- bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus"));
+ bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].OpenParentId == window->IDStack.back());
+ ImGuiWindow* backed_nav_window = g.NavWindow;
if (menuset_is_open)
- g.FocusedWindow = window;
+ 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 (using FindBestPopupWindowPos).
ImVec2 popup_pos, pos = window->DC.CursorPos;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
+ // Menu inside an horizontal menu bar
+ // Selectable extend their highlight by half ItemSpacing in each direction.
+ // For ChildMenu, the popup position will be overwritten by the call to FindBestPopupWindowPos() in Begin()
popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
float w = label_size.x;
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
PopStyleVar();
- SameLine();
- window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
+ window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
+ // Menu inside a menu
popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
- RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false);
+ RenderTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right);
if (!enabled) PopStyleColor();
}
- bool hovered = enabled && IsHovered(window->DC.LastItemRect, id);
+ const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id);
if (menuset_is_open)
- g.FocusedWindow = backed_focused_window;
+ g.NavWindow = backed_nav_window;
bool want_open = false, want_close = false;
- if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
+ if (window->DC.LayoutType != ImGuiLayoutType_Horizontal) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
{
// Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
bool moving_within_opened_triangle = false;
@@ -8905,7 +9795,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
- moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc);
+ moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
//window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug
}
}
@@ -8913,13 +9803,20 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
}
- else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close
+ else
{
- want_close = true;
- want_open = menu_is_open = false;
+ // Menu bar
+ if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
+ {
+ want_close = true;
+ want_open = menu_is_open = false;
+ }
+ else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
+ {
+ want_open = true;
+ }
}
- else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others
- want_open = true;
+
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))
@@ -8938,9 +9835,9 @@ bool ImGui::BeginMenu(const char* label, bool enabled)
if (menu_is_open)
{
- SetNextWindowPos(popup_pos, ImGuiSetCond_Always);
- ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
- menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
+ SetNextWindowPos(popup_pos, ImGuiCond_Always);
+ ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
+ menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
}
return menu_is_open;
@@ -8951,50 +9848,260 @@ void ImGui::EndMenu()
EndPopup();
}
+// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
+void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+
+ int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
+ BeginTooltipEx(0, true);
+
+ const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
+ if (text_end > text)
+ {
+ TextUnformatted(text, text_end);
+ Separator();
+ }
+
+ ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
+ ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
+ SameLine();
+ if (flags & ImGuiColorEditFlags_NoAlpha)
+ Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
+ else
+ Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
+ EndTooltip();
+}
+
+static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b)
+{
+ float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
+ int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
+ int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
+ int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
+ return IM_COL32(r, g, b, 0xFF);
+}
+
+// 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.
+// I 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.
+void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
+ {
+ ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col));
+ ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col));
+ window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags);
+
+ int yi = 0;
+ for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
+ {
+ float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
+ if (y2 <= y1)
+ continue;
+ for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
+ {
+ float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
+ if (x2 <= x1)
+ continue;
+ int rounding_corners_flags_cell = 0;
+ if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; }
+ if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; }
+ rounding_corners_flags_cell &= rounding_corners_flags;
+ window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
+ }
+ }
+ }
+ else
+ {
+ window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
+ }
+}
+
+void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ if ((flags & ImGuiColorEditFlags__InputsMask) == 0)
+ flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask;
+ if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
+ flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
+ if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
+ flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
+ IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected
+ IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected
+ IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected
+ g.ColorEditOptions = flags;
+}
+
// A little colored square. Return true when clicked.
// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
-bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border)
+// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
+bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
- const ImGuiStyle& style = g.Style;
- const ImGuiID id = window->GetID("#colorbutton");
- const float square_size = g.FontSize;
- const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2)));
- ItemSize(bb, small_height ? 0.0f : style.FramePadding.y);
- if (!ItemAdd(bb, &id))
+ const ImGuiID id = window->GetID(desc_id);
+ float default_size = GetFrameHeight();
+ if (size.x == 0.0f)
+ size.x = default_size;
+ if (size.y == 0.0f)
+ size.y = default_size;
+ const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
+ ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
+ if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
- RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding);
- if (hovered)
- SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.z));
+ if (flags & ImGuiColorEditFlags_NoAlpha)
+ flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
+
+ ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f);
+ float grid_step = ImMin(size.x, size.y) / 2.99f;
+ float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
+ ImRect bb_inner = bb;
+ float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
+ bb_inner.Expand(off);
+ if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f)
+ {
+ float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f);
+ RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col), 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_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft);
+ }
+ else
+ {
+ // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
+ ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha;
+ if (col_source.w < 1.0f)
+ RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
+ else
+ window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
+ }
+ if (g.Style.FrameBorderSize > 0.0f)
+ RenderFrameBorder(bb.Min, bb.Max, rounding);
+ else
+ window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
+
+ // Drag and Drop Source
+ if (g.ActiveId == id && BeginDragDropSource()) // NB: The ActiveId test is merely an optional micro-optimization
+ {
+ if (flags & ImGuiColorEditFlags_NoAlpha)
+ SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col, sizeof(float) * 3, ImGuiCond_Once);
+ else
+ SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once);
+ ColorButton(desc_id, col, flags);
+ SameLine();
+ TextUnformatted("Color");
+ EndDragDropSource();
+ hovered = false;
+ }
+
+ // Tooltip
+ if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)
+ ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
return pressed;
}
-bool ImGui::ColorEdit3(const char* label, float col[3])
+bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
- float col4[4];
- col4[0] = col[0];
- col4[1] = col[1];
- col4[2] = col[2];
- col4[3] = 1.0f;
- const bool value_changed = ColorEdit4(label, col4, false);
- col[0] = col4[0];
- col[1] = col4[1];
- col[2] = col4[2];
- return value_changed;
+ return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
}
-// Edit colors components (each component in 0.0f..1.0f range
-// Use CTRL-Click to input value and TAB to go to next item.
-bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha)
+void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
+{
+ bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask);
+ bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
+ if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
+ return;
+ ImGuiContext& g = *GImGui;
+ ImGuiColorEditFlags opts = g.ColorEditOptions;
+ if (allow_opt_inputs)
+ {
+ if (RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB;
+ if (RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV;
+ if (RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX;
+ }
+ if (allow_opt_datatype)
+ {
+ if (allow_opt_inputs) Separator();
+ if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
+ if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
+ }
+
+ if (allow_opt_inputs || allow_opt_datatype)
+ Separator();
+ if (Button("Copy as..", ImVec2(-1,0)))
+ OpenPopup("Copy");
+ if (BeginPopup("Copy"))
+ {
+ int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
+ char buf[64];
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
+ if (Selectable(buf))
+ SetClipboardText(buf);
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
+ if (Selectable(buf))
+ SetClipboardText(buf);
+ if (flags & ImGuiColorEditFlags_NoAlpha)
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb);
+ else
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca);
+ if (Selectable(buf))
+ SetClipboardText(buf);
+ EndPopup();
+ }
+
+ g.ColorEditOptions = opts;
+ EndPopup();
+}
+
+static void ColorPickerOptionsPopup(ImGuiColorEditFlags flags, const float* ref_col)
+{
+ bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
+ bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
+ if ((!allow_opt_picker && !allow_opt_alpha_bar) || !ImGui::BeginPopup("context"))
+ return;
+ ImGuiContext& g = *GImGui;
+ if (allow_opt_picker)
+ {
+ ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
+ ImGui::PushItemWidth(picker_size.x);
+ for (int picker_type = 0; picker_type < 2; picker_type++)
+ {
+ // Draw small/thumbnail version of each picker type (over an invisible button for selection)
+ if (picker_type > 0) ImGui::Separator();
+ ImGui::PushID(picker_type);
+ 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 = ImGui::GetCursorScreenPos();
+ if (ImGui::Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
+ g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
+ ImGui::SetCursorScreenPos(backup_pos);
+ ImVec4 dummy_ref_col;
+ memcpy(&dummy_ref_col.x, ref_col, sizeof(float) * (picker_flags & ImGuiColorEditFlags_NoAlpha ? 3 : 4));
+ ImGui::ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
+ ImGui::PopID();
+ }
+ ImGui::PopItemWidth();
+ }
+ if (allow_opt_alpha_bar)
+ {
+ if (allow_opt_picker) ImGui::Separator();
+ ImGui::CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
+ }
+ ImGui::EndPopup();
+}
+
+// Edit colors components (each component in 0.0f..1.0f range).
+// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
+// With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
+bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
@@ -9002,137 +10109,516 @@ bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha)
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
- const ImGuiID id = window->GetID(label);
- const float w_full = CalcItemWidth();
- const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f);
+ const float square_sz = GetFrameHeight();
+ const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
+ const float w_items_all = CalcItemWidth() - w_extra;
+ const char* label_display_end = FindRenderedTextEnd(label);
- ImGuiColorEditMode edit_mode = window->DC.ColorEditMode;
- if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton)
- edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3;
-
- float f[4] = { col[0], col[1], col[2], col[3] };
- if (edit_mode == ImGuiColorEditMode_HSV)
- ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
-
- int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
-
- int components = alpha ? 4 : 3;
- bool value_changed = false;
+ const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
+ const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
+ const int components = alpha ? 4 : 3;
+ const ImGuiColorEditFlags flags_untouched = flags;
BeginGroup();
PushID(label);
- const bool hsv = (edit_mode == 1);
- switch (edit_mode)
+ // If we're not showing any slider there's no point in doing any HSV conversions
+ if (flags & ImGuiColorEditFlags_NoInputs)
+ flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions;
+
+ // Context menu: display and modify options (before defaults are applied)
+ if (!(flags & ImGuiColorEditFlags_NoOptions))
+ ColorEditOptionsPopup(col, flags);
+
+ // Read stored options
+ if (!(flags & ImGuiColorEditFlags__InputsMask))
+ flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask);
+ if (!(flags & ImGuiColorEditFlags__DataTypeMask))
+ flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
+ if (!(flags & ImGuiColorEditFlags__PickerMask))
+ flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
+ flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask));
+
+ // Convert to the formats we need
+ float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
+ if (flags & ImGuiColorEditFlags_HSV)
+ ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
+ int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
+
+ bool value_changed = false;
+ bool value_changed_as_float = false;
+
+ if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
- case ImGuiColorEditMode_RGB:
- case ImGuiColorEditMode_HSV:
- {
- // RGB/HSV 0..255 Sliders
- const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x);
- const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
- const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
+ // RGB/HSV 0..255 Sliders
+ const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
+ const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
- const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x);
- const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
- const char* fmt_table[3][4] =
- {
- { "%3.0f", "%3.0f", "%3.0f", "%3.0f" },
- { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" },
- { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" }
- };
- const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1];
-
- PushItemWidth(w_item_one);
- for (int n = 0; n < components; n++)
- {
- if (n > 0)
- SameLine(0, style.ItemInnerSpacing.x);
- if (n + 1 == components)
- PushItemWidth(w_item_last);
- value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]);
- }
- PopItemWidth();
- PopItemWidth();
- }
- break;
- case ImGuiColorEditMode_HEX:
+ const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
+ const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
+ const char* fmt_table_int[3][4] =
{
- // RGB Hexadecimal Input
- const float w_slider_all = w_full - square_sz;
- char buf[64];
- if (alpha)
- ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]);
+ { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, // Short display
+ { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, // Long display for RGBA
+ { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } // Long display for HSVA
+ };
+ const char* fmt_table_float[3][4] =
+ {
+ { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
+ { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
+ { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
+ };
+ const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1;
+
+ PushItemWidth(w_item_one);
+ for (int n = 0; n < components; n++)
+ {
+ if (n > 0)
+ SameLine(0, style.ItemInnerSpacing.x);
+ if (n + 1 == components)
+ PushItemWidth(w_item_last);
+ if (flags & ImGuiColorEditFlags_Float)
+ value_changed = value_changed_as_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]);
else
- ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]);
- PushItemWidth(w_slider_all - style.ItemInnerSpacing.x);
- if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
- {
- value_changed |= true;
- char* p = buf;
- while (*p == '#' || ImCharIsSpace(*p))
- p++;
- i[0] = i[1] = i[2] = i[3] = 0;
- if (alpha)
- sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
- else
- sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
- }
- PopItemWidth();
+ 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");
}
- break;
+ PopItemWidth();
+ PopItemWidth();
+ }
+ else if ((flags & ImGuiColorEditFlags_HEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
+ {
+ // 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));
+ else
+ ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255));
+ PushItemWidth(w_items_all);
+ if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
+ {
+ value_changed = true;
+ char* p = buf;
+ while (*p == '#' || ImCharIsSpace(*p))
+ p++;
+ i[0] = i[1] = i[2] = i[3] = 0;
+ if (alpha)
+ sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
+ else
+ sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
+ }
+ if (!(flags & ImGuiColorEditFlags_NoOptions))
+ OpenPopupOnItemClick("context");
+ PopItemWidth();
}
- SameLine(0, style.ItemInnerSpacing.x);
+ ImGuiWindow* picker_active_window = NULL;
+ if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
+ {
+ if (!(flags & ImGuiColorEditFlags_NoInputs))
+ SameLine(0, style.ItemInnerSpacing.x);
- const ImVec4 col_display(col[0], col[1], col[2], 1.0f);
- if (ColorButton(col_display))
- g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
+ const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
+ if (ColorButton("##ColorButton", col_v4, flags))
+ {
+ if (!(flags & ImGuiColorEditFlags_NoPicker))
+ {
+ // Store current color and open a picker
+ g.ColorPickerRef = col_v4;
+ OpenPopup("picker");
+ SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y));
+ }
+ }
+ if (!(flags & ImGuiColorEditFlags_NoOptions))
+ OpenPopupOnItemClick("context");
+
+ if (BeginPopup("picker"))
+ {
+ picker_active_window = g.CurrentWindow;
+ if (label != label_display_end)
+ {
+ TextUnformatted(label, label_display_end);
+ Separator();
+ }
+ ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
+ ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
+ PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
+ value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
+ PopItemWidth();
+ EndPopup();
+ }
+ }
- // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here
- if (IsItemHovered())
- SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3]));
-
- if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton)
+ if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
{
SameLine(0, style.ItemInnerSpacing.x);
- const char* button_titles[3] = { "RGB", "HSV", "HEX" };
- if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups))
- g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away!
- }
-
- const char* label_display_end = FindRenderedTextEnd(label);
- if (label != label_display_end)
- {
- SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x);
TextUnformatted(label, label_display_end);
}
// Convert back
- for (int n = 0; n < 4; n++)
- f[n] = i[n] / 255.0f;
- if (edit_mode == 1)
- ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
-
- if (value_changed)
+ if (picker_active_window == NULL)
{
- col[0] = f[0];
- col[1] = f[1];
- col[2] = f[2];
- if (alpha)
- col[3] = f[3];
+ if (!value_changed_as_float)
+ for (int n = 0; n < 4; n++)
+ f[n] = i[n] / 255.0f;
+ if (flags & ImGuiColorEditFlags_HSV)
+ ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
+ if (value_changed)
+ {
+ col[0] = f[0];
+ col[1] = f[1];
+ col[2] = f[2];
+ if (alpha)
+ col[3] = f[3];
+ }
}
PopID();
EndGroup();
+ // Drag and Drop Target
+ if (window->DC.LastItemRectHoveredRect && BeginDragDropTarget()) // NB: The LastItemRectHoveredRect test is merely an optional micro-optimization
+ {
+ if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
+ {
+ memcpy((float*)col, payload->Data, sizeof(float) * 3);
+ value_changed = true;
+ }
+ if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
+ {
+ memcpy((float*)col, payload->Data, sizeof(float) * components);
+ value_changed = true;
+ }
+ EndDragDropTarget();
+ }
+
+ // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
+ if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
+ window->DC.LastItemId = g.ActiveId;
+
return value_changed;
}
-void ImGui::ColorEditMode(ImGuiColorEditMode mode)
+bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
+ float col4[4] = { col[0], col[1], col[2], 1.0f };
+ if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
+ return false;
+ col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
+ return true;
+}
+
+// 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side.
+static void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col)
+{
+ switch (direction)
+ {
+ case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return;
+ case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return;
+ case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return;
+ case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return;
+ case ImGuiDir_None: case ImGuiDir_Count_: break; // Fix warnings
+ }
+}
+
+static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w)
+{
+ RenderArrow(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK);
+ RenderArrow(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE);
+ RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK);
+ RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE);
+}
+
+// ColorPicker
+// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
+// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
+bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
+{
+ ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
- window->DC.ColorEditMode = mode;
+ ImDrawList* draw_list = window->DrawList;
+
+ ImGuiStyle& style = g.Style;
+ ImGuiIO& io = g.IO;
+
+ PushID(label);
+ BeginGroup();
+
+ if (!(flags & ImGuiColorEditFlags_NoSidePreview))
+ flags |= ImGuiColorEditFlags_NoSmallPreview;
+
+ // Context menu: display and store options.
+ if (!(flags & ImGuiColorEditFlags_NoOptions))
+ ColorPickerOptionsPopup(flags, col);
+
+ // Read stored options
+ if (!(flags & ImGuiColorEditFlags__PickerMask))
+ flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
+ IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected
+ if (!(flags & ImGuiColorEditFlags_NoOptions))
+ flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
+
+ // Setup
+ int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
+ bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
+ ImVec2 picker_pos = window->DC.CursorPos;
+ float square_sz = GetFrameHeight();
+ float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
+ float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
+ float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
+ float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
+ float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f);
+
+ float backup_initial_col[4];
+ memcpy(backup_initial_col, col, components * sizeof(float));
+
+ 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);
+
+ // 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);
+ ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
+ ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
+ ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
+
+ float H,S,V;
+ ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V);
+
+ bool value_changed = false, value_changed_h = false, value_changed_sv = false;
+
+ if (flags & ImGuiColorEditFlags_PickerHueWheel)
+ {
+ // Hue wheel + SV triangle logic
+ InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
+ if (IsItemActive())
+ {
+ 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))
+ {
+ // Interactive with Hue wheel
+ H = atan2f(current_off.y, current_off.x) / IM_PI*0.5f;
+ if (H < 0.0f)
+ H += 1.0f;
+ value_changed = value_changed_h = true;
+ }
+ float cos_hue_angle = cosf(-H * 2.0f * IM_PI);
+ float sin_hue_angle = sinf(-H * 2.0f * IM_PI);
+ if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
+ {
+ // Interacting with SV triangle
+ ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
+ if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
+ current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
+ float uu, vv, ww;
+ ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
+ V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
+ S = ImClamp(uu / V, 0.0001f, 1.0f);
+ value_changed = value_changed_sv = true;
+ }
+ }
+ if (!(flags & ImGuiColorEditFlags_NoOptions))
+ OpenPopupOnItemClick("context");
+ }
+ else if (flags & ImGuiColorEditFlags_PickerHueBar)
+ {
+ // SV rectangle logic
+ 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));
+ value_changed = value_changed_sv = true;
+ }
+ if (!(flags & ImGuiColorEditFlags_NoOptions))
+ OpenPopupOnItemClick("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));
+ value_changed = value_changed_h = true;
+ }
+ }
+
+ // Alpha bar logic
+ if (alpha_bar)
+ {
+ SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
+ 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));
+ value_changed = true;
+ }
+ }
+
+ if (!(flags & ImGuiColorEditFlags_NoSidePreview))
+ {
+ SameLine(0, style.ItemInnerSpacing.x);
+ BeginGroup();
+ }
+
+ if (!(flags & ImGuiColorEditFlags_NoLabel))
+ {
+ const char* label_display_end = FindRenderedTextEnd(label);
+ if (label != label_display_end)
+ {
+ if ((flags & ImGuiColorEditFlags_NoSidePreview))
+ SameLine(0, style.ItemInnerSpacing.x);
+ TextUnformatted(label, label_display_end);
+ }
+ }
+
+ if (!(flags & ImGuiColorEditFlags_NoSidePreview))
+ {
+ ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
+ if ((flags & ImGuiColorEditFlags_NoLabel))
+ Text("Current");
+ ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2));
+ if (ref_col != NULL)
+ {
+ Text("Original");
+ ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
+ if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)))
+ {
+ memcpy(col, ref_col, components * sizeof(float));
+ value_changed = true;
+ }
+ }
+ EndGroup();
+ }
+
+ // Convert back color to RGB
+ if (value_changed_h || value_changed_sv)
+ 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]);
+
+ // R,G,B and H,S,V slider color editor
+ if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
+ {
+ PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
+ ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
+ ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
+ if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0)
+ value_changed |= ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB);
+ if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0)
+ value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV);
+ if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0)
+ value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX);
+ PopItemWidth();
+ }
+
+ // Try to cancel hue wrap (after ColorEdit), if any
+ if (value_changed)
+ {
+ float new_H, new_S, new_V;
+ ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
+ if (new_H <= 0 && H > 0)
+ {
+ if (new_V <= 0 && V != new_V)
+ ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
+ else if (new_S <= 0)
+ ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
+ }
+ }
+
+ ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
+ ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
+ ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f));
+
+ const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) };
+ ImVec2 sv_cursor_pos;
+
+ if (flags & ImGuiColorEditFlags_PickerHueWheel)
+ {
+ // Render Hue Wheel
+ const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
+ const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
+ for (int n = 0; n < 6; n++)
+ {
+ const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
+ const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
+ const int vert_start_idx = draw_list->VtxBuffer.Size;
+ draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
+ draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness);
+ const int vert_end_idx = draw_list->VtxBuffer.Size;
+
+ // Paint colors over existing vertices
+ ImVec2 gradient_p0(wheel_center.x + cosf(a0) * wheel_r_inner, wheel_center.y + sinf(a0) * wheel_r_inner);
+ ImVec2 gradient_p1(wheel_center.x + cosf(a1) * wheel_r_inner, wheel_center.y + sinf(a1) * wheel_r_inner);
+ ShadeVertsLinearColorGradientKeepAlpha(draw_list->VtxBuffer.Data + vert_start_idx, draw_list->VtxBuffer.Data + vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]);
+ }
+
+ // Render Cursor + preview on Hue Wheel
+ float cos_hue_angle = cosf(H * 2.0f * IM_PI);
+ float sin_hue_angle = sinf(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);
+ 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, IM_COL32(128,128,128,255), hue_cursor_segments);
+ draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments);
+
+ // Render SV triangle (rotated according to hue)
+ ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
+ ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
+ ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
+ ImVec2 uv_white = GetFontTexUvWhitePixel();
+ draw_list->PrimReserve(6, 6);
+ draw_list->PrimVtx(tra, uv_white, hue_color32);
+ draw_list->PrimVtx(trb, uv_white, hue_color32);
+ draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE);
+ draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS);
+ draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK);
+ draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS);
+ draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f);
+ sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
+ }
+ else if (flags & ImGuiColorEditFlags_PickerHueBar)
+ {
+ // Render SV Square
+ draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE);
+ draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK);
+ RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f);
+ sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
+ sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
+
+ // Render Hue Bar
+ for (int i = 0; i < 6; ++i)
+ draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]);
+ float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f);
+ RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
+ RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
+ }
+
+ // 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, col32_no_alpha, 12);
+ draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12);
+ draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12);
+
+ // Render alpha bar
+ if (alpha_bar)
+ {
+ float alpha = ImSaturate(col[3]);
+ ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
+ RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
+ draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK);
+ float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f);
+ RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
+ RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
+ }
+
+ EndGroup();
+ PopID();
+
+ return value_changed && memcmp(backup_initial_col, col, components * sizeof(float));
}
// Horizontal separating line.
@@ -9141,8 +10627,20 @@ void ImGui::Separator()
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
+ ImGuiContext& g = *GImGui;
- if (window->DC.ColumnsCount > 1)
+ ImGuiWindowFlags flags = 0;
+ if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0)
+ flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
+ IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected
+ if (flags & ImGuiSeparatorFlags_Vertical)
+ {
+ VerticalSeparator();
+ return;
+ }
+
+ // Horizontal Separator
+ if (window->DC.ColumnsSet)
PopClipRect();
float x1 = window->Pos.x;
@@ -9152,26 +10650,93 @@ void ImGui::Separator()
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f));
ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
- if (!ItemAdd(bb, NULL))
+ if (!ItemAdd(bb, 0))
{
- if (window->DC.ColumnsCount > 1)
+ if (window->DC.ColumnsSet)
PushColumnClipRect();
return;
}
- window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Border));
+ window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator));
- ImGuiContext& g = *GImGui;
if (g.LogEnabled)
- LogText(IM_NEWLINE "--------------------------------");
+ LogRenderedText(NULL, IM_NEWLINE "--------------------------------");
- if (window->DC.ColumnsCount > 1)
+ if (window->DC.ColumnsSet)
{
PushColumnClipRect();
- window->DC.ColumnsCellMinY = window->DC.CursorPos.y;
+ window->DC.ColumnsSet->CellMinY = window->DC.CursorPos.y;
}
}
+void ImGui::VerticalSeparator()
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ if (window->SkipItems)
+ return;
+ ImGuiContext& g = *GImGui;
+
+ float y1 = window->DC.CursorPos.y;
+ float y2 = window->DC.CursorPos.y + window->DC.CurrentLineHeight;
+ const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2));
+ ItemSize(ImVec2(bb.GetWidth(), 0.0f));
+ if (!ItemAdd(bb, 0))
+ return;
+
+ window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));
+ if (g.LogEnabled)
+ LogText(" |");
+}
+
+bool ImGui::SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
+#ifdef IMGUI_HAS_NAV
+ window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
+#endif
+ bool add = ItemAdd(bb, id);
+ window->DC.ItemFlags = item_flags_backup;
+ if (!add)
+ return false;
+
+ bool hovered, held;
+ ImRect bb_interact = bb;
+ bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
+ ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);
+ if (g.ActiveId != id)
+ SetItemAllowOverlap();
+
+ if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id))
+ SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
+
+ ImRect bb_render = bb;
+ if (held)
+ {
+ ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;
+ float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;
+
+ // Minimum pane size
+ if (mouse_delta < min_size1 - *size1)
+ mouse_delta = min_size1 - *size1;
+ if (mouse_delta > *size2 - min_size2)
+ mouse_delta = *size2 - min_size2;
+
+ // Apply resize
+ *size1 += mouse_delta;
+ *size2 -= mouse_delta;
+ bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
+ }
+
+ // Render
+ const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
+ window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding);
+
+ return held;
+}
+
void ImGui::Spacing()
{
ImGuiWindow* window = GetCurrentWindow();
@@ -9188,7 +10753,7 @@ void ImGui::Dummy(const ImVec2& size)
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb);
- ItemAdd(bb, NULL);
+ ItemAdd(bb, 0);
}
bool ImGui::IsRectVisible(const ImVec2& size)
@@ -9232,12 +10797,11 @@ void ImGui::EndGroup()
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
- IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
+ IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
- group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves.
group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
window->DC.CursorPos = group_data.BackupCursorPos;
@@ -9252,20 +10816,19 @@ void ImGui::EndGroup()
{
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
- ItemAdd(group_bb, NULL);
+ ItemAdd(group_bb, 0);
}
- // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will function on the entire group.
+ // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context.
const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow);
if (active_id_within_group)
window->DC.LastItemId = g.ActiveId;
- if (active_id_within_group && g.HoveredId == g.ActiveId)
- window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true;
+ window->DC.LastItemRect = group_bb;
window->DC.GroupStack.pop_back();
- //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // Debug
+ //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
// Gets back to previous line and continue with horizontal layout
@@ -9301,38 +10864,44 @@ void ImGui::NewLine()
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
+
+ ImGuiContext& g = *GImGui;
+ const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
+ window->DC.LayoutType = ImGuiLayoutType_Vertical;
if (window->DC.CurrentLineHeight > 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));
else
- ItemSize(ImVec2(0.0f, GImGui->FontSize));
+ ItemSize(ImVec2(0.0f, g.FontSize));
+ window->DC.LayoutType = backup_layout_type;
}
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
- if (window->SkipItems || window->DC.ColumnsCount <= 1)
+ if (window->SkipItems || window->DC.ColumnsSet == NULL)
return;
ImGuiContext& g = *GImGui;
PopItemWidth();
PopClipRect();
- window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
- if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount)
+ ImGuiColumnsSet* columns = window->DC.ColumnsSet;
+ columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y);
+ if (++columns->Current < columns->Count)
{
// Columns 1+ cancel out IndentX
- window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x;
- window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent);
+ window->DC.ColumnsOffsetX = GetColumnOffset(columns->Current) - window->DC.IndentX + g.Style.ItemSpacing.x;
+ window->DrawList->ChannelsSetCurrent(columns->Current);
}
else
{
- window->DC.ColumnsCurrent = 0;
window->DC.ColumnsOffsetX = 0.0f;
- window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY;
window->DrawList->ChannelsSetCurrent(0);
+ columns->Current = 0;
+ columns->CellMinY = columns->CellMaxY;
}
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
- window->DC.CursorPos.y = window->DC.ColumnsCellMinY;
+ window->DC.CursorPos.y = columns->CellMinY;
window->DC.CurrentLineHeight = 0.0f;
window->DC.CurrentLineTextBaseOffset = 0.0f;
@@ -9343,182 +10912,308 @@ void ImGui::NextColumn()
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
- return window->DC.ColumnsCurrent;
+ return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
- return window->DC.ColumnsCount;
+ return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1;
}
-static float GetDraggedColumnOffset(int column_index)
+static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm)
+{
+ return offset_norm * (columns->MaxX - columns->MinX);
+}
+
+static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset)
+{
+ return offset / (columns->MaxX - columns->MinX);
+}
+
+static inline float GetColumnsRectHalfWidth() { return 4.0f; }
+
+static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
{
// Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
// window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
ImGuiContext& g = *GImGui;
- ImGuiWindow* window = ImGui::GetCurrentWindowRead();
+ ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets.
- IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index));
+ IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
- float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x;
- x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing);
+ float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
+ x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
+ if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
+ x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
- return (float)(int)x;
+ return x;
}
float ImGui::GetColumnOffset(int column_index)
{
- ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindowRead();
- if (column_index < 0)
- column_index = window->DC.ColumnsCurrent;
+ ImGuiColumnsSet* columns = window->DC.ColumnsSet;
+ IM_ASSERT(columns != NULL);
+ if (column_index < 0)
+ column_index = columns->Current;
+ IM_ASSERT(column_index < columns->Columns.Size);
+
+ /*
if (g.ActiveId)
{
- const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
+ ImGuiContext& g = *GImGui;
+ const ImGuiID column_id = columns->ColumnsSetId + ImGuiID(column_index);
if (g.ActiveId == column_id)
- return GetDraggedColumnOffset(column_index);
+ return GetDraggedColumnOffset(columns, column_index);
}
+ */
- IM_ASSERT(column_index < window->DC.ColumnsData.Size);
- const float t = window->DC.ColumnsData[column_index].OffsetNorm;
- const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
- return (float)(int)x_offset;
+ const float t = columns->Columns[column_index].OffsetNorm;
+ const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
+ return x_offset;
}
-void ImGui::SetColumnOffset(int column_index, float offset)
+static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false)
{
- ImGuiWindow* window = GetCurrentWindow();
if (column_index < 0)
- column_index = window->DC.ColumnsCurrent;
+ column_index = columns->Current;
- IM_ASSERT(column_index < window->DC.ColumnsData.Size);
- const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX);
- window->DC.ColumnsData[column_index].OffsetNorm = t;
-
- const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
- window->DC.StateStorage->SetFloat(column_id, t);
+ float offset_norm;
+ if (before_resize)
+ offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
+ else
+ offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
+ return OffsetNormToPixels(columns, offset_norm);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
- if (column_index < 0)
- column_index = window->DC.ColumnsCurrent;
+ ImGuiColumnsSet* columns = window->DC.ColumnsSet;
+ IM_ASSERT(columns != NULL);
- float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index);
- return w;
+ if (column_index < 0)
+ column_index = columns->Current;
+ return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
}
-static void PushColumnClipRect(int column_index)
+void ImGui::SetColumnOffset(int column_index, float offset)
{
- ImGuiWindow* window = ImGui::GetCurrentWindow();
- if (column_index < 0)
- column_index = window->DC.ColumnsCurrent;
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiColumnsSet* columns = window->DC.ColumnsSet;
+ IM_ASSERT(columns != NULL);
- float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f);
- float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f);
- ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true);
+ if (column_index < 0)
+ 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 float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
+
+ if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
+ offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
+ columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX);
+
+ if (preserve_width)
+ SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
}
-void ImGui::Columns(int columns_count, const char* id, bool border)
+void ImGui::SetColumnWidth(int column_index, float width)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiColumnsSet* columns = window->DC.ColumnsSet;
+ IM_ASSERT(columns != NULL);
+
+ if (column_index < 0)
+ column_index = columns->Current;
+ SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
+}
+
+void ImGui::PushColumnClipRect(int column_index)
+{
+ ImGuiWindow* window = GetCurrentWindowRead();
+ ImGuiColumnsSet* columns = window->DC.ColumnsSet;
+ if (column_index < 0)
+ column_index = columns->Current;
+
+ PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false);
+}
+
+static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id)
+{
+ for (int n = 0; n < window->ColumnsStorage.Size; n++)
+ if (window->ColumnsStorage[n].ID == id)
+ return &window->ColumnsStorage[n];
+
+ window->ColumnsStorage.push_back(ImGuiColumnsSet());
+ ImGuiColumnsSet* columns = &window->ColumnsStorage.back();
+ columns->ID = id;
+ return columns;
+}
+
+void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
- IM_ASSERT(columns_count >= 1);
- if (window->DC.ColumnsCount != 1)
- {
- if (window->DC.ColumnsCurrent != 0)
- ItemSize(ImVec2(0,0)); // Advance to column 0
- PopItemWidth();
- PopClipRect();
- window->DrawList->ChannelsMerge();
-
- window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y);
- window->DC.CursorPos.y = window->DC.ColumnsCellMaxY;
- }
-
- // Draw columns borders and handle resize at the time of "closing" a columns set
- if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems)
- {
- const float y1 = window->DC.ColumnsStartPosY;
- const float y2 = window->DC.CursorPos.y;
- for (int i = 1; i < window->DC.ColumnsCount; i++)
- {
- float x = window->Pos.x + GetColumnOffset(i);
- const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i);
- const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2));
- if (IsClippedEx(column_rect, &column_id, false))
- continue;
-
- bool hovered, held;
- ButtonBehavior(column_rect, column_id, &hovered, &held);
- if (hovered || held)
- g.MouseCursor = ImGuiMouseCursor_ResizeEW;
-
- // Draw before resize so our items positioning are in sync with the line being drawn
- const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column);
- const float xi = (float)(int)x;
- window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col);
-
- if (held)
- {
- if (g.ActiveIdIsJustActivated)
- g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking)
- x = GetDraggedColumnOffset(i);
- SetColumnOffset(i, x);
- }
- }
- }
+ IM_ASSERT(columns_count > 1);
+ IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported
// Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
// In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
- PushID(0x11223347 + (id ? 0 : columns_count));
- window->DC.ColumnsSetId = window->GetID(id ? id : "columns");
+ PushID(0x11223347 + (str_id ? 0 : columns_count));
+ ImGuiID id = window->GetID(str_id ? str_id : "columns");
PopID();
- // Set state for first column
- window->DC.ColumnsCurrent = 0;
- window->DC.ColumnsCount = columns_count;
- window->DC.ColumnsShowBorders = border;
+ // Acquire storage for the columns set
+ ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id);
+ IM_ASSERT(columns->ID == id);
+ columns->Current = 0;
+ columns->Count = columns_count;
+ columns->Flags = flags;
+ window->DC.ColumnsSet = columns;
- const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x;
- window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range
- window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
- window->DC.ColumnsStartPosY = window->DC.CursorPos.y;
- window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y;
+ // Set state for first column
+ const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->Size.x -window->ScrollbarSizes.x);
+ columns->MinX = window->DC.IndentX - g.Style.ItemSpacing.x; // Lock our horizontal range
+ //column->MaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x;
+ columns->MaxX = content_region_width - window->Scroll.x;
+ columns->StartPosY = window->DC.CursorPos.y;
+ columns->StartMaxPosX = window->DC.CursorMaxPos.x;
+ columns->CellMinY = columns->CellMaxY = window->DC.CursorPos.y;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
- if (window->DC.ColumnsCount != 1)
+ // Clear data if columns count changed
+ if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
+ columns->Columns.resize(0);
+
+ // Initialize defaults
+ columns->IsFirstFrame = (columns->Columns.Size == 0);
+ if (columns->Columns.Size == 0)
{
- // Cache column offsets
- window->DC.ColumnsData.resize(columns_count + 1);
- for (int column_index = 0; column_index < columns_count + 1; column_index++)
+ columns->Columns.reserve(columns_count + 1);
+ for (int n = 0; n < columns_count + 1; n++)
{
- const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index);
- KeepAliveID(column_id);
- const float default_t = column_index / (float)window->DC.ColumnsCount;
- const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store a union into the map?)
- window->DC.ColumnsData[column_index].OffsetNorm = t;
+ ImGuiColumnData column;
+ column.OffsetNorm = n / (float)columns_count;
+ columns->Columns.push_back(column);
}
- window->DrawList->ChannelsSplit(window->DC.ColumnsCount);
- PushColumnClipRect();
- PushItemWidth(GetColumnWidth() * 0.65f);
}
- else
+
+ for (int n = 0; n < columns_count + 1; n++)
{
- window->DC.ColumnsData.resize(0);
+ // Clamp position
+ ImGuiColumnData* column = &columns->Columns[n];
+ float t = column->OffsetNorm;
+ if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
+ t = ImMin(t, PixelsToOffsetNorm(columns, (columns->MaxX - columns->MinX) - g.Style.ColumnsMinSpacing * (columns->Count - n)));
+ column->OffsetNorm = t;
+
+ if (n == columns_count)
+ continue;
+
+ // Compute clipping rectangle
+ float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
+ float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
+ column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
+ column->ClipRect.ClipWith(window->ClipRect);
}
+
+ window->DrawList->ChannelsSplit(columns->Count);
+ PushColumnClipRect();
+ PushItemWidth(GetColumnWidth() * 0.65f);
+}
+
+void ImGui::EndColumns()
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = GetCurrentWindow();
+ ImGuiColumnsSet* columns = window->DC.ColumnsSet;
+ IM_ASSERT(columns != NULL);
+
+ PopItemWidth();
+ PopClipRect();
+ window->DrawList->ChannelsMerge();
+
+ columns->CellMaxY = ImMax(columns->CellMaxY, window->DC.CursorPos.y);
+ window->DC.CursorPos.y = columns->CellMaxY;
+ if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
+ window->DC.CursorMaxPos.x = ImMax(columns->StartMaxPosX, columns->MaxX); // Restore cursor max pos, as columns don't grow parent
+
+ // Draw columns borders and handle resize
+ bool is_being_resized = false;
+ if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
+ {
+ const float y1 = columns->StartPosY;
+ const float y2 = window->DC.CursorPos.y;
+ int dragging_column = -1;
+ for (int n = 1; n < columns->Count; n++)
+ {
+ float x = window->Pos.x + GetColumnOffset(n);
+ const ImGuiID column_id = columns->ID + ImGuiID(n);
+ const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction
+ const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2));
+ KeepAliveID(column_id);
+ if (IsClippedEx(column_rect, column_id, false))
+ continue;
+
+ bool hovered = false, held = false;
+ if (!(columns->Flags & ImGuiColumnsFlags_NoResize))
+ {
+ ButtonBehavior(column_rect, column_id, &hovered, &held);
+ if (hovered || held)
+ g.MouseCursor = ImGuiMouseCursor_ResizeEW;
+ if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize))
+ dragging_column = n;
+ }
+
+ // Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.)
+ const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
+ const float xi = (float)(int)x;
+ window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col);
+ }
+
+ // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
+ if (dragging_column != -1)
+ {
+ if (!columns->IsBeingResized)
+ for (int n = 0; n < columns->Count + 1; n++)
+ columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
+ columns->IsBeingResized = is_being_resized = true;
+ float x = GetDraggedColumnOffset(columns, dragging_column);
+ SetColumnOffset(dragging_column, x);
+ }
+ }
+ columns->IsBeingResized = is_being_resized;
+
+ window->DC.ColumnsSet = NULL;
+ window->DC.ColumnsOffsetX = 0.0f;
+ window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
+}
+
+// [2017/12: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
+void ImGui::Columns(int columns_count, const char* id, bool border)
+{
+ ImGuiWindow* window = GetCurrentWindow();
+ IM_ASSERT(columns_count >= 1);
+ if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count != columns_count)
+ EndColumns();
+
+ ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
+ //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
+ if (columns_count != 1)
+ BeginColumns(id, columns_count, flags);
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
- window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
+ window->DC.IndentX += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
}
@@ -9526,7 +11221,7 @@ void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
- window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing;
+ window->DC.IndentX -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
}
@@ -9591,33 +11286,287 @@ void ImGui::Value(const char* prefix, float v, const char* float_format)
}
}
-// FIXME: May want to remove those helpers?
-void ImGui::ValueColor(const char* prefix, const ImVec4& v)
+//-----------------------------------------------------------------------------
+// DRAG AND DROP
+//-----------------------------------------------------------------------------
+
+void ImGui::ClearDragDrop()
{
- Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w);
- SameLine();
- ColorButton(v, true);
+ ImGuiContext& g = *GImGui;
+ g.DragDropActive = false;
+ g.DragDropPayload.Clear();
+ g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
+ g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
+ g.DragDropAcceptFrameCount = -1;
}
-void ImGui::ValueColor(const char* prefix, ImU32 v)
+// Call when current ID is active.
+// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
+bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags, int mouse_button)
{
- Text("%s: %08X", prefix, v);
- SameLine();
- ColorButton(ColorConvertU32ToFloat4(v), true);
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+
+ bool source_drag_active = false;
+ ImGuiID source_id = 0;
+ ImGuiID source_parent_id = 0;
+ if (!(flags & ImGuiDragDropFlags_SourceExtern))
+ {
+ source_id = window->DC.LastItemId;
+ if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
+ return false;
+ if (g.IO.MouseDown[mouse_button] == false)
+ return false;
+
+ if (source_id == 0)
+ {
+ // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
+ // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
+ if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
+ {
+ IM_ASSERT(0);
+ return false;
+ }
+
+ // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
+ // We build a throwaway ID based on current ID stack + relative AABB of items in window.
+ // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
+ // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
+ bool is_hovered = window->DC.LastItemRectHoveredRect;
+ if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
+ return false;
+ source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
+ if (is_hovered)
+ SetHoveredID(source_id);
+ if (is_hovered && g.IO.MouseClicked[mouse_button])
+ {
+ SetActiveID(source_id, window);
+ FocusWindow(window);
+ }
+ if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
+ g.ActiveIdAllowOverlap = is_hovered;
+ }
+ if (g.ActiveId != source_id)
+ return false;
+ source_parent_id = window->IDStack.back();
+ source_drag_active = IsMouseDragging(mouse_button);
+ }
+ else
+ {
+ window = NULL;
+ source_id = ImHash("#SourceExtern", 0);
+ source_drag_active = true;
+ }
+
+ if (source_drag_active)
+ {
+ if (!g.DragDropActive)
+ {
+ IM_ASSERT(source_id != 0);
+ ClearDragDrop();
+ ImGuiPayload& payload = g.DragDropPayload;
+ payload.SourceId = source_id;
+ payload.SourceParentId = source_parent_id;
+ g.DragDropActive = true;
+ g.DragDropSourceFlags = flags;
+ g.DragDropMouseButton = mouse_button;
+ }
+
+ if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
+ {
+ // FIXME-DRAG
+ //SetNextWindowPos(g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding);
+ //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This is better but e.g ColorButton with checkboard has issue with transparent colors :(
+ SetNextWindowPos(g.IO.MousePos);
+ PushStyleColor(ImGuiCol_PopupBg, GetStyleColorVec4(ImGuiCol_PopupBg) * ImVec4(1.0f, 1.0f, 1.0f, 0.6f));
+ BeginTooltipEx(ImGuiWindowFlags_NoInputs);
+ }
+
+ if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
+ window->DC.LastItemRectHoveredRect = false;
+
+ return true;
+ }
+ return false;
+}
+
+void ImGui::EndDragDropSource()
+{
+ ImGuiContext& g = *GImGui;
+ IM_ASSERT(g.DragDropActive);
+
+ if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
+ {
+ EndTooltip();
+ PopStyleColor();
+ //PopStyleVar();
+ }
+
+ // Discard the drag if have not called SetDragDropPayload()
+ if (g.DragDropPayload.DataFrameCount == -1)
+ ClearDragDrop();
+}
+
+// Use 'cond' to choose to submit payload on drag start or every frame
+bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiPayload& payload = g.DragDropPayload;
+ if (cond == 0)
+ cond = ImGuiCond_Always;
+
+ IM_ASSERT(type != NULL);
+ IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 12 characters long");
+ IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
+ IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
+ IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
+
+ if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
+ {
+ // Copy payload
+ ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
+ g.DragDropPayloadBufHeap.resize(0);
+ if (data_size > sizeof(g.DragDropPayloadBufLocal))
+ {
+ // Store in heap
+ g.DragDropPayloadBufHeap.resize((int)data_size);
+ payload.Data = g.DragDropPayloadBufHeap.Data;
+ memcpy((void*)payload.Data, data, data_size);
+ }
+ else if (data_size > 0)
+ {
+ // Store locally
+ memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
+ payload.Data = g.DragDropPayloadBufLocal;
+ memcpy((void*)payload.Data, data, data_size);
+ }
+ else
+ {
+ payload.Data = NULL;
+ }
+ payload.DataSize = (int)data_size;
+ }
+ payload.DataFrameCount = g.FrameCount;
+
+ return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
+}
+
+bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
+{
+ ImGuiContext& g = *GImGui;
+ if (!g.DragDropActive)
+ return false;
+
+ ImGuiWindow* window = g.CurrentWindow;
+ if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
+ return false;
+ IM_ASSERT(id != 0);
+ if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
+ return false;
+
+ g.DragDropTargetRect = bb;
+ g.DragDropTargetId = id;
+ return true;
+}
+
+// We don't use BeginDragDropTargetCustom() and duplicate its code because:
+// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
+// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
+// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
+bool ImGui::BeginDragDropTarget()
+{
+ ImGuiContext& g = *GImGui;
+ if (!g.DragDropActive)
+ return false;
+
+ ImGuiWindow* window = g.CurrentWindow;
+ if (!window->DC.LastItemRectHoveredRect)
+ return false;
+ if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
+ return false;
+
+ ImGuiID id = window->DC.LastItemId;
+ if (id == 0)
+ id = window->GetIDFromRectangle(window->DC.LastItemRect);
+ if (g.DragDropPayload.SourceId == id)
+ return false;
+
+ g.DragDropTargetRect = window->DC.LastItemRect;
+ g.DragDropTargetId = id;
+ return true;
+}
+
+bool ImGui::IsDragDropPayloadBeingAccepted()
+{
+ ImGuiContext& g = *GImGui;
+ return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
+}
+
+const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
+{
+ ImGuiContext& g = *GImGui;
+ ImGuiWindow* window = g.CurrentWindow;
+ ImGuiPayload& payload = g.DragDropPayload;
+ IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
+ IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
+ if (type != NULL && !payload.IsDataType(type))
+ return NULL;
+
+ // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
+ // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
+ const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
+ ImRect r = g.DragDropTargetRect;
+ float r_surface = r.GetWidth() * r.GetHeight();
+ if (r_surface < g.DragDropAcceptIdCurrRectSurface)
+ {
+ g.DragDropAcceptIdCurr = g.DragDropTargetId;
+ g.DragDropAcceptIdCurrRectSurface = r_surface;
+ }
+
+ // Render default drop visuals
+ payload.Preview = was_accepted_previously;
+ flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
+ if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
+ {
+ // 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->PushClipRectFullScreen();
+ window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
+ if (push_clip_rect) window->DrawList->PopClipRect();
+ }
+
+ g.DragDropAcceptFrameCount = g.FrameCount;
+ payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
+ if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
+ return NULL;
+
+ return &payload;
+}
+
+// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
+void ImGui::EndDragDropTarget()
+{
+ ImGuiContext& g = *GImGui; (void)g;
+ IM_ASSERT(g.DragDropActive);
}
//-----------------------------------------------------------------------------
// PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
-#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS))
+#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
+#ifndef __MINGW32__
+#include
+#else
#include
#endif
+#endif
// Win32 API clipboard implementation
-#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS)
+#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
@@ -9631,7 +11580,10 @@ static const char* GetClipboardTextFn_DefaultImpl(void*)
return NULL;
HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
+ {
+ CloseClipboard();
return NULL;
+ }
if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
{
int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
@@ -9650,7 +11602,10 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
if (wbuf_handle == NULL)
+ {
+ CloseClipboard();
return;
+ }
ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
GlobalUnlock(wbuf_handle);
@@ -9664,28 +11619,25 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
- return GImGui->PrivateClipboard;
+ ImGuiContext& g = *GImGui;
+ return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
- if (g.PrivateClipboard)
- {
- ImGui::MemFree(g.PrivateClipboard);
- g.PrivateClipboard = NULL;
- }
+ g.PrivateClipboard.clear();
const char* text_end = text + strlen(text);
- g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1);
- memcpy(g.PrivateClipboard, text, (size_t)(text_end - text));
+ g.PrivateClipboard.resize((int)(text_end - text) + 1);
+ memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
g.PrivateClipboard[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
-#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)
+#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include
#ifdef _MSC_VER
@@ -9720,17 +11672,17 @@ void ImGui::ShowMetricsWindow(bool* p_open)
{
if (ImGui::Begin("ImGui Metrics", p_open))
{
- ImGui::Text("ImGui %s", ImGui::GetVersion());
+ ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs);
static bool show_clip_rects = true;
- ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects);
+ ImGui::Checkbox("Show clipping rectangles when hovering an ImDrawCmd", &show_clip_rects);
ImGui::Separator();
struct Funcs
{
- static void NodeDrawList(ImDrawList* draw_list, const char* label)
+ static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
@@ -9740,14 +11692,18 @@ void ImGui::ShowMetricsWindow(bool* p_open)
if (node_open) ImGui::TreePop();
return;
}
+
+ ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
+ if (window && ImGui::IsItemHovered())
+ overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
- ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list
- overlay_draw_list->PushClipRectFullScreen();
int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
+ if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
+ continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
@@ -9766,25 +11722,32 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
if (!pcmd_node_open)
continue;
+
+ // 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.
while (clipper.Step())
for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
- char buf[300], *buf_p = buf;
+ char buf[300];
+ char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangles_pos[3];
for (int n = 0; n < 3; n++, vtx_i++)
{
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
triangles_pos[n] = v.pos;
- buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
+ buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (ImGui::IsItemHovered())
- overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle
+ {
+ ImDrawListFlags backup_flags = overlay_draw_list->Flags;
+ overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
+ overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
+ overlay_draw_list->Flags = backup_flags;
+ }
}
ImGui::TreePop();
}
- overlay_draw_list->PopClipRect();
ImGui::TreePop();
}
@@ -9801,10 +11764,10 @@ void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
return;
- NodeDrawList(window->DrawList, "DrawList");
- ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y);
- ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
- ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y);
+ NodeDrawList(window, window->DrawList, "DrawList");
+ ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
+ ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetScrollMaxX(window), window->Scroll.y, GetScrollMaxY(window));
+ ImGui::BulletText("Active: %d, WriteAccessed: %d", window->Active, window->WriteAccessed);
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
@@ -9812,12 +11775,13 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
};
- ImGuiContext& g = *GImGui; // Access private state
+ // Access private state, we are going to display the draw lists from last frame
+ ImGuiContext& g = *GImGui;
Funcs::NodeWindows(g.Windows, "Windows");
- if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size))
+ if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
- for (int i = 0; i < g.RenderDrawLists[0].Size; i++)
- Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList");
+ for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
+ Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size))
@@ -9831,11 +11795,13 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
if (ImGui::TreeNode("Basic state"))
{
- ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL");
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
- ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
- ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame);
+ ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec)", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
+ ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec)", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer);
+ ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
+ ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->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::TreePop();
}
}
diff --git a/imgui.h b/imgui.h
index 9d84a94fe..a0453eeac 100644
--- a/imgui.h
+++ b/imgui.h
@@ -1,8 +1,8 @@
-// dear imgui, v1.50 WIP
+// dear imgui, v1.54 WIP
// (headers)
// See imgui.cpp file for documentation.
-// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code.
+// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
// Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
@@ -16,7 +16,7 @@
#include // ptrdiff_t, NULL
#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp
-#define IMGUI_VERSION "1.50 WIP"
+#define IMGUI_VERSION "1.54 WIP"
// Define attributes of all API symbols declarations, e.g. for DLL under Windows.
#ifndef IMGUI_API
@@ -29,12 +29,17 @@
#define IM_ASSERT(_EXPR) assert(_EXPR)
#endif
+// Helpers
// Some compilers support applying printf-style warnings to user functions.
#if defined(__clang__) || defined(__GNUC__)
-#define IM_PRINTFARGS(FMT) __attribute__((format(printf, FMT, (FMT+1))))
+#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1)))
+#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0)))
#else
-#define IM_PRINTFARGS(FMT)
+#define IM_FMTARGS(FMT)
+#define IM_FMTLIST(FMT)
#endif
+#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
+#define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++.
#if defined(__clang__)
#pragma clang diagnostic push
@@ -46,9 +51,10 @@ struct ImDrawChannel; // Temporary storage for outputting drawing
struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call)
struct ImDrawData; // All draw command lists required to render the frame
struct ImDrawList; // A single draw command list (generally one per window)
+struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself)
struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT)
struct ImFont; // Runtime data for a single font within a parent ImFontAtlas
-struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF font loader
+struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader
struct ImFontConfig; // Configuration data when adding a font or merging fonts
struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4
struct ImGuiIO; // Main configuration and I/O between your application and ImGui
@@ -58,8 +64,9 @@ struct ImGuiStyle; // Runtime data for styling/colors
struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
struct ImGuiTextBuffer; // Text buffer for logging/accumulating text
struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use)
-struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use)
+struct ImGuiSizeCallbackData; // Structure used to constraint window size in custom ways when using custom ImGuiSizeCallback (rare/advanced use)
struct ImGuiListClipper; // Helper to manually clip large list of items
+struct ImGuiPayload; // User data payload for drag and drop operations
struct ImGuiContext; // ImGui context (opaque)
// Typedefs and Enumerations (declared as int for compatibility and to not pollute the top of this file)
@@ -67,18 +74,30 @@ typedef unsigned int ImU32; // 32-bit unsigned integer (typically used t
typedef unsigned int ImGuiID; // unique ID used by widgets (typically hashed from a stack of string)
typedef unsigned short ImWchar; // character for keyboard input/display
typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp)
-typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_
-typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_
-typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_
-typedef int ImGuiColorEditMode; // color edit mode for ColorEdit*() // enum ImGuiColorEditMode_
-typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_
-typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_
-typedef int ImGuiSetCond; // condition flags for Set*() // enum ImGuiSetCond_
-typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_
-typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_
-typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_
+typedef int ImGuiCol; // enum: a color identifier for styling // enum ImGuiCol_
+typedef int ImGuiCond; // enum: a condition for Set*() // enum ImGuiCond_
+typedef int ImGuiKey; // enum: a key identifier (ImGui-side enum) // enum ImGuiKey_
+typedef int ImGuiMouseCursor; // enum: a mouse cursor identifier // enum ImGuiMouseCursor_
+typedef int ImGuiStyleVar; // enum: a variable identifier for styling // enum ImGuiStyleVar_
+typedef int ImDrawCornerFlags; // flags: for ImDrawList::AddRect*() etc. // enum ImDrawCornerFlags_
+typedef int ImDrawListFlags; // flags: for ImDrawList // enum ImDrawListFlags_
+typedef int ImGuiColorEditFlags; // flags: for ColorEdit*(), ColorPicker*() // enum ImGuiColorEditFlags_
+typedef int ImGuiColumnsFlags; // flags: for *Columns*() // enum ImGuiColumnsFlags_
+typedef int ImGuiDragDropFlags; // flags: for *DragDrop*() // enum ImGuiDragDropFlags_
+typedef int ImGuiComboFlags; // flags: for BeginCombo() // enum ImGuiComboFlags_
+typedef int ImGuiFocusedFlags; // flags: for IsWindowFocused() // enum ImGuiFocusedFlags_
+typedef int ImGuiHoveredFlags; // flags: for IsItemHovered() etc. // enum ImGuiHoveredFlags_
+typedef int ImGuiInputTextFlags; // flags: for InputText*() // enum ImGuiInputTextFlags_
+typedef int ImGuiSelectableFlags; // flags: for Selectable() // enum ImGuiSelectableFlags_
+typedef int ImGuiTreeNodeFlags; // flags: for TreeNode*(),CollapsingHeader()// enum ImGuiTreeNodeFlags_
+typedef int ImGuiWindowFlags; // flags: for Begin*() // enum ImGuiWindowFlags_
typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data);
-typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data);
+typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data);
+#if defined(_MSC_VER) && !defined(__clang__)
+typedef unsigned __int64 ImU64; // 64-bit unsigned integer
+#else
+typedef unsigned long long ImU64; // 64-bit unsigned integer
+#endif
// Others helpers at bottom of the file:
// class ImVector<> // Lightweight std::vector like class.
@@ -112,21 +131,25 @@ namespace ImGui
IMGUI_API ImGuiIO& GetIO();
IMGUI_API ImGuiStyle& GetStyle();
IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame()
- IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render().
- IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set.
+ IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until Render()/EndFrame().
+ IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data, then call your io.RenderDrawListsFn() function if set.
+ IMGUI_API void EndFrame(); // ends the ImGui frame. automatically called by Render(), so most likely don't need to ever call that yourself directly. If you don't need to render you may call EndFrame() but you'll have wasted CPU already. If you don't need to render, better to not create any imgui windows instead!
IMGUI_API void Shutdown();
- IMGUI_API void ShowUserGuide(); // help block
- IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block. you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
- IMGUI_API void ShowTestWindow(bool* p_open = NULL); // test window demonstrating ImGui features
- IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // metrics window for debugging ImGui
+
+ // Demo, Debug, Informations
+ IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application!
+ IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc.
+ IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
+ IMGUI_API bool ShowStyleSelector(const char* label);
+ IMGUI_API void ShowFontSelector(const char* label);
+ IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls).
// Window
- IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false).
- IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually.
- IMGUI_API void End(); // finish appending to current window, pop it off the window stack.
- IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400).
- IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // "
- IMGUI_API void EndChild();
+ IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed (so you can early out in your code) but you always need to call End() regardless. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false).
+ IMGUI_API void End(); // always call even if Begin() return false (which indicates a collapsed window)! finish appending to current window, pop it off the window stack.
+ IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400).
+ IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); // "
+ IMGUI_API void EndChild(); // always call even if BeginChild() return false (which indicates a collapsed or clipping child window)
IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
IMGUI_API float GetContentRegionAvailWidth(); //
@@ -139,24 +162,24 @@ namespace ImGui
IMGUI_API float GetWindowWidth();
IMGUI_API float GetWindowHeight();
IMGUI_API bool IsWindowCollapsed();
+ IMGUI_API bool IsWindowAppearing();
IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows
- IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position. call before Begin()
- IMGUI_API void SetNextWindowPosCenter(ImGuiSetCond cond = 0); // set next window position to be centered on screen. call before Begin()
- IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond 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, ImGuiSizeConstraintCallback 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. Use callback to apply non-trivial programmatic constraints.
- IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (enforce the range of scrollbars). set axis to 0.0f to leave it automatic. call before Begin()
- IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin()
- IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state. call before 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 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. Use callback to apply non-trivial programmatic constraints.
+ IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin()
+ IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin()
IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin()
- IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond 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, ImGuiSetCond 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, ImGuiSetCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
+ IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg.
+ 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 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 / front-most. prefer using SetNextWindowFocus().
- IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position.
- IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
- IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond = 0); // set named window collapsed state
- IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus.
+ IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position.
+ IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
+ IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state
+ IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus.
IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()]
IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()]
@@ -164,25 +187,27 @@ namespace ImGui
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 SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom.
+ IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions.
- IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use negative 'offset' to access previous widgets.
IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
IMGUI_API ImGuiStorage* GetStateStorage();
// Parameters stacks (shared)
IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
IMGUI_API void PopFont();
+ IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col);
IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col);
IMGUI_API void PopStyleColor(int count = 1);
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val);
IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val);
IMGUI_API void PopStyleVar(int count = 1);
+ IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwhise use GetColorU32() to get style color + style alpha.
IMGUI_API ImFont* GetFont(); // get current font
IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied
IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier
IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied
+ IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied
// Parameters stacks (current window)
IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side)
@@ -190,19 +215,19 @@ namespace ImGui
IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position
IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
IMGUI_API void PopTextWrapPos();
- IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
+ IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
IMGUI_API void PopAllowKeyboardFocus();
- IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (uses io.KeyRepeatDelay/io.KeyRepeatRate for now). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
+ IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
IMGUI_API void PopButtonRepeat();
// Cursor / Layout
- IMGUI_API void Separator(); // horizontal line
+ IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally
IMGUI_API void NewLine(); // undo a SameLine()
IMGUI_API void Spacing(); // add vertical spacing
IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size
- IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if >0
- IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if >0
+ IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0
+ IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0
IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
IMGUI_API void EndGroup();
IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position
@@ -214,72 +239,78 @@ namespace ImGui
IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position
IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
- IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets
- IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize()
- IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y
- IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y
+ IMGUI_API void AlignTextToFramePadding(); // vertically align/lower upcoming text to FramePadding.y so that it will aligns to upcoming widgets (call if you have text on a line before regular widgets)
+ IMGUI_API float GetTextLineHeight(); // ~ FontSize
+ IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
+ IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2
+ IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)
// Columns
- // You can also use SameLine(pos_x) for simplified columning. The columns API is still work-in-progress and rather lacking.
- IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1).
- IMGUI_API void NextColumn(); // next column
+ // You can also use SameLine(pos_x) for simplified columns. The columns API is still work-in-progress and rather lacking.
+ IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true);
+ IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished
IMGUI_API int GetColumnIndex(); // get current column index
- IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this
+ IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column
+ IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column
+ IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
- IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset())
- IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns())
+ IMGUI_API int GetColumnsCount();
// ID scopes
- // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them.
+ // If you are creating widgets in a loop you most likely want to push a unique identifier (e.g. object pointer, loop index) so ImGui can differentiate them.
// You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details.
- IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the *entire* stack!
+ IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the entire stack!
IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end);
IMGUI_API void PushID(const void* ptr_id);
IMGUI_API void PushID(int int_id);
IMGUI_API void PopID();
- IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). useful if you want to query into ImGuiStorage yourself. otherwise rarely needed
+ IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself
IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end);
IMGUI_API ImGuiID GetID(const void* ptr_id);
- // Widgets
- IMGUI_API void Text(const char* fmt, ...) IM_PRINTFARGS(1);
- IMGUI_API void TextV(const char* fmt, va_list args);
- IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_PRINTFARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
- IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args);
- IMGUI_API void TextDisabled(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
- IMGUI_API void TextDisabledV(const char* fmt, va_list args);
- IMGUI_API void TextWrapped(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
- IMGUI_API void TextWrappedV(const char* fmt, va_list args);
- IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text
- IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_PRINTFARGS(2); // display text+label aligned the same way as value+label widgets
- IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args);
- 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 BulletText(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for Bullet()+Text()
- IMGUI_API void BulletTextV(const char* fmt, va_list args);
+ // Widgets: Text
+ IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
+ IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text
+ IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
+ IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2);
+ IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
+ IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
+ IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets
+ IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
+ IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
+ IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
+
+ // Widgets: Main
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)
- IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size);
+ 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, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
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);
IMGUI_API bool RadioButton(const char* label, int* v, int v_button);
- IMGUI_API bool Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1);
- IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\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 height_in_items = -1);
- IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true);
- IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x
- IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // "
- IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and will be obsoleted/replaced.
IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float));
IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0));
IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float));
IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0));
IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL);
+ // Widgets: Combo Box
+ // The new BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it.
+ // The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose.
+ IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0);
+ IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true!
+ IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);
+ 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 (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds)
- // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
+ // 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
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* display_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* display_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* display_format = "%.3f", float power = 1.0f);
@@ -304,7 +335,7 @@ namespace ImGui
IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0);
// Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds)
- IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders
+ IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for logarithmic sliders
IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f);
IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f);
@@ -316,110 +347,135 @@ namespace ImGui
IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_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* display_format = "%.0f");
+ // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
+ // 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 the pass the address of a first float element out of a contiguous structure, e.g. &myvector.x
+ IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
+ IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0);
+ IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
+ IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL);
+ IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed.
+ IMGUI_API 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
IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop().
- IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
- IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_PRINTFARGS(2); // "
- IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // "
- IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // "
+ IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
+ IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // "
+ IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2);
+ IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2);
IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);
- IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3);
- IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3);
- IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args);
- IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args);
- IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose
+ IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
+ IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
+ IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
+ IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
+ IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose
IMGUI_API void TreePush(const void* ptr_id = NULL); // "
IMGUI_API void TreePop(); // ~ Unindent()+PopId()
IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing()
IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
- IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond = 0); // set next TreeNode/CollapsingHeader open state.
+ IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header
// Widgets: Selectable / Lists
- IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // 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));
- 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 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 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. make sure to 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. make sure to 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
+ IMGUI_API void ListBoxFooter(); // terminate the scrolling region
// Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)
IMGUI_API void Value(const char* prefix, bool b);
IMGUI_API void Value(const char* prefix, int v);
IMGUI_API void Value(const char* prefix, unsigned int v);
IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL);
- IMGUI_API void ValueColor(const char* prefix, const ImVec4& v);
- IMGUI_API void ValueColor(const char* prefix, ImU32 v);
// Tooltips
- IMGUI_API void SetTooltip(const char* fmt, ...) IM_PRINTFARGS(1); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins
- IMGUI_API void SetTooltipV(const char* fmt, va_list args);
- IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text
+ IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set text tooltip under mouse-cursor, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip().
+ IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1);
+ IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of contents).
IMGUI_API void EndTooltip();
// Menus
- IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true!
- IMGUI_API void EndMainMenuBar();
- IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set). only call EndMenuBar() if this returns true!
- IMGUI_API void EndMenuBar();
+ IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar.
+ IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true!
+ IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).
+ IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true!
IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true!
- IMGUI_API void EndMenu();
+ IMGUI_API void EndMenu(); // only call EndBegin() if BeginMenu() returns true!
IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment
IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL
// Popups
- IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. 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).
- IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true!
- IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (block interactions behind the modal window, can't close the modal window by clicking outside)
- IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp!
- IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on current window.
- IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window).
- IMGUI_API void EndPopup();
+ 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, int 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, int 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, int 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, int mouse_button = 1); // helper to open popup when clicked on last item. return true when just opened.
+ IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open
IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup.
- // Logging: all text output from interface is redirected to tty/file/clipboard. By default, tree nodes are automatically opened during logging.
+ // Logging/Capture: all text output from interface is captured to tty/file/clipboard. By default, tree nodes are automatically opened during logging.
IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty
IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file
IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard
IMGUI_API void LogFinish(); // stop logging (close file, etc.)
IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard
- IMGUI_API void LogText(const char* fmt, ...) IM_PRINTFARGS(1); // pass text data straight to log (without being displayed)
+ IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed)
+
+ // Drag and Drop
+ // [BETA API] Missing Demo code. API may evolve.
+ IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0, int mouse_button = 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 size, ImGuiCond cond = 0);// type is a user defined string of maximum 12 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!
+ IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive an item. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()
+ IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.
+ IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true!
// Clipping
IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);
IMGUI_API void PopClipRect();
+ // Styles
+ IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL);
+ IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL);
+ IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL);
+
+ // Focus
+ // (FIXME: Those functions will be reworked after we merge the navigation branch + have a pass at focusing/tabbing features.)
+ // (Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHere()" when applicable, to make your code more forward compatible when navigation branch is merged)
+ IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window (WIP navigation branch only). Pleaase use instead of SetScrollHere().
+ IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
+
// Utilities
- IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse?
- IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this
- IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false)
- IMGUI_API bool IsItemClicked(int mouse_button = 0); // was the last item clicked? (e.g. button/node just clicked on)
- IMGUI_API bool IsItemVisible(); // was the last item visible? (aka not out of sight due to clipping/scrolling.)
+ IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.
+ IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false)
+ IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on)
+ IMGUI_API bool IsItemVisible(); // is the last item visible? (aka not out of sight due to clipping/scrolling.)
IMGUI_API bool IsAnyItemHovered();
IMGUI_API bool IsAnyItemActive();
- IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space
+ IMGUI_API ImVec2 GetItemRectMin(); // get bounding rectangle of last item, in screen space
IMGUI_API ImVec2 GetItemRectMax(); // "
- IMGUI_API ImVec2 GetItemRectSize(); // "
+ IMGUI_API ImVec2 GetItemRectSize(); // get size of last item, in screen space
IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.
- IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others)
- IMGUI_API bool IsWindowFocused(); // is current window focused
- IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self)
- IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused
- IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup)
+ IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags = 0); // is current window focused? or its root/child, depending on flags. see flags for options.
+ IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags = 0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options.
IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped.
IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.
- IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window
IMGUI_API float GetTime();
IMGUI_API int GetFrameCount();
- IMGUI_API const char* GetStyleColName(ImGuiCol idx);
- IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items
+ IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text
+ IMGUI_API ImDrawListSharedData* GetDrawListSharedData();
+ IMGUI_API const char* GetStyleColorName(ImGuiCol idx);
IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);
IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can.
- IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
- IMGUI_API void EndChildFrame();
+ IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
+ IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window)
IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in);
IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in);
@@ -427,23 +483,23 @@ namespace ImGui
IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);
// Inputs
- IMGUI_API int GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
- IMGUI_API bool IsKeyDown(int key_index); // key_index into the keys_down[] array, imgui doesn't know the semantic of each entry, uses your own indices!
- IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // uses user's key indices as stored in the keys_down[] array. if repeat=true. uses io.KeyRepeatDelay / KeyRepeatRate
- IMGUI_API bool IsKeyReleased(int key_index); // "
+ IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
+ IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]!
+ IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
+ IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down)..
+ IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate
IMGUI_API bool IsMouseDown(int button); // is mouse button held
IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down)
IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime.
IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down)
- IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window). disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup)
- IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any visible window
- 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. disregarding of consideration of focus/window ordering/blocked by a popup.
IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold
+ 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. disregarding of consideration of focus/window ordering/blocked by a popup.
+ IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); //
IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into
IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold
IMGUI_API void ResetMouseDragDelta(int button = 0); //
- IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you
+ IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you
IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type
IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered.
IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle).
@@ -462,32 +518,21 @@ namespace ImGui
IMGUI_API ImGuiContext* GetCurrentContext();
IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
- // Obsolete (will be removed)
-#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
- static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+
- static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+
- static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+
- static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+
- static inline bool GetWindowCollapsed() { return ImGui::IsWindowCollapsed(); } // OBSOLETE 1.39+
- static inline bool IsRectClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.39+
-#endif
-
} // namespace ImGui
// Flags for ImGui::Begin()
enum ImGuiWindowFlags_
{
- // Default: 0
ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar
ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip
ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window
ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically)
- ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel
+ ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it
ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame
- ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items
+ //ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items (OBSOLETE! Use e.g. style.FrameBorderSize=1.0f to enable borders).
ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file
- ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs
+ ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs, hovering test with pass through.
ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar
ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section.
ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state
@@ -495,21 +540,19 @@ enum ImGuiWindowFlags_
ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y)
ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
+ ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // (WIP) Enable resize from any corners and borders. Your back-end needs to honor the different values of io.MouseCursor set by imgui.
+
// [Internal]
- ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild()
- ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild()
- ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 22, // Don't use! For internal use by BeginChild()
- ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox()
- ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip()
- ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup()
- ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal()
- ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu()
+ ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild()
+ ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip()
+ ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup()
+ ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal()
+ ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu()
};
// Flags for ImGui::InputText()
enum ImGuiInputTextFlags_
{
- // Default: 0
ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/
ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef
ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z
@@ -521,11 +564,12 @@ enum ImGuiInputTextFlags_
ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer.
ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character.
ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field
- ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, allow exiting edition by pressing Enter. Ctrl+Enter to add new line (by default adds new lines with Enter).
+ ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter).
ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally
ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode
ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode
ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*'
+ 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().
// [Internal]
ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline()
};
@@ -535,7 +579,7 @@ enum ImGuiTreeNodeFlags_
{
ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected
ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader)
- ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one
+ ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one
ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack
ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes)
ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open
@@ -543,20 +587,79 @@ enum ImGuiTreeNodeFlags_
ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open.
ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes).
ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow
- //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed
- //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
+ ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding().
+ //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed
+ //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 12, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible
ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog
+
+ // Obsolete names (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ , ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap
+#endif
};
// Flags for ImGui::Selectable()
enum ImGuiSelectableFlags_
{
- // Default: 0
ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window
ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column)
ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too
};
+// Flags for ImGui::BeginCombo()
+enum ImGuiComboFlags_
+{
+ ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default
+ ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo()
+ ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default)
+ ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible
+ ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible
+ ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest
+};
+
+// Flags for ImGui::IsWindowFocused()
+enum ImGuiFocusedFlags_
+{
+ ImGuiFocusedFlags_ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused
+ ImGuiFocusedFlags_RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy)
+ ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused
+ ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows
+};
+
+// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered()
+enum ImGuiHoveredFlags_
+{
+ ImGuiHoveredFlags_Default = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them.
+ ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered
+ ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy)
+ ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered
+ ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window
+ //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.
+ ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.
+ ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window
+ ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped,
+ ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows
+};
+
+// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload()
+enum ImGuiDragDropFlags_
+{
+ // BeginDragDropSource() flags
+ ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior.
+ ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return true, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item.
+ ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.
+ ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit.
+ ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.
+ // AcceptDragDropPayload() flags
+ ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.
+ ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target.
+ ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery.
+};
+
+// Standard Drag and Drop payload types. You can define you own payload types using 12-characters long strings. Types starting with '_' are defined by Dear ImGui.
+#define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3] // Standard type for colors, without alpha. User code may use this type.
+#define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4] // Standard type for colors. User code may use this type.
+
// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array
enum ImGuiKey_
{
@@ -569,6 +672,7 @@ enum ImGuiKey_
ImGuiKey_PageDown,
ImGuiKey_Home, // for text edit
ImGuiKey_End, // for text edit
+ ImGuiKey_Insert, // for text edit
ImGuiKey_Delete, // for text edit
ImGuiKey_Backspace, // for text edit
ImGuiKey_Enter, // for text edit
@@ -588,7 +692,7 @@ enum ImGuiCol_
ImGuiCol_Text,
ImGuiCol_TextDisabled,
ImGuiCol_WindowBg, // Background of normal windows
- ImGuiCol_ChildWindowBg, // Background of child windows
+ ImGuiCol_ChildBg, // Background of child windows
ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows
ImGuiCol_Border,
ImGuiCol_BorderShadow,
@@ -596,14 +700,13 @@ enum ImGuiCol_
ImGuiCol_FrameBgHovered,
ImGuiCol_FrameBgActive,
ImGuiCol_TitleBg,
- ImGuiCol_TitleBgCollapsed,
ImGuiCol_TitleBgActive,
+ ImGuiCol_TitleBgCollapsed,
ImGuiCol_MenuBarBg,
ImGuiCol_ScrollbarBg,
ImGuiCol_ScrollbarGrab,
ImGuiCol_ScrollbarGrabHovered,
ImGuiCol_ScrollbarGrabActive,
- ImGuiCol_ComboBg,
ImGuiCol_CheckMark,
ImGuiCol_SliderGrab,
ImGuiCol_SliderGrabActive,
@@ -613,9 +716,9 @@ enum ImGuiCol_
ImGuiCol_Header,
ImGuiCol_HeaderHovered,
ImGuiCol_HeaderActive,
- ImGuiCol_Column,
- ImGuiCol_ColumnHovered,
- ImGuiCol_ColumnActive,
+ ImGuiCol_Separator,
+ ImGuiCol_SeparatorHovered,
+ ImGuiCol_SeparatorActive,
ImGuiCol_ResizeGrip,
ImGuiCol_ResizeGripHovered,
ImGuiCol_ResizeGripActive,
@@ -628,37 +731,79 @@ enum ImGuiCol_
ImGuiCol_PlotHistogramHovered,
ImGuiCol_TextSelectedBg,
ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active
+ ImGuiCol_DragDropTarget,
ImGuiCol_COUNT
+
+ // Obsolete names (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ //, ImGuiCol_ComboBg = ImGuiCol_PopupBg // ComboBg has been merged with PopupBg, so a redirect isn't accurate.
+ , ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg, ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive
+#endif
};
-// Enumeration for PushStyleVar() / PopStyleVar()
-// NB: the enum only refers to fields of ImGuiStyle() which makes sense to be pushed/poped in UI code. Feel free to add others.
+// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure.
+// NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly.
+// NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.
enum ImGuiStyleVar_
{
- ImGuiStyleVar_Alpha, // float
- ImGuiStyleVar_WindowPadding, // ImVec2
- ImGuiStyleVar_WindowRounding, // float
- ImGuiStyleVar_WindowMinSize, // ImVec2
- ImGuiStyleVar_ChildWindowRounding, // float
- ImGuiStyleVar_FramePadding, // ImVec2
- ImGuiStyleVar_FrameRounding, // float
- ImGuiStyleVar_ItemSpacing, // ImVec2
- ImGuiStyleVar_ItemInnerSpacing, // ImVec2
- ImGuiStyleVar_IndentSpacing, // float
- ImGuiStyleVar_GrabMinSize, // float
- ImGuiStyleVar_ButtonTextAlign, // flags ImGuiAlign_*
+ // Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions)
+ ImGuiStyleVar_Alpha, // float Alpha
+ ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding
+ ImGuiStyleVar_WindowRounding, // float WindowRounding
+ ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize
+ ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize
+ ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign
+ ImGuiStyleVar_ChildRounding, // float ChildRounding
+ ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize
+ ImGuiStyleVar_PopupRounding, // float PopupRounding
+ ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize
+ ImGuiStyleVar_FramePadding, // ImVec2 FramePadding
+ ImGuiStyleVar_FrameRounding, // float FrameRounding
+ ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize
+ ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing
+ ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing
+ ImGuiStyleVar_IndentSpacing, // float IndentSpacing
+ ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize
+ ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding
+ ImGuiStyleVar_GrabMinSize, // float GrabMinSize
+ ImGuiStyleVar_GrabRounding, // float GrabRounding
+ ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign
ImGuiStyleVar_Count_
+
+ // Obsolete names (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ , ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding
+#endif
};
-// Enumeration for ColorEditMode()
-// FIXME-OBSOLETE: Will be replaced by future color/picker api
-enum ImGuiColorEditMode_
+// Enumeration for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()
+enum ImGuiColorEditFlags_
{
- ImGuiColorEditMode_UserSelect = -2,
- ImGuiColorEditMode_UserSelectShowButton = -1,
- ImGuiColorEditMode_RGB = 0,
- ImGuiColorEditMode_HSV = 1,
- ImGuiColorEditMode_HEX = 2
+ ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer).
+ ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square.
+ ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.
+ ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs)
+ ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square).
+ ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview.
+ ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker).
+ ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead.
+ // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup.
+ ImGuiColorEditFlags_AlphaBar = 1 << 9, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
+ ImGuiColorEditFlags_AlphaPreview = 1 << 10, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.
+ ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 11, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque.
+ ImGuiColorEditFlags_HDR = 1 << 12, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well).
+ ImGuiColorEditFlags_RGB = 1 << 13, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX.
+ ImGuiColorEditFlags_HSV = 1 << 14, // [Inputs] // "
+ ImGuiColorEditFlags_HEX = 1 << 15, // [Inputs] // "
+ ImGuiColorEditFlags_Uint8 = 1 << 16, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255.
+ ImGuiColorEditFlags_Float = 1 << 17, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers.
+ ImGuiColorEditFlags_PickerHueBar = 1 << 18, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value.
+ ImGuiColorEditFlags_PickerHueWheel = 1 << 19, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value.
+ // Internals/Masks
+ ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX,
+ ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float,
+ ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar,
+ ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions()
};
// Enumeration for GetMouseCursor()
@@ -668,33 +813,43 @@ enum ImGuiMouseCursor_
ImGuiMouseCursor_Arrow = 0,
ImGuiMouseCursor_TextInput, // When hovering over InputText, etc.
ImGuiMouseCursor_Move, // Unused
- ImGuiMouseCursor_ResizeNS, // Unused
- ImGuiMouseCursor_ResizeEW, // When hovering over a column
- ImGuiMouseCursor_ResizeNESW, // Unused
+ ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border
+ ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column
+ ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window
ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window
ImGuiMouseCursor_Count_
};
-// Condition flags for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions
-// All those functions treat 0 as a shortcut to ImGuiSetCond_Always
-enum ImGuiSetCond_
+// Condition for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions
+// All those functions treat 0 as a shortcut to ImGuiCond_Always. From the point of view of the user use this as an enum (don't combine multiple values into flags).
+enum ImGuiCond_
{
- ImGuiSetCond_Always = 1 << 0, // Set the variable
- ImGuiSetCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed)
- ImGuiSetCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file)
- ImGuiSetCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time)
+ 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_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file)
+ ImGuiCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time)
+
+ // Obsolete names (will be removed)
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing
+#endif
};
struct ImGuiStyle
{
float Alpha; // Global alpha applies to everything in ImGui
ImVec2 WindowPadding; // Padding within a window
- ImVec2 WindowMinSize; // Minimum window size
float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
+ 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
ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
- float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows
+ float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
+ float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly)
+ float PopupRounding; // Radius of popup window corners rounding.
+ float PopupBorderSize; // Thickness of border around popup windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly)
ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets)
float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
+ float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly)
ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines
ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
@@ -708,11 +863,12 @@ struct ImGuiStyle
ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
ImVec2 DisplaySafeAreaPadding; // 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.
bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU.
- bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
- float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
+ bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
+ 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.
ImVec4 Colors[ImGuiCol_COUNT];
IMGUI_API ImGuiStyle();
+ IMGUI_API void ScaleAllSizes(float scale_factor);
};
// This is where your app communicate with ImGui. Access via ImGui::GetIO().
@@ -730,10 +886,10 @@ struct ImGuiIO
const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified).
float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds.
float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels.
- float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging
- int KeyMap[ImGuiKey_COUNT]; // // Map of indices into the KeysDown[512] entries array
+ float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging.
+ int KeyMap[ImGuiKey_COUNT]; // // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state.
float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
- float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds.
+ float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds.
void* UserData; // = NULL // Store your own data for retrieval by callbacks.
ImFontAtlas* Fonts; // // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array.
@@ -745,10 +901,11 @@ struct ImGuiIO
ImVec2 DisplayVisibleMax; // (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize
// Advanced/subtle behaviors
- bool OSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl
+ bool OptMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl
+ bool OptCursorBlink; // = true // Enable blinking cursor, for users who consider it annoying.
//------------------------------------------------------------------
- // User Functions
+ // Settings (User Functions)
//------------------------------------------------------------------
// Rendering function, will be called in Render().
@@ -776,15 +933,16 @@ struct ImGuiIO
// Input - Fill before calling NewFrame()
//------------------------------------------------------------------
- ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
+ ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.)
bool MouseDown[5]; // Mouse buttons: left, right, 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.
- float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text.
+ float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text.
+ float MouseWheelH; // Mouse wheel (Horizontal). Most users don't have a mouse with an horizontal wheel, may not be filled by all back ends.
bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor).
bool KeyCtrl; // Keyboard modifier pressed: Control
bool KeyShift; // Keyboard modifier pressed: Shift
bool KeyAlt; // Keyboard modifier pressed: Alt
bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows
- bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data)
+ bool KeysDown[512]; // Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys).
ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper.
// Functions
@@ -796,42 +954,76 @@ struct ImGuiIO
// Output - Retrieve after calling NewFrame()
//------------------------------------------------------------------
- bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input). Use to hide mouse from the rest of your application
- bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input). Use to hide keyboard from the rest of your application
- bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. Use to activate on screen keyboard if your system needs one
+ bool WantCaptureMouse; // When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. This is set by ImGui when it wants to use your mouse (e.g. unclicked mouse is hovering a window, or a widget is active).
+ bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. This is set by ImGui when it wants to use your keyboard inputs.
+ bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
+ bool WantMoveMouse; // [BETA-NAV] MousePos has been altered, back-end should reposition mouse on next frame. Set only when 'NavMovesMouse=true'.
float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames
int MetricsAllocs; // Number of active memory allocations
int MetricsRenderVertices; // Vertices output during last call to Render()
int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3
int MetricsActiveWindows; // Number of visible root windows (exclude child windows)
- ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative, so a disappearing/reappearing mouse won't have a huge delta for one frame.
+ ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.
//------------------------------------------------------------------
- // [Private] ImGui will maintain those fields. Forward compatibility not guaranteed!
+ // [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed!
//------------------------------------------------------------------
ImVec2 MousePosPrev; // Previous mouse position temporary storage (nb: not for public use, set to MousePos in NewFrame())
- bool MouseClicked[5]; // Mouse button went from !Down to Down
ImVec2 MouseClickedPos[5]; // Position at time of clicking
float MouseClickedTime[5]; // Time of last click (used to figure out double-click)
+ bool MouseClicked[5]; // Mouse button went from !Down to Down
bool MouseDoubleClicked[5]; // Has mouse button been double-clicked?
bool MouseReleased[5]; // Mouse button went from Down to !Down
bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds.
float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked)
float MouseDownDurationPrev[5]; // Previous time the mouse button has been down
- float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click point
+ ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
+ float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point
float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed)
float KeysDownDurationPrev[512]; // Previous duration the key has been down
IMGUI_API ImGuiIO();
};
+//-----------------------------------------------------------------------------
+// Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details)
+//-----------------------------------------------------------------------------
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+namespace ImGui
+{
+ // OBSOLETED in 1.54 (from Dec 2017)
+ 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) { (void)on_edge; (void)outward; IM_ASSERT(0); return pos; }
+ // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)
+ static inline void ShowTestWindow() { return ShowDemoWindow(); }
+ static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); }
+ static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); }
+ static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); }
+ static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); }
+ // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017)
+ bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // Use SetNextWindowSize(size, ImGuiCond_FirstUseEver) + SetNextWindowBgAlpha() instead.
+ static inline bool IsRootWindowOrAnyChildHovered() { return IsItemHovered(ImGuiHoveredFlags_RootAndChildWindows); }
+ static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); }
+ static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); }
+ // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017)
+ static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); }
+ static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // This was misleading and partly broken. You probably want to use the ImGui::GetIO().WantCaptureMouse flag instead.
+ static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); }
+ static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); }
+ // OBSOLETED IN 1.49 (between Apr 2016 and May 2016)
+ static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1 << 5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); }
+}
+#endif
+
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
// Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug).
-// Our implementation does NOT call c++ constructors because we don't use them in ImGui. Don't use this class as a straight std::vector replacement in your code!
+// Our implementation does NOT call C++ constructors/destructors. This is intentional and we do not require it. Do not use this class as a straight std::vector replacement in your code!
template
class ImVector
{
@@ -844,8 +1036,8 @@ public:
typedef value_type* iterator;
typedef const value_type* const_iterator;
- ImVector() { Size = Capacity = 0; Data = NULL; }
- ~ImVector() { if (Data) ImGui::MemFree(Data); }
+ inline ImVector() { Size = Capacity = 0; Data = NULL; }
+ inline ~ImVector() { if (Data) ImGui::MemFree(Data); }
inline bool empty() const { return Size == 0; }
inline int size() const { return Size; }
@@ -861,40 +1053,40 @@ public:
inline const_iterator end() const { return Data + Size; }
inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; }
inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; }
- inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; }
- inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; }
+ inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; }
+ inline const value_type& 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; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
- inline int _grow_capacity(int new_size) { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > new_size ? new_capacity : new_size; }
+ 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++) Data[n] = v; Size = new_size; }
inline void reserve(int new_capacity)
{
- if (new_capacity <= Capacity) return;
- T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type));
+ if (new_capacity <= Capacity)
+ return;
+ T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(T));
if (Data)
- memcpy(new_data, Data, (size_t)Size * sizeof(value_type));
+ memcpy(new_data, Data, (size_t)Size * sizeof(T));
ImGui::MemFree(Data);
Data = new_data;
Capacity = new_capacity;
}
- inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; }
+ inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); Data[Size++] = v; }
inline void pop_back() { IM_ASSERT(Size > 0); Size--; }
+ inline void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); }
inline iterator erase(const_iterator 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(value_type)); Size--; return Data + off; }
- inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; }
+ inline iterator insert(const_iterator it, const value_type& 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(value_type)); Data[off] = v; Size++; return Data + off; }
+ inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
};
-// Helper: execute a block of code at maximum once a frame
-// Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame.
+// Helper: execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame.
// Usage:
-// IMGUI_ONCE_UPON_A_FRAME
-// {
-// // code block will be executed one per frame
-// }
-// Attention! the macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces.
-#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf##__LINE__; if (imgui_oaf##__LINE__)
+// static ImGuiOnceUponAFrame oaf;
+// if (oaf)
+// ImGui::Text("This will be called only once per frame");
struct ImGuiOnceUponAFrame
{
ImGuiOnceUponAFrame() { RefFrame = -1; }
@@ -902,6 +1094,11 @@ struct ImGuiOnceUponAFrame
operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; }
};
+// Helper macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces.
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Will obsolete
+#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf)
+#endif
+
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
struct ImGuiTextFilter
{
@@ -925,13 +1122,12 @@ struct ImGuiTextFilter
ImVector Filters;
int CountGrep;
- ImGuiTextFilter(const char* default_filter = "");
- ~ImGuiTextFilter() {}
- void Clear() { InputBuf[0] = 0; Build(); }
- bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build
- bool PassFilter(const char* text, const char* text_end = NULL) const;
- bool IsActive() const { return !Filters.empty(); }
+ IMGUI_API ImGuiTextFilter(const char* default_filter = "");
+ IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build
+ IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const;
IMGUI_API void Build();
+ void Clear() { InputBuf[0] = 0; Build(); }
+ bool IsActive() const { return !Filters.empty(); }
};
// Helper: Text buffer for logging/accumulating text
@@ -946,18 +1142,19 @@ struct ImGuiTextBuffer
int size() const { return Buf.Size - 1; }
bool empty() { return Buf.Size <= 1; }
void clear() { Buf.clear(); Buf.push_back(0); }
+ void reserve(int capacity) { Buf.reserve(capacity); }
const char* c_str() const { return Buf.Data; }
- IMGUI_API void append(const char* fmt, ...) IM_PRINTFARGS(2);
- IMGUI_API void appendv(const char* fmt, va_list args);
+ IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2);
+ IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2);
};
// Helper: Simple Key->value storage
// Typically you don't have to worry about this since a storage is held within each Window.
-// We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options.
-// You can use it as custom user storage for temporary values.
-// Declare your own storage if:
+// We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options.
+// This is optimized for efficient reading (dichotomy into a contiguous buffer), rare writing (typically tied to user interactions)
+// You can use it as custom user storage for temporary values. Declare your own storage if, for example:
// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state).
-// - You want to store custom debug data easily without adding or editing structures in your code.
+// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient)
// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types.
struct ImGuiStorage
{
@@ -965,7 +1162,7 @@ struct ImGuiStorage
{
ImGuiID key;
union { int val_i; float val_f; void* val_p; };
- Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; }
+ Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; }
Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; }
Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; }
};
@@ -974,7 +1171,7 @@ struct ImGuiStorage
// - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N)
// - Set***() functions find pair, insertion on demand if missing.
// - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair.
- IMGUI_API void Clear();
+ void Clear() { Data.clear(); }
IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const;
IMGUI_API void SetInt(ImGuiID key, int val);
IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const;
@@ -995,6 +1192,9 @@ struct ImGuiStorage
// Use on your own storage if you know only integer are being stored (open/close all tree nodes)
IMGUI_API void SetAllInt(int val);
+
+ // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
+ IMGUI_API void BuildSortByKey();
};
// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered.
@@ -1020,21 +1220,43 @@ struct ImGuiTextEditCallbackData
int SelectionEnd; // // Read-write
// NB: Helper functions for text manipulation. Calling those function loses selection.
- void DeleteChars(int pos, int bytes_count);
- void InsertChars(int pos, const char* text, const char* text_end = NULL);
- bool HasSelection() const { return SelectionStart != SelectionEnd; }
+ 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; }
};
// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.
-struct ImGuiSizeConstraintCallbackData
+struct ImGuiSizeCallbackData
{
void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints()
- ImVec2 Pos; // Read-only. Window position, for reference.
- ImVec2 CurrentSize; // Read-only. Current window size.
+ ImVec2 Pos; // Read-only. Window position, for reference.
+ ImVec2 CurrentSize; // Read-only. Current window size.
ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing.
};
+// Data payload for Drag and Drop operations
+struct ImGuiPayload
+{
+ // Members
+ const void* Data; // Data (copied and owned by dear imgui)
+ int DataSize; // Data size
+
+ // [Internal]
+ ImGuiID SourceId; // Source item id
+ ImGuiID SourceParentId; // Source parent id (if available)
+ int DataFrameCount; // Data timestamp
+ char DataType[12 + 1]; // Data type tag (short user-supplied string, 12 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.
+
+ ImGuiPayload() { Clear(); }
+ void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; }
+ bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; }
+ bool IsPreview() const { return Preview; }
+ bool IsDelivery() const { return Delivery; }
+};
+
// Helpers macros to generate 32-bits encoded colors
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
#define IM_COL32_R_SHIFT 16
@@ -1050,14 +1272,14 @@ struct ImGuiSizeConstraintCallbackData
#define IM_COL32_A_MASK 0xFF000000
#endif
#define IM_COL32(R,G,B,A) (((ImU32)(A)< IdxBuffer;
};
+enum ImDrawCornerFlags_
+{
+ ImDrawCornerFlags_TopLeft = 1 << 0, // 0x1
+ ImDrawCornerFlags_TopRight = 1 << 1, // 0x2
+ ImDrawCornerFlags_BotLeft = 1 << 2, // 0x4
+ ImDrawCornerFlags_BotRight = 1 << 3, // 0x8
+ ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, // 0x3
+ ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, // 0xC
+ ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, // 0x5
+ ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, // 0xA
+ ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience
+};
+
+enum ImDrawListFlags_
+{
+ ImDrawListFlags_AntiAliasedLines = 1 << 0,
+ ImDrawListFlags_AntiAliasedFill = 1 << 1
+};
+
// Draw command list
// This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering.
-// At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future.
-// If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives.
+// Each ImGui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to access the current window draw list and draw custom primitives.
// You can interleave normal ImGui:: calls and adding primitives to the current draw list.
-// All positions are in screen coordinates (0,0=top-left, 1 pixel per unit). Primitives are always added to the list and not culled (culling is done at render time and at a higher-level by ImGui:: functions).
+// All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), however you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well)
+// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects.
struct ImDrawList
{
// This is what you have to render
- ImVector CmdBuffer; // Commands. Typically 1 command = 1 gpu draw call.
+ ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
ImVector VtxBuffer; // Vertex buffer.
// [Internal, used while building lists]
+ ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
+ const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context)
const char* _OwnerName; // Pointer to owner window's name for debugging
unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size
ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
@@ -1181,18 +1425,21 @@ struct ImDrawList
int _ChannelsCount; // [Internal] number of active channels (1+)
ImVector _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size)
- ImDrawList() { _OwnerName = NULL; Clear(); }
+ // 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(); }
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();
IMGUI_API void PushTextureID(const ImTextureID& texture_id);
IMGUI_API void PopTextureID();
+ inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }
+ inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }
// Primitives
IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f);
- IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round
- IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0); // a: upper-left, b: lower-right
+ IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round
+ IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right
IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left);
IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f);
IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col);
@@ -1202,21 +1449,23 @@ struct ImDrawList
IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12);
IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL);
IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL);
- IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), ImU32 col = 0xFFFFFFFF);
- IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased);
- IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased);
+ IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF);
+ IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF);
+ IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All);
+ IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness);
+ IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col);
IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0);
// Stateful path API, add points then finish with PathFill() or PathStroke()
inline void PathClear() { _Path.resize(0); }
inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); }
inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); }
- inline void PathFill(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); }
- inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); PathClear(); }
+ inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); PathClear(); }
+ inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); PathClear(); }
IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10);
IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle
IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0);
- IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ~0); // rounding_corners_flags: 4-bits corresponding to which corner to round
+ IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All);
// Channels
// - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives)
@@ -1254,41 +1503,51 @@ struct ImDrawData
int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size
// Functions
- ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; }
- IMGUI_API void DeIndexAllBuffers(); // For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
+ ImDrawData() { Clear(); }
+ void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } // Draw lists are owned by the ImGuiContext and only pointed to here.
+ IMGUI_API void DeIndexAllBuffers(); // For backward compatibility or convenience: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
};
struct ImFontConfig
{
- void* FontData; // // TTF data
- int FontDataSize; // // TTF data size
- bool FontDataOwnedByAtlas; // true // TTF data ownership taken by the container ImFontAtlas (will delete memory itself). Set to true
- int FontNo; // 0 // Index of font within TTF file
- float SizePixels; // // Size in pixels for rasterizer
+ void* FontData; // // TTF/OTF data
+ int FontDataSize; // // TTF/OTF data size
+ bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
+ int FontNo; // 0 // Index of font within TTF/OTF file
+ float SizePixels; // // Size in pixels for rasterizer.
int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
- ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs
- const ImWchar* GlyphRanges; // // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
- bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs).
- bool MergeGlyphCenterV; // false // When merging (multiple ImFontInput for one ImFont), vertically center new glyphs instead of aligning their baseline
+ ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
+ ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
+ const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
+ bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
+ unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
+ float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
// [Internal]
- char Name[32]; // Name (strictly for debugging)
+ char Name[32]; // Name (strictly to ease debugging)
ImFont* DstFont;
IMGUI_API ImFontConfig();
};
-// Load and rasterize multiple TTF fonts into a same texture.
+struct ImFontGlyph
+{
+ ImWchar Codepoint; // 0x0000..0xFFFF
+ float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
+ float X0, Y0, X1, Y1; // Glyph corners
+ float U0, V0, U1, V1; // Texture coordinates
+};
+
+// Load and rasterize multiple TTF/OTF fonts into a same texture.
// Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering.
// We also add custom graphic data into the texture that serves for ImGui.
// 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you.
// 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
// 3. Upload the pixels data into a texture within your graphics system.
// 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture.
-// 5. Call ClearTexData() to free textures memory on the heap.
-// NB: If you use a 'glyph_ranges' array you need to make sure that your array persist up until the ImFont is cleared. We only copy the pointer, not the data.
+// IMPORTANT: If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the ImFont is build (when calling GetTextData*** or Build()). We only copy the pointer, not the data.
struct ImFontAtlas
{
IMGUI_API ImFontAtlas();
@@ -1296,70 +1555,110 @@ struct ImFontAtlas
IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg);
IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL);
IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);
- IMGUI_API ImFont* AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build()
- IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data' still owned by caller. Compress with binary_to_compressed_c.cpp
- IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 paramaeter
+ IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after Build(). Set font_cfg->FontDataOwnedByAtlas to false to keep ownership.
+ IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
+ IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory.
IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges)
IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates)
IMGUI_API void Clear(); // Clear all
- // Retrieve texture data
- // User is in charge of copying the pixels into graphics memory, then call SetTextureUserID()
- // After loading the texture into your graphic system, store your texture handle in 'TexID' (ignore if you aren't using multiple fonts nor images)
- // RGBA32 format is provided for convenience and high compatibility, but note that all RGB pixels are white, so 75% of the memory is wasted.
+ // Build atlas, retrieve pixel data.
+ // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
+ // RGBA32 format is provided for convenience and compatibility, but note that unless you use CustomRect to draw color data, the RGB pixels emitted from Fonts will all be white (~75% of waste).
// Pitch = Width * BytesPerPixels
+ IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions.
IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel
IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel
- void SetTexID(void* id) { TexID = id; }
+ void SetTexID(ImTextureID id) { TexID = id; }
+
+ //-------------------------------------------
+ // Glyph Ranges
+ //-------------------------------------------
// Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)
- // NB: Make sure that your string are UTF-8 and NOT in your local code page. See FAQ for details.
+ // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details.
IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters
IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
- IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs
+ IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Default + Japanese + full set of about 21000 CJK Unified Ideographs
IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters
+ // Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges().
+ struct GlyphRangesBuilder
+ {
+ ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used)
+ GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); }
+ bool GetBit(int n) { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; }
+ void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array
+ void AddChar(ImWchar c) { SetBit(c); } // Add character
+ IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added)
+ IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault) to force add all of ASCII/Latin+Ext
+ IMGUI_API void BuildRanges(ImVector* out_ranges); // Output new ranges
+ };
+
+ //-------------------------------------------
+ // Custom Rectangles/Glyphs API
+ //-------------------------------------------
+
+ // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels.
+ // 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.
+ struct CustomRect
+ {
+ unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 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<0x10000): glyph xadvance
+ ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset
+ ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font
+ CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; }
+ bool IsPacked() const { return X != 0xFFFF; }
+ };
+
+ IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. 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 < 0x10000 to register a rectangle to map into a specific font.
+ const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
+
+ // Internals
+ IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max);
+ IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
+
+ //-------------------------------------------
// Members
- // (Access texture data via GetTexData*() calls which will setup a default font for you.)
- void* TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It ia passed back to you during rendering.
+ //-------------------------------------------
+
+ ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
+ int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
+ int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1.
+
+ // [Internal]
+ // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.
unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight
unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
int TexWidth; // Texture width calculated during Build().
int TexHeight; // Texture height calculated during Build().
- int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
+ ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight)
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.
-
- // Private
+ ImVector CustomRects; // Rectangles for packing custom texture data into the atlas.
ImVector ConfigData; // Internal data
- IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions.
- IMGUI_API void RenderCustomTexData(int pass, void* rects);
+ int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList
};
// Font runtime data and rendering
// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
struct ImFont
{
- struct Glyph
- {
- ImWchar Codepoint;
- float XAdvance;
- float X0, Y0, X1, Y1;
- float U0, V0, U1, V1; // Texture coordinates
- };
-
// Members: Hot ~62/78 bytes
float FontSize; // // Height of characters, set during loading (don't change after loading)
float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale()
ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels
- ImVector Glyphs; // // All glyphs.
- ImVector IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
+ ImVector Glyphs; // // All glyphs.
+ ImVector IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
ImVector IndexLookup; // // Sparse. Index glyphs by Unicode code-point.
- const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar)
- float FallbackXAdvance; // == FallbackGlyph->XAdvance
+ const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar)
+ float FallbackAdvanceX; // == FallbackGlyph->AdvanceX
ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar()
// Members: Cold ~18/26 bytes
@@ -1367,16 +1666,18 @@ struct ImFont
ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData
ImFontAtlas* ContainerAtlas; // // What we has been loaded into
float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
+ int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
// Methods
IMGUI_API ImFont();
IMGUI_API ~ImFont();
- IMGUI_API void Clear();
+ IMGUI_API void ClearOutputData();
IMGUI_API void BuildLookupTable();
- IMGUI_API const Glyph* FindGlyph(ImWchar c) const;
+ IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
IMGUI_API void SetFallbackChar(ImWchar c);
- float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; }
+ float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
bool IsLoaded() const { return ContainerAtlas != NULL; }
+ const char* GetDebugName() const { return ConfigData ? ConfigData->Name : ""; }
// 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.
// 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.
@@ -1385,9 +1686,14 @@ struct ImFont
IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const;
IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;
- // Private
+ // [Internal]
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 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.
+
+#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+ typedef ImFontGlyph Glyph; // OBSOLETE 1.52+
+#endif
};
#if defined(__clang__)
diff --git a/imgui_demo.cpp b/imgui_demo.cpp
index dda0a53db..9c49281fb 100644
--- a/imgui_demo.cpp
+++ b/imgui_demo.cpp
@@ -1,9 +1,22 @@
-// dear imgui, v1.50 WIP
+// dear imgui, v1.54 WIP
// (demo code)
-// Don't remove this file from your project! It is useful reference code that you can execute.
-// You can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui.
-// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow().
+// Message to the person tempted to delete this file when integrating ImGui into their code base:
+// Don't do it! Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to.
+// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow().
+// During development, you can call ImGui::ShowDemoWindow() in your code to learn about various features of ImGui. Have it wired in a debug menu!
+// 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.
+// Note that you can #define IMGUI_DISABLE_DEMO_WINDOWS in imconfig.h for the same effect.
+// If you want to link core ImGui in your final builds but not those demo windows, #define IMGUI_DISABLE_DEMO_WINDOWS in imconfig.h and those functions will be empty.
+// In other situation, when you have ImGui available you probably want this to be available for reference and execution.
+// Thank you,
+// -Your beloved friend, imgui_demo.cpp (that you won't delete)
+
+// Message to beginner C/C++ programmers. About the meaning of 'static': in this demo code, we frequently we use 'static' variables inside functions.
+// We do this as a way to gather code and data in the same place, just to make the demo code faster to read, faster to write, and use less code.
+// A static variable persist across calls, so it is essentially like a global variable but declared inside the scope of the function.
+// 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 threads.
+// This might be a pattern you occasionally want to use in your code, but most of the real data you would be editing is likely to be stored outside your function.
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
@@ -13,7 +26,7 @@
#include // toupper, isprint
#include // sqrtf, powf, cosf, sinf, floorf, ceilf
#include // vsnprintf, sscanf, printf
-#include // NULL, malloc, free, qsort, atoi
+#include // NULL, malloc, free, atoi
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include // intptr_t
#else
@@ -39,25 +52,28 @@
#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
#if (__GNUC__ >= 6)
-#pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on github.
+#pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub.
#endif
#endif
-// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n.
+// Play it nice with Windows users. Notepad in 2017 still doesn't display text data with Unix-style \n.
#ifdef _WIN32
#define IM_NEWLINE "\r\n"
#else
#define IM_NEWLINE "\n"
#endif
-#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B))
//-----------------------------------------------------------------------------
// DEMO CODE
//-----------------------------------------------------------------------------
-#ifndef IMGUI_DISABLE_TEST_WINDOWS
+#if !defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) && defined(IMGUI_DISABLE_TEST_WINDOWS) && !defined(IMGUI_DISABLE_DEMO_WINDOWS) // Obsolete name since 1.53, TEST->DEMO
+#define IMGUI_DISABLE_DEMO_WINDOWS
+#endif
+
+#if !defined(IMGUI_DISABLE_DEMO_WINDOWS)
static void ShowExampleAppConsole(bool* p_open);
static void ShowExampleAppLog(bool* p_open);
@@ -67,7 +83,7 @@ static void ShowExampleAppLongText(bool* p_open);
static void ShowExampleAppAutoResize(bool* p_open);
static void ShowExampleAppConstrainedResize(bool* p_open);
static void ShowExampleAppFixedOverlay(bool* p_open);
-static void ShowExampleAppManipulatingWindowTitle(bool* p_open);
+static void ShowExampleAppWindowTitles(bool* p_open);
static void ShowExampleAppCustomRendering(bool* p_open);
static void ShowExampleAppMainMenuBar();
static void ShowExampleMenuFile();
@@ -88,27 +104,27 @@ static void ShowHelpMarker(const char* desc)
void ImGui::ShowUserGuide()
{
ImGui::BulletText("Double-click on title bar to collapse window.");
- ImGui::BulletText("Click and drag on lower right corner to resize window.");
+ ImGui::BulletText("Click and drag on lower right corner to resize window\n(double-click to auto fit window to its contents).");
ImGui::BulletText("Click and drag on any empty space to move window.");
- ImGui::BulletText("Mouse Wheel to scroll.");
+ ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
+ ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text.");
if (ImGui::GetIO().FontAllowUserScaling)
ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents.");
- ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
- ImGui::BulletText("CTRL+Click on a slider or drag box to input text.");
- ImGui::BulletText(
- "While editing text:\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"
- "- You can apply arithmetic operators +,*,/ on numerical values.\n"
- " Use +- to subtract.\n");
+ ImGui::BulletText("Mouse Wheel to scroll.");
+ ImGui::BulletText("While editing text:\n");
+ ImGui::Indent();
+ ImGui::BulletText("Hold SHIFT or use mouse to select text.");
+ ImGui::BulletText("CTRL+Left/Right to word jump.");
+ ImGui::BulletText("CTRL+A or double-click to select all.");
+ ImGui::BulletText("CTRL+X,CTRL+C,CTRL+V to use clipboard.");
+ ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo.");
+ ImGui::BulletText("ESCAPE to revert.");
+ ImGui::BulletText("You can apply arithmetic operators +,*,/ on numerical values.\nUse +- to subtract.");
+ ImGui::Unindent();
}
// Demonstrate most ImGui features (big function!)
-void ImGui::ShowTestWindow(bool* p_open)
+void ImGui::ShowDemoWindow(bool* p_open)
{
// Examples apps
static bool show_app_main_menu_bar = false;
@@ -120,55 +136,56 @@ void ImGui::ShowTestWindow(bool* p_open)
static bool show_app_auto_resize = false;
static bool show_app_constrained_resize = false;
static bool show_app_fixed_overlay = false;
- static bool show_app_manipulating_window_title = false;
+ static bool show_app_window_titles = false;
static bool show_app_custom_rendering = false;
static bool show_app_style_editor = false;
static bool show_app_metrics = false;
static bool show_app_about = false;
- if (show_app_main_menu_bar) ShowExampleAppMainMenuBar();
- if (show_app_console) ShowExampleAppConsole(&show_app_console);
- if (show_app_log) ShowExampleAppLog(&show_app_log);
- if (show_app_layout) ShowExampleAppLayout(&show_app_layout);
- if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor);
- if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text);
- if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize);
- if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize);
- if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay);
- if (show_app_manipulating_window_title) ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title);
- if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering);
+ if (show_app_main_menu_bar) ShowExampleAppMainMenuBar();
+ if (show_app_console) ShowExampleAppConsole(&show_app_console);
+ if (show_app_log) ShowExampleAppLog(&show_app_log);
+ if (show_app_layout) ShowExampleAppLayout(&show_app_layout);
+ if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor);
+ if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text);
+ if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize);
+ if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize);
+ if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay);
+ if (show_app_window_titles) ShowExampleAppWindowTitles(&show_app_window_titles);
+ if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering);
- 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_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::Begin("About ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize);
- ImGui::Text("dear imgui, %s", ImGui::GetVersion());
+ ImGui::Begin("About Dear ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize);
+ ImGui::Text("Dear ImGui, %s", ImGui::GetVersion());
ImGui::Separator();
- ImGui::Text("By Omar Cornut and all github contributors.");
- ImGui::Text("ImGui is licensed under the MIT License, see LICENSE for more information.");
+ ImGui::Text("By Omar Cornut and all dear imgui contributors.");
+ ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information.");
ImGui::End();
}
static bool no_titlebar = false;
- static bool no_border = true;
- static bool no_resize = false;
- static bool no_move = false;
static bool no_scrollbar = false;
- static bool no_collapse = false;
static bool no_menu = false;
+ static bool no_move = false;
+ static bool no_resize = false;
+ static bool no_collapse = false;
+ static bool no_close = false;
// Demonstrate the various window flags. Typically you would just use the default.
ImGuiWindowFlags window_flags = 0;
if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar;
- if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders;
- if (no_resize) window_flags |= ImGuiWindowFlags_NoResize;
- if (no_move) window_flags |= ImGuiWindowFlags_NoMove;
if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar;
- if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse;
if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar;
- ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiSetCond_FirstUseEver);
+ if (no_move) window_flags |= ImGuiWindowFlags_NoMove;
+ if (no_resize) window_flags |= ImGuiWindowFlags_NoResize;
+ if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse;
+ if (no_close) p_open = NULL; // Don't pass our bool* to Begin
+
+ ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("ImGui Demo", p_open, window_flags))
{
// Early out if the window is collapsed, as an optimization.
@@ -179,7 +196,7 @@ void ImGui::ShowTestWindow(bool* p_open)
//ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels
ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels
- ImGui::Text("Dear ImGui says hello.");
+ ImGui::Text("dear imgui says hello. (%s)", IMGUI_VERSION);
// Menu
if (ImGui::BeginMenuBar())
@@ -200,7 +217,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize);
ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize);
ImGui::MenuItem("Simple overlay", NULL, &show_app_fixed_overlay);
- ImGui::MenuItem("Manipulating window title", NULL, &show_app_manipulating_window_title);
+ ImGui::MenuItem("Manipulating window titles", NULL, &show_app_window_titles);
ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering);
ImGui::EndMenu();
}
@@ -208,7 +225,7 @@ void ImGui::ShowTestWindow(bool* p_open)
{
ImGui::MenuItem("Metrics", NULL, &show_app_metrics);
ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor);
- ImGui::MenuItem("About ImGui", NULL, &show_app_about);
+ ImGui::MenuItem("About Dear ImGui", NULL, &show_app_about);
ImGui::EndMenu();
}
ImGui::EndMenuBar();
@@ -217,19 +234,20 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::Spacing();
if (ImGui::CollapsingHeader("Help"))
{
- ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:");
+ ImGui::TextWrapped("This window is being created by the ShowDemoWindow() function. Please refer to the code in imgui_demo.cpp for reference.\n\n");
+ ImGui::Text("USER GUIDE:");
ImGui::ShowUserGuide();
}
if (ImGui::CollapsingHeader("Window options"))
{
ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150);
- ImGui::Checkbox("No border", &no_border); ImGui::SameLine(300);
- ImGui::Checkbox("No resize", &no_resize);
- ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150);
ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300);
- ImGui::Checkbox("No collapse", &no_collapse);
ImGui::Checkbox("No menu", &no_menu);
+ ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150);
+ ImGui::Checkbox("No resize", &no_resize); ImGui::SameLine(300);
+ ImGui::Checkbox("No collapse", &no_collapse);
+ ImGui::Checkbox("No close", &no_close);
if (ImGui::TreeNode("Style"))
{
@@ -237,7 +255,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::TreePop();
}
- if (ImGui::TreeNode("Logging"))
+ 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. You can also call ImGui::LogText() to output directly to the log without a visual output.");
ImGui::LogButtons();
@@ -247,6 +265,145 @@ void ImGui::ShowTestWindow(bool* p_open)
if (ImGui::CollapsingHeader("Widgets"))
{
+ if (ImGui::TreeNode("Basic"))
+ {
+ static int clicked = 0;
+ if (ImGui::Button("Button"))
+ clicked++;
+ if (clicked & 1)
+ {
+ ImGui::SameLine();
+ ImGui::Text("Thanks for clicking me!");
+ }
+
+ static bool check = true;
+ ImGui::Checkbox("checkbox", &check);
+
+ static int e = 0;
+ ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine();
+ ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine();
+ ImGui::RadioButton("radio c", &e, 2);
+
+ // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style.
+ for (int i = 0; i < 7; i++)
+ {
+ 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::Button("Click");
+ ImGui::PopStyleColor(3);
+ ImGui::PopID();
+ }
+
+ ImGui::Text("Hover over me");
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("I am a tooltip");
+
+ ImGui::SameLine();
+ ImGui::Text("- or me");
+ if (ImGui::IsItemHovered())
+ {
+ ImGui::BeginTooltip();
+ ImGui::Text("I am a fancy tooltip");
+ static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
+ ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr));
+ ImGui::EndTooltip();
+ }
+
+ // Testing ImGuiOnceUponAFrame helper.
+ //static ImGuiOnceUponAFrame once;
+ //for (int i = 0; i < 5; i++)
+ // if (once)
+ // ImGui::Text("This will be displayed only once.");
+
+ ImGui::Separator();
+
+ ImGui::LabelText("label", "Value");
+
+ {
+ // Simplified one-liner Combo() API, using values packed in a single constant string
+ static int current_item_1 = 1;
+ ImGui::Combo("combo", ¤t_item_1, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
+ //ImGui::Combo("combo w/ array of char*", ¤t_item_2_idx, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that.
+
+ // General BeginCombo() API, you have full control over your selection data and display type
+ const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO", "PPPP", "QQQQQQQQQQ", "RRR", "SSSS" };
+ static const char* current_item_2 = NULL;
+ if (ImGui::BeginCombo("combo 2", current_item_2)) // The second parameter is the label previewed before opening the combo.
+ {
+ for (int n = 0; n < IM_ARRAYSIZE(items); n++)
+ {
+ bool is_selected = (current_item_2 == items[n]); // You can store your selection however you want, outside or inside your objects
+ if (ImGui::Selectable(items[n], is_selected))
+ current_item_2 = items[n];
+ if (is_selected)
+ ImGui::SetItemDefaultFocus(); // Set the initial focus when opening the combo (scrolling + for keyboard navigation support in the upcoming navigation branch)
+ }
+ ImGui::EndCombo();
+ }
+ }
+
+ {
+ static char str0[128] = "Hello, world!";
+ static int i0=123;
+ static float f0=0.001f;
+ ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
+ ImGui::SameLine(); ShowHelpMarker("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");
+
+ ImGui::InputInt("input int", &i0);
+ ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n");
+
+ ImGui::InputFloat("input float", &f0, 0.01f, 1.0f);
+
+ static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
+ ImGui::InputFloat3("input float3", vec4a);
+ }
+
+ {
+ static int i1=50, i2=42;
+ ImGui::DragInt("drag int", &i1, 1);
+ ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value.");
+
+ ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%");
+
+ 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;
+ ImGui::SliderInt("slider int", &i1, -1, 3);
+ ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value.");
+
+ static float f1=0.123f, f2=0.0f;
+ ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
+ ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f);
+ static float angle = 0.0f;
+ ImGui::SliderAngle("slider angle", &angle);
+ }
+
+ 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(); ShowHelpMarker("Click on the colored square to open a color picker.\nRight-click on the colored square to show options.\nCTRL+click on individual component to input value.\n");
+
+ ImGui::ColorEdit4("color 2", col2);
+
+ 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);
+
+ //static int listbox_item_current2 = 2;
+ //ImGui::PushItemWidth(-1);
+ //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
+ //ImGui::PopItemWidth();
+
+ ImGui::TreePop();
+ }
+
if (ImGui::TreeNode("Trees"))
{
if (ImGui::TreeNode("Basic trees"))
@@ -256,7 +413,7 @@ void ImGui::ShowTestWindow(bool* p_open)
{
ImGui::Text("blah blah");
ImGui::SameLine();
- if (ImGui::SmallButton("print")) printf("Child %d pressed", i);
+ if (ImGui::SmallButton("button")) { };
ImGui::TreePop();
}
ImGui::TreePop();
@@ -293,7 +450,8 @@ void ImGui::ShowTestWindow(bool* p_open)
else
{
// Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text().
- ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i);
+ node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet
+ ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i);
if (ImGui::IsItemClicked())
node_clicked = i;
}
@@ -317,14 +475,16 @@ void ImGui::ShowTestWindow(bool* p_open)
if (ImGui::TreeNode("Collapsing Headers"))
{
static bool closable_group = true;
+ ImGui::Checkbox("Enable extra group", &closable_group);
if (ImGui::CollapsingHeader("Header"))
{
- ImGui::Checkbox("Enable extra group", &closable_group);
+ ImGui::Text("IsItemHovered: %d", IsItemHovered());
for (int i = 0; i < 5; i++)
ImGui::Text("Some content %d", i);
}
if (ImGui::CollapsingHeader("Header with a close button", &closable_group))
{
+ ImGui::Text("IsItemHovered: %d", IsItemHovered());
for (int i = 0; i < 5; i++)
ImGui::Text("More content %d", i);
}
@@ -340,79 +500,95 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::TreePop();
}
- if (ImGui::TreeNode("Colored Text"))
+ if (ImGui::TreeNode("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::TextDisabled("Disabled");
- ImGui::TreePop();
- }
+ 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::TextDisabled("Disabled");
+ ImGui::SameLine(); ShowHelpMarker("The TextDisabled color is stored in ImGuiStyle.");
+ ImGui::TreePop();
+ }
- if (ImGui::TreeNode("Word Wrapping"))
- {
- // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.
- ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.");
- ImGui::Spacing();
+ if (ImGui::TreeNode("Word Wrapping"))
+ {
+ // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.
+ ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.");
+ ImGui::Spacing();
- static float wrap_width = 200.0f;
- ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f");
+ 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 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();
+ 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();
- ImGui::TreePop();
- }
+ ImGui::TreePop();
+ }
- if (ImGui::TreeNode("UTF-8 Text"))
- {
- // UTF-8 test with Japanese characters
- // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html)
- // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature')
- // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants.
- // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system!
- // Note that characters values are preserved even 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->LoadFromFileTTF() manually to load extra character ranges.");
- ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)");
- 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";
- ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf));
+ if (ImGui::TreeNode("UTF-8 Text"))
+ {
+ // UTF-8 test with Japanese characters
+ // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html)
+ // - 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')
+ // - HOWEVER, FOR THIS DEMO FILE, BECAUSE WE WANT TO SUPPORT COMPILER, WE ARE *NOT* INCLUDING RAW UTF-8 CHARACTERS IN THIS SOURCE FILE.
+ // Instead we are encoding a few string with hexadecimal constants. Don't do this 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->LoadFromFileTTF() manually to load extra character ranges.");
+ ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)");
+ 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"; // "nihongo"
+ ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf));
+ ImGui::TreePop();
+ }
ImGui::TreePop();
}
if (ImGui::TreeNode("Images"))
{
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!");
- ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos();
- float tex_w = (float)ImGui::GetIO().Fonts->TexWidth;
- float tex_h = (float)ImGui::GetIO().Fonts->TexHeight;
- ImTextureID tex_id = ImGui::GetIO().Fonts->TexID;
- ImGui::Text("%.0fx%.0f", tex_w, tex_h);
- ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128));
+ ImGuiIO& io = ImGui::GetIO();
+
+ // 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_glfw_gl3.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().
+ 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), ImColor(255,255,255,255), ImColor(255,255,255,128));
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
float focus_sz = 32.0f;
- float focus_x = ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > tex_w - focus_sz) focus_x = tex_w - focus_sz;
- float focus_y = ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > tex_h - focus_sz) focus_y = tex_h - focus_sz;
+ float focus_x = io.MousePos.x - pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > my_tex_w - focus_sz) focus_x = my_tex_w - focus_sz;
+ float focus_y = io.MousePos.y - pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > my_tex_h - focus_sz) focus_y = my_tex_h - focus_sz;
ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y);
ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz);
- ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h);
- ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h);
- ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128));
+ ImVec2 uv0 = ImVec2((focus_x) / my_tex_w, (focus_y) / my_tex_h);
+ ImVec2 uv1 = ImVec2((focus_x + focus_sz) / my_tex_w, (focus_y + focus_sz) / my_tex_h);
+ ImGui::Image(my_tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128));
ImGui::EndTooltip();
}
ImGui::TextWrapped("And now some textured buttons..");
@@ -421,7 +597,7 @@ void ImGui::ShowTestWindow(bool* p_open)
{
ImGui::PushID(i);
int frame_padding = -1 + i; // -1 = uses default padding
- if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding, ImColor(0,0,0,255)))
+ if (ImGui::ImageButton(my_tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/my_tex_w,32/my_tex_h), frame_padding, ImColor(0,0,0,255)))
pressed_count += 1;
ImGui::PopID();
ImGui::SameLine();
@@ -433,24 +609,58 @@ void ImGui::ShowTestWindow(bool* p_open)
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* 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).
if (ImGui::TreeNode("Basic"))
{
- static bool selected[4] = { false, true, false, false };
- ImGui::Selectable("1. I am selectable", &selected[0]);
- ImGui::Selectable("2. I am selectable", &selected[1]);
+ static bool selection[5] = { false, true, false, false, false };
+ ImGui::Selectable("1. I am selectable", &selection[0]);
+ ImGui::Selectable("2. I am selectable", &selection[1]);
ImGui::Text("3. I am not selectable");
- ImGui::Selectable("4. I am selectable", &selected[2]);
- if (ImGui::Selectable("5. I am double clickable", selected[3], ImGuiSelectableFlags_AllowDoubleClick))
+ ImGui::Selectable("4. I am selectable", &selection[3]);
+ if (ImGui::Selectable("5. I am double clickable", selection[4], ImGuiSelectableFlags_AllowDoubleClick))
if (ImGui::IsMouseDoubleClicked(0))
- selected[3] = !selected[3];
+ selection[4] = !selection[4];
ImGui::TreePop();
}
- if (ImGui::TreeNode("Rendering more text into the same block"))
+ if (ImGui::TreeNode("Selection State: Single Selection"))
{
+ static int selected = -1;
+ for (int n = 0; n < 5; n++)
+ {
+ char buf[32];
+ sprintf(buf, "Object %d", n);
+ if (ImGui::Selectable(buf, selected == n))
+ selected = n;
+ }
+ ImGui::TreePop();
+ }
+ if (ImGui::TreeNode("Selection State: Multiple Selection"))
+ {
+ ShowHelpMarker("Hold CTRL and click to select multiple items.");
+ static bool selection[5] = { false, false, false, false, false };
+ for (int n = 0; n < 5; n++)
+ {
+ char buf[32];
+ sprintf(buf, "Object %d", n);
+ if (ImGui::Selectable(buf, selection[n]))
+ {
+ if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held
+ memset(selection, 0, sizeof(selection));
+ selection[n] ^= 1;
+ }
+ }
+ ImGui::TreePop();
+ }
+ 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.
static bool selected[3] = { false, false, false };
- ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
+ 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");
- ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
+ ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
ImGui::TreePop();
}
if (ImGui::TreeNode("In columns"))
@@ -529,143 +739,219 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::TreePop();
}
- static bool a=false;
- if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; }
- if (a)
+ if (ImGui::TreeNode("Plots widgets"))
{
- ImGui::SameLine();
- ImGui::Text("Thanks for clicking me!");
- }
+ static bool animate = true;
+ ImGui::Checkbox("Animate", &animate);
- static bool check = true;
- ImGui::Checkbox("checkbox", &check);
-
- static int e = 0;
- ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine();
- ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine();
- ImGui::RadioButton("radio c", &e, 2);
-
- // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style.
- for (int i = 0; i < 7; i++)
- {
- if (i > 0) ImGui::SameLine();
- ImGui::PushID(i);
- ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f));
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f));
- ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f));
- ImGui::Button("Click");
- ImGui::PopStyleColor(3);
- ImGui::PopID();
- }
-
- ImGui::Text("Hover over me");
- if (ImGui::IsItemHovered())
- ImGui::SetTooltip("I am a tooltip");
-
- ImGui::SameLine();
- ImGui::Text("- or me");
- if (ImGui::IsItemHovered())
- {
- ImGui::BeginTooltip();
- ImGui::Text("I am a fancy tooltip");
static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
- ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr));
- ImGui::EndTooltip();
+ 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.
+ static float values[90] = { 0 };
+ static int values_offset = 0;
+ static float refresh_time = 0.0f;
+ if (!animate || refresh_time == 0.0f)
+ refresh_time = ImGui::GetTime();
+ while (refresh_time < ImGui::GetTime()) // Create dummy data at fixed 60 hz rate for the demo
+ {
+ static float phase = 0.0f;
+ values[values_offset] = cosf(phase);
+ values_offset = (values_offset+1) % IM_ARRAYSIZE(values);
+ phase += 0.10f*values_offset;
+ refresh_time += 1.0f/60.0f;
+ }
+ ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80));
+ ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80));
+
+ // 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.
+ struct Funcs
+ {
+ static float Sin(void*, int i) { return sinf(i * 0.1f); }
+ static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; }
+ };
+ static int func_type = 0, display_count = 70;
+ ImGui::Separator();
+ ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth();
+ 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::Separator();
+
+ // Animate a simple progress bar
+ static float progress = 0.0f, progress_dir = 1.0f;
+ if (animate)
+ {
+ progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime;
+ if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; }
+ if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; }
+ }
+
+ // Typically we would use ImVec2(-1.0f,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::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;
+ char buf[32];
+ sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753);
+ ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf);
+ ImGui::TreePop();
}
- // Testing IMGUI_ONCE_UPON_A_FRAME macro
- //for (int i = 0; i < 5; i++)
- //{
- // IMGUI_ONCE_UPON_A_FRAME
- // {
- // ImGui::Text("This will be displayed only once.");
- // }
- //}
-
- ImGui::Separator();
-
- ImGui::LabelText("label", "Value");
-
- static int item = 1;
- ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); // Combo using values packed in a single constant string (for really quick combo)
-
- const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" };
- static int item2 = -1;
- ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that.
-
+ if (ImGui::TreeNode("Color/Picker Widgets"))
{
- static char str0[128] = "Hello, world!";
- static int i0=123;
- static float f0=0.001f;
- ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
- ImGui::SameLine(); ShowHelpMarker("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");
+ static ImVec4 color = ImColor(114, 144, 154, 200);
- ImGui::InputInt("input int", &i0);
- ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n");
+ static bool alpha_preview = true;
+ static bool alpha_half_preview = false;
+ static bool options_menu = true;
+ static bool hdr = false;
+ ImGui::Checkbox("With Alpha Preview", &alpha_preview);
+ ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview);
+ ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); ShowHelpMarker("Right-click on the individual color widget to show options.");
+ ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); ShowHelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
+ int misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
- ImGui::InputFloat("input float", &f0, 0.01f, 1.0f);
+ ImGui::Text("Color widget:");
+ ImGui::SameLine(); ShowHelpMarker("Click on the colored square to open a color picker.\nCTRL+click on individual component to input value.\n");
+ ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags);
- static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
- ImGui::InputFloat3("input float3", vec4a);
+ ImGui::Text("Color widget HSV with Alpha:");
+ ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_HSV | misc_flags);
+
+ ImGui::Text("Color widget with Float Display:");
+ ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);
+
+ ImGui::Text("Color button with Picker:");
+ ImGui::SameLine(); ShowHelpMarker("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::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);
+
+ ImGui::Text("Color button with Custom Picker Popup:");
+
+ // Generate a dummy palette
+ static bool saved_palette_inited = false;
+ static ImVec4 saved_palette[32];
+ if (!saved_palette_inited)
+ 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);
+ saved_palette[n].w = 1.0f; // Alpha
+ }
+ saved_palette_inited = true;
+
+ static ImVec4 backup_color;
+ bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags);
+ ImGui::SameLine();
+ open_popup |= ImGui::Button("Palette");
+ if (open_popup)
+ {
+ ImGui::OpenPopup("mypicker");
+ backup_color = color;
+ }
+ if (ImGui::BeginPopup("mypicker"))
+ {
+ // FIXME: Adding a drag and drop example here would be perfect!
+ ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!");
+ ImGui::Separator();
+ ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview);
+ ImGui::SameLine();
+ ImGui::BeginGroup();
+ ImGui::Text("Current");
+ 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)))
+ color = backup_color;
+ ImGui::Separator();
+ ImGui::Text("Palette");
+ for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
+ {
+ 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)))
+ color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha!
+
+ if (ImGui::BeginDragDropTarget())
+ {
+ if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
+ memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3);
+ if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
+ memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4);
+ EndDragDropTarget();
+ }
+
+ ImGui::PopID();
+ }
+ ImGui::EndGroup();
+ ImGui::EndPopup();
+ }
+
+ ImGui::Text("Color button only:");
+ ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags, 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 int inputs_mode = 2;
+ static int picker_mode = 0;
+ ImGui::Checkbox("With Alpha", &alpha);
+ ImGui::Checkbox("With Alpha Bar", &alpha_bar);
+ ImGui::Checkbox("With Side Preview", &side_preview);
+ if (side_preview)
+ {
+ ImGui::SameLine();
+ ImGui::Checkbox("With Ref Color", &ref_color);
+ if (ref_color)
+ {
+ ImGui::SameLine();
+ ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags);
+ }
+ }
+ ImGui::Combo("Inputs Mode", &inputs_mode, "All Inputs\0No Inputs\0RGB Input\0HSV Input\0HEX Input\0");
+ ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0");
+ ImGui::SameLine(); ShowHelpMarker("User can right-click the picker to change mode.");
+ ImGuiColorEditFlags flags = misc_flags;
+ if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4()
+ if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar;
+ if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview;
+ if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar;
+ if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel;
+ if (inputs_mode == 1) flags |= ImGuiColorEditFlags_NoInputs;
+ if (inputs_mode == 2) flags |= ImGuiColorEditFlags_RGB;
+ if (inputs_mode == 3) flags |= ImGuiColorEditFlags_HSV;
+ if (inputs_mode == 4) flags |= ImGuiColorEditFlags_HEX;
+ ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL);
+
+ ImGui::Text("Programmatically set defaults/options:");
+ ImGui::SameLine(); ShowHelpMarker("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.");
+ if (ImGui::Button("Uint8 + HSV"))
+ ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_HSV);
+ ImGui::SameLine();
+ if (ImGui::Button("Float + HDR"))
+ ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_RGB);
+
+ ImGui::TreePop();
}
- {
- static int i1=50, i2=42;
- ImGui::DragInt("drag int", &i1, 1);
- ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value.");
-
- ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%");
-
- 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;
- ImGui::SliderInt("slider int", &i1, -1, 3);
- ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value.");
-
- static float f1=0.123f, f2=0.0f;
- ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
- ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f);
- static float angle = 0.0f;
- ImGui::SliderAngle("slider angle", &angle);
- }
-
- 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(); ShowHelpMarker("Click on the colored square to change edit mode.\nCTRL+click on individual component to input value.\n");
-
- ImGui::ColorEdit4("color 2", col2);
-
- 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);
-
- //static int listbox_item_current2 = 2;
- //ImGui::PushItemWidth(-1);
- //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
- //ImGui::PopItemWidth();
-
if (ImGui::TreeNode("Range Widgets"))
{
- ImGui::Unindent();
-
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::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %.0f units", "Max: %.0f units");
-
- ImGui::Indent();
ImGui::TreePop();
}
if (ImGui::TreeNode("Multi-component Widgets"))
{
- ImGui::Unindent();
-
static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
static int vec4i[4] = { 1, 5, 100, 255 };
@@ -692,13 +978,11 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::DragInt4("drag int4", vec4i, 1, 0, 255);
ImGui::SliderInt4("slider int4", vec4i, 0, 255);
- ImGui::Indent();
ImGui::TreePop();
}
if (ImGui::TreeNode("Vertical Sliders"))
{
- ImGui::Unindent();
const float spacing = 4;
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));
@@ -712,10 +996,10 @@ void ImGui::ShowTestWindow(bool* p_open)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
- ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f));
- ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f));
- ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f));
- ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f));
+ 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]);
@@ -758,79 +1042,17 @@ void ImGui::ShowTestWindow(bool* p_open)
}
ImGui::PopID();
ImGui::PopStyleVar();
-
- ImGui::Indent();
ImGui::TreePop();
}
}
- if (ImGui::CollapsingHeader("Graphs widgets"))
- {
- static bool animate = true;
- ImGui::Checkbox("Animate", &animate);
-
- 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.
- static float values[90] = { 0 };
- static int values_offset = 0;
- if (animate)
- {
- static float refresh_time = ImGui::GetTime(); // Create dummy data at fixed 60 hz rate for the demo
- for (; ImGui::GetTime() > refresh_time + 1.0f/60.0f; refresh_time += 1.0f/60.0f)
- {
- static float phase = 0.0f;
- values[values_offset] = cosf(phase);
- values_offset = (values_offset+1) % IM_ARRAYSIZE(values);
- phase += 0.10f*values_offset;
- }
- }
- ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80));
- ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80));
-
- // 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.
- struct Funcs
- {
- static float Sin(void*, int i) { return sinf(i * 0.1f); }
- static float Saw(void*, int i) { return (i & 1) ? 1.0f : 0.0f; }
- };
- static int func_type = 0, display_count = 70;
- ImGui::Separator();
- ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth();
- 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::Separator();
-
- // Animate a simple progress bar
- static float progress = 0.0f, progress_dir = 1.0f;
- if (animate)
- {
- progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime;
- if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; }
- if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; }
- }
-
- // Typically we would use ImVec2(-1.0f,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::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;
- char buf[32];
- sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753);
- ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf);
- }
-
if (ImGui::CollapsingHeader("Layout"))
{
if (ImGui::TreeNode("Child regions"))
{
+ static bool disable_mouse_wheel = false;
+ ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel);
+
ImGui::Text("Without border");
static int line = 50;
bool goto_line = ImGui::Button("Goto");
@@ -838,33 +1060,40 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::PushItemWidth(100);
goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue);
ImGui::PopItemWidth();
- ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f,300), false, ImGuiWindowFlags_HorizontalScrollbar);
- for (int i = 0; i < 100; i++)
+
+ // Child 1: no border, enable horizontal scrollbar
{
- ImGui::Text("%04d: scrollable region", i);
- if (goto_line && line == i)
+ ImGui::BeginChild("Child1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 300), false, ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0));
+ for (int i = 0; i < 100; i++)
+ {
+ ImGui::Text("%04d: scrollable region", i);
+ if (goto_line && line == i)
+ ImGui::SetScrollHere();
+ }
+ if (goto_line && line >= 100)
ImGui::SetScrollHere();
+ ImGui::EndChild();
}
- if (goto_line && line >= 100)
- ImGui::SetScrollHere();
- ImGui::EndChild();
ImGui::SameLine();
- ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f);
- ImGui::BeginChild("Sub2", ImVec2(0,300), true);
- ImGui::Text("With border");
- ImGui::Columns(2);
- for (int i = 0; i < 100; i++)
+ // Child 2: rounded border
{
- if (i == 50)
- ImGui::NextColumn();
- char buf[32];
- sprintf(buf, "%08x", i*5731);
- ImGui::Button(buf, ImVec2(-1.0f, 0.0f));
+ ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
+ ImGui::BeginChild("Child2", ImVec2(0,300), true, (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0));
+ ImGui::Text("With border");
+ ImGui::Columns(2);
+ for (int i = 0; i < 100; i++)
+ {
+ if (i == 50)
+ ImGui::NextColumn();
+ char buf[32];
+ sprintf(buf, "%08x", i*5731);
+ ImGui::Button(buf, ImVec2(-1.0f, 0.0f));
+ }
+ ImGui::EndChild();
+ ImGui::PopStyleVar();
}
- ImGui::EndChild();
- ImGui::PopStyleVar();
ImGui::TreePop();
}
@@ -918,7 +1147,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::TextColored(ImVec4(1,1,0,1), "Sailor");
// Button
- ImGui::AlignFirstTextHeightToWidgets();
+ ImGui::AlignTextToFramePadding();
ImGui::Text("Normal buttons"); ImGui::SameLine();
ImGui::Button("Banana"); ImGui::SameLine();
ImGui::Button("Apple"); ImGui::SameLine();
@@ -991,11 +1220,11 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::Button("CCC");
ImGui::Button("DDD");
ImGui::EndGroup();
- if (ImGui::IsItemHovered())
- ImGui::SetTooltip("Group hovered");
ImGui::SameLine();
ImGui::Button("EEE");
ImGui::EndGroup();
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("First group hovered");
}
// Capture the group size and create widgets using the same size
ImVec2 size = ImGui::GetItemRectSize();
@@ -1044,11 +1273,12 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::Text("TEST"); ImGui::SameLine();
ImGui::SmallButton("TEST##2");
- ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets.
+ ImGui::AlignTextToFramePadding(); // If your line starts with text, call this to align it to upcoming widgets.
ImGui::Text("Text aligned to Widget"); ImGui::SameLine();
ImGui::Button("Widget##1"); ImGui::SameLine();
ImGui::Text("Widget"); ImGui::SameLine();
- ImGui::SmallButton("Widget##2");
+ ImGui::SmallButton("Widget##2"); ImGui::SameLine();
+ ImGui::Button("Widget##3");
// Tree
const float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
@@ -1056,7 +1286,7 @@ void ImGui::ShowTestWindow(bool* p_open)
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
- ImGui::AlignFirstTextHeightToWidgets(); // 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(); // 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.
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
@@ -1066,7 +1296,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::SameLine(0.0f, spacing);
ImGui::BulletText("Bullet text");
- ImGui::AlignFirstTextHeightToWidgets();
+ ImGui::AlignTextToFramePadding();
ImGui::BulletText("Node");
ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4");
@@ -1080,9 +1310,9 @@ void ImGui::ShowTestWindow(bool* p_open)
static int track_line = 50, scroll_to_px = 200;
ImGui::Checkbox("Track", &track);
ImGui::PushItemWidth(100);
- ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line %.0f");
- bool scroll_to = ImGui::Button("Scroll To");
- ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "y = %.0f px");
+ ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line = %.0f");
+ bool scroll_to = ImGui::Button("Scroll To Pos");
+ ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "Y = %.0f px");
ImGui::PopItemWidth();
if (scroll_to) track = false;
@@ -1106,7 +1336,9 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::Text("Line %d", line);
}
}
+ float scroll_y = ImGui::GetScrollY(), scroll_max_y = ImGui::GetScrollMaxY();
ImGui::EndChild();
+ ImGui::Text("%.0f/%0.f", scroll_y, scroll_max_y);
ImGui::EndGroup();
}
ImGui::TreePop();
@@ -1120,7 +1352,7 @@ void ImGui::ShowTestWindow(bool* p_open)
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::GetItemsLineHeightWithSpacing()*7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar);
+ ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetFrameHeightWithSpacing()*7 + 30), 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
@@ -1131,22 +1363,25 @@ void ImGui::ShowTestWindow(bool* p_open)
if (n > 0) ImGui::SameLine();
ImGui::PushID(n + line * 1000);
char num_buf[16];
- const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : (sprintf(num_buf, "%d", n), num_buf);
+ sprintf(num_buf, "%d", n);
+ const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : num_buf;
float hue = n*0.05f;
- ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(hue, 0.6f, 0.6f));
- ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(hue, 0.7f, 0.7f));
- ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(hue, 0.8f, 0.8f));
+ 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));
ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f));
ImGui::PopStyleColor(3);
ImGui::PopID();
}
}
+ float scroll_x = ImGui::GetScrollX(), scroll_max_x = ImGui::GetScrollMaxX();
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::Text("Scroll from code"); ImGui::SameLine();
- ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f;
+ 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::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)
@@ -1166,8 +1401,8 @@ void ImGui::ShowTestWindow(bool* p_open)
ImVec4 clip_rect(pos.x, pos.y, pos.x+size.x, pos.y+size.y);
ImGui::InvisibleButton("##dummy", size);
if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { 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), ImColor(90,90,120,255));
- ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), ImColor(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect);
+ 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::TreePop();
}
}
@@ -1187,7 +1422,7 @@ void ImGui::ShowTestWindow(bool* p_open)
if (ImGui::Button("Select.."))
ImGui::OpenPopup("select");
ImGui::SameLine();
- ImGui::Text(selected_fish == -1 ? "" : names[selected_fish]);
+ ImGui::TextUnformatted(selected_fish == -1 ? "" : names[selected_fish]);
if (ImGui::BeginPopup("select"))
{
ImGui::Text("Aquarium");
@@ -1240,42 +1475,35 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::EndPopup();
}
- ImGui::Spacing();
- 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.
- ImGui::PushID("foo");
- ImGui::MenuItem("Menu item", "CTRL+M");
- if (ImGui::BeginMenu("Menu inside a regular window"))
- {
- ShowExampleMenuFile();
- ImGui::EndMenu();
- }
- ImGui::PopID();
- ImGui::Separator();
-
ImGui::TreePop();
}
if (ImGui::TreeNode("Context menus"))
{
+ // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing:
+ // if (IsItemHovered() && IsMouseClicked(0))
+ // OpenPopup(id);
+ // return BeginPopup(id);
+ // For more advanced uses you may want to replicate and cuztomize this code. This the comments inside BeginPopupContextItem() implementation.
static float value = 0.5f;
ImGui::Text("Value = %.3f (<-- right-click here)", value);
if (ImGui::BeginPopupContextItem("item context menu"))
{
if (ImGui::Selectable("Set to zero")) value = 0.0f;
if (ImGui::Selectable("Set to PI")) value = 3.1415f;
+ ImGui::PushItemWidth(-1);
+ ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f);
+ ImGui::PopItemWidth();
ImGui::EndPopup();
}
- static ImVec4 color = ImColor(0.8f, 0.5f, 1.0f, 1.0f);
- ImGui::ColorButton(color);
- if (ImGui::BeginPopupContextItem("color context menu"))
+ static char name[32] = "Label1";
+ char buf[64]; sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label
+ ImGui::Button(buf);
+ if (ImGui::BeginPopupContextItem()) // When used after an item that has an ID (here the Button), we can skip providing an ID to BeginPopupContextItem().
{
- ImGui::Text("Edit color");
- ImGui::ColorEdit3("##edit", (float*)&color);
+ ImGui::Text("Edit name:");
+ ImGui::InputText("##edit", name, IM_ARRAYSIZE(name));
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
@@ -1293,7 +1521,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::OpenPopup("Delete?");
if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
- ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
+ ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
ImGui::Separator();
//static int dummy_i = 0;
@@ -1314,13 +1542,17 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::OpenPopup("Stacked 1");
if (ImGui::BeginPopupModal("Stacked 1"))
{
- ImGui::Text("Hello from Stacked The First");
+ ImGui::Text("Hello from Stacked The First\nUsing style.Colors[ImGuiCol_ModalWindowDarkening] for darkening.");
+ static int item = 1;
+ ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
+ static float color[4] = { 0.4f,0.7f,0.0f,0.5f };
+ ImGui::ColorEdit4("color", color); // This is to test behavior of stacked regular popups over a modal
- if (ImGui::Button("Another one.."))
+ if (ImGui::Button("Add another modal.."))
ImGui::OpenPopup("Stacked 2");
if (ImGui::BeginPopupModal("Stacked 2"))
{
- ImGui::Text("Hello from Stacked The Second");
+ ImGui::Text("Hello from Stacked The Second!");
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
@@ -1333,10 +1565,31 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::TreePop();
}
+
+ if (ImGui::TreeNode("Menus inside a regular window"))
+ {
+ 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.
+ ImGui::PushID("foo");
+ ImGui::MenuItem("Menu item", "CTRL+M");
+ if (ImGui::BeginMenu("Menu inside a regular window"))
+ {
+ ShowExampleMenuFile();
+ ImGui::EndMenu();
+ }
+ ImGui::PopID();
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
}
if (ImGui::CollapsingHeader("Columns"))
{
+ ImGui::PushID("Columns");
+
// Basic columns
if (ImGui::TreeNode("Basic"))
{
@@ -1360,7 +1613,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::Text("ID"); ImGui::NextColumn();
ImGui::Text("Name"); ImGui::NextColumn();
ImGui::Text("Path"); ImGui::NextColumn();
- ImGui::Text("Flags"); ImGui::NextColumn();
+ ImGui::Text("Hovered"); ImGui::NextColumn();
ImGui::Separator();
const char* names[3] = { "One", "Two", "Three" };
const char* paths[3] = { "/path/one", "/path/two", "/path/three" };
@@ -1371,19 +1624,89 @@ void ImGui::ShowTestWindow(bool* p_open)
sprintf(label, "%04d", i);
if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns))
selected = i;
+ bool hovered = ImGui::IsItemHovered();
ImGui::NextColumn();
ImGui::Text(names[i]); ImGui::NextColumn();
ImGui::Text(paths[i]); ImGui::NextColumn();
- ImGui::Text("...."); ImGui::NextColumn();
+ ImGui::Text("%d", hovered); ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
+ // Create multiple items in a same cell before switching to next column
+ if (ImGui::TreeNode("Mixed items"))
+ {
+ ImGui::Columns(3, "mixed");
+ ImGui::Separator();
+
+ ImGui::Text("Hello");
+ ImGui::Button("Banana");
+ ImGui::NextColumn();
+
+ ImGui::Text("ImGui");
+ ImGui::Button("Apple");
+ static float foo = 1.0f;
+ ImGui::InputFloat("red", &foo, 0.05f, 0, 3);
+ ImGui::Text("An extra line here.");
+ ImGui::NextColumn();
+
+ ImGui::Text("Sailor");
+ ImGui::Button("Corniflower");
+ static float bar = 1.0f;
+ ImGui::InputFloat("blue", &bar, 0.05f, 0, 3);
+ ImGui::NextColumn();
+
+ if (ImGui::CollapsingHeader("Category A")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
+ if (ImGui::CollapsingHeader("Category B")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
+ if (ImGui::CollapsingHeader("Category C")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ // Word wrapping
+ if (ImGui::TreeNode("Word-wrapping"))
+ {
+ ImGui::Columns(2, "word-wrapping");
+ ImGui::Separator();
+ ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
+ ImGui::TextWrapped("Hello Left");
+ ImGui::NextColumn();
+ ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
+ ImGui::TextWrapped("Hello Right");
+ ImGui::Columns(1);
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
+ if (ImGui::TreeNode("Borders"))
+ {
+ // NB: Future columns API should allow automatic horizontal borders.
+ static bool h_borders = true;
+ static bool v_borders = true;
+ ImGui::Checkbox("horizontal", &h_borders);
+ ImGui::SameLine();
+ ImGui::Checkbox("vertical", &v_borders);
+ ImGui::Columns(4, NULL, v_borders);
+ for (int i = 0; i < 4*3; i++)
+ {
+ if (h_borders && ImGui::GetColumnIndex() == 0)
+ ImGui::Separator();
+ ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i);
+ ImGui::Text("Width %.2f\nOffset %.2f", ImGui::GetColumnWidth(), ImGui::GetColumnOffset());
+ ImGui::NextColumn();
+ }
+ ImGui::Columns(1);
+ if (h_borders)
+ ImGui::Separator();
+ ImGui::TreePop();
+ }
+
// Scrolling columns
/*
- if (ImGui::TreeNode("Scrolling"))
+ if (ImGui::TreeNode("Vertical Scrolling"))
{
ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y));
ImGui::Columns(3);
@@ -1407,73 +1730,29 @@ void ImGui::ShowTestWindow(bool* p_open)
}
*/
- // Create multiple items in a same cell before switching to next column
- if (ImGui::TreeNode("Mixed items"))
+ if (ImGui::TreeNode("Horizontal Scrolling"))
{
- ImGui::Columns(3, "mixed");
- ImGui::Separator();
-
- ImGui::Text("Hello");
- ImGui::Button("Banana");
- ImGui::NextColumn();
-
- ImGui::Text("ImGui");
- ImGui::Button("Apple");
- static float foo = 1.0f;
- ImGui::InputFloat("red", &foo, 0.05f, 0, 3);
- ImGui::Text("An extra line here.");
- ImGui::NextColumn();
-
- ImGui::Text("Sailor");
- ImGui::Button("Corniflower");
- static float bar = 1.0f;
- ImGui::InputFloat("blue", &bar, 0.05f, 0, 3);
- ImGui::NextColumn();
-
- if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn();
- if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn();
- if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn();
- ImGui::Columns(1);
- ImGui::Separator();
- ImGui::TreePop();
- }
-
- // Word wrapping
- if (ImGui::TreeNode("Word-wrapping"))
- {
- ImGui::Columns(2, "word-wrapping");
- ImGui::Separator();
- ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
- ImGui::TextWrapped("Hello Left");
- ImGui::NextColumn();
- ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
- ImGui::TextWrapped("Hello Right");
- ImGui::Columns(1);
- ImGui::Separator();
- ImGui::TreePop();
- }
-
- if (ImGui::TreeNode("Borders"))
- {
- static bool h_borders = true;
- static bool v_borders = true;
- ImGui::Checkbox("horizontal", &h_borders);
- ImGui::SameLine();
- ImGui::Checkbox("vertical", &v_borders);
- ImGui::Columns(4, NULL, v_borders);
- if (h_borders) ImGui::Separator();
- for (int i = 0; i < 8; i++)
+ ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f));
+ ImGui::BeginChild("##ScrollingRegion", ImVec2(0, ImGui::GetFontSize() * 20), false, ImGuiWindowFlags_HorizontalScrollbar);
+ ImGui::Columns(10);
+ int ITEMS_COUNT = 2000;
+ ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list
+ while (clipper.Step())
{
- ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i);
- ImGui::NextColumn();
+ for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
+ for (int j = 0; j < 10; j++)
+ {
+ ImGui::Text("Line %d Column %d...", i, j);
+ ImGui::NextColumn();
+ }
}
ImGui::Columns(1);
- if (h_borders) ImGui::Separator();
+ ImGui::EndChild();
ImGui::TreePop();
}
bool node_open = ImGui::TreeNode("Tree within single cell");
- ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell.\nThere's no storage of state per-cell.");
+ ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell. There's no storage of state per-cell.");
if (node_open)
{
ImGui::Columns(2, "tree items");
@@ -1484,6 +1763,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::Separator();
ImGui::TreePop();
}
+ ImGui::PopID();
}
if (ImGui::CollapsingHeader("Filtering"))
@@ -1501,8 +1781,46 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::BulletText("%s", lines[i]);
}
- if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus"))
+ if (ImGui::CollapsingHeader("Inputs & Focus"))
{
+ ImGuiIO& io = ImGui::GetIO();
+ ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
+ ImGui::SameLine(); ShowHelpMarker("Request ImGui to render a mouse cursor for you in software. 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("WantCaptureMouse: %d", io.WantCaptureMouse);
+ ImGui::Text("WantCaptureKeyboard: %d", io.WantCaptureKeyboard);
+ ImGui::Text("WantTextInput: %d", io.WantTextInput);
+ ImGui::Text("WantMoveMouse: %d", io.WantMoveMouse);
+
+ if (ImGui::TreeNode("Keyboard & Mouse State"))
+ {
+ if (ImGui::IsMousePosValid())
+ ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
+ else
+ ImGui::Text("Mouse pos: ");
+ 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 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);
+
+ ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); }
+ ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); }
+ ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); }
+ ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
+
+
+ ImGui::Button("Hovering me sets the\nkeyboard capture flag");
+ if (ImGui::IsItemHovered())
+ ImGui::CaptureKeyboardFromApp(true);
+ ImGui::SameLine();
+ ImGui::Button("Holding me clears the\nthe keyboard capture flag");
+ if (ImGui::IsItemActive())
+ ImGui::CaptureKeyboardFromApp(false);
+
+ ImGui::TreePop();
+ }
+
if (ImGui::TreeNode("Tabbing"))
{
ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields.");
@@ -1539,6 +1857,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 3;
ImGui::PopAllowKeyboardFocus();
+
if (has_focus)
ImGui::Text("Item with focus: %d", has_focus);
else
@@ -1547,65 +1866,104 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::TreePop();
}
+ if (ImGui::TreeNode("Focused & Hovered Test"))
+ {
+ 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("embeddingchild", ImVec2(0, ImGui::GetFontSize() * 25), true);
+
+ // Testing IsWindowFocused() function with its various flags (note that the flags can be combined)
+ ImGui::BulletText(
+ "IsWindowFocused() = %d\n"
+ "IsWindowFocused(_ChildWindows) = %d\n"
+ "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n"
+ "IsWindowFocused(_RootWindow) = %d\n"
+ "IsWindowFocused(_AnyWindow) = %d\n",
+ ImGui::IsWindowFocused(),
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows),
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow),
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow),
+ ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow));
+
+ // Testing IsWindowHovered() function with its various flags (note that the flags can be combined)
+ ImGui::BulletText(
+ "IsWindowHovered() = %d\n"
+ "IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n"
+ "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n"
+ "IsWindowHovered(_ChildWindows) = %d\n"
+ "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n"
+ "IsWindowHovered(_RootWindow) = %d\n"
+ "IsWindowHovered(_AnyWindow) = %d\n",
+ ImGui::IsWindowHovered(),
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows),
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow),
+ ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow));
+
+ // Testing IsItemHovered() function (because BulletText is an item itself and that would affect the output of IsItemHovered, we pass all lines in a single items to shorten the code)
+ ImGui::Button("ITEM");
+ ImGui::BulletText(
+ "IsItemHovered() = %d\n"
+ "IsItemHovered(_AllowWhenBlockedByPopup) = %d\n"
+ "IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n"
+ "IsItemHovered(_AllowWhenOverlapped) = %d\n"
+ "IsItemhovered(_RectOnly) = %d\n",
+ ImGui::IsItemHovered(),
+ ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
+ ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
+ ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlapped),
+ ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly));
+
+ ImGui::BeginChild("child", ImVec2(0,50), true);
+ ImGui::Text("This is another child window for testing IsWindowHovered() flags.");
+ ImGui::EndChild();
+
+ if (embed_all_inside_a_child_window)
+ EndChild();
+
+ ImGui::TreePop();
+ }
+
if (ImGui::TreeNode("Dragging"))
{
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::Button("Drag Me");
if (ImGui::IsItemActive())
{
// Draw a line between the button and the mouse cursor
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->PushClipRectFullScreen();
- draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f);
+ draw_list->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f);
draw_list->PopClipRect();
+
+ // 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 = ImGui::GetIO().MouseDelta;
+ ImVec2 mouse_delta = io.MouseDelta;
ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y);
}
ImGui::TreePop();
}
- if (ImGui::TreeNode("Keyboard & Mouse State"))
- {
- ImGuiIO& io = ImGui::GetIO();
-
- ImGui::Text("MousePos: (%g, %g)", io.MousePos.x, io.MousePos.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 released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
- ImGui::Text("MouseWheel: %.1f", io.MouseWheel);
-
- ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); }
- ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); }
- ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); }
- ImGui::Text("KeyMods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
-
- ImGui::Text("WantCaptureMouse: %s", io.WantCaptureMouse ? "true" : "false");
- ImGui::Text("WantCaptureKeyboard: %s", io.WantCaptureKeyboard ? "true" : "false");
- ImGui::Text("WantTextInput: %s", io.WantTextInput ? "true" : "false");
-
- ImGui::Button("Hovering me sets the\nkeyboard capture flag");
- if (ImGui::IsItemHovered())
- ImGui::CaptureKeyboardFromApp(true);
- ImGui::SameLine();
- ImGui::Button("Holding me clears the\nthe keyboard capture flag");
- if (ImGui::IsItemActive())
- ImGui::CaptureKeyboardFromApp(false);
-
- ImGui::TreePop();
- }
-
if (ImGui::TreeNode("Mouse cursors"))
{
- ImGui::TextWrapped("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software.");
- ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor);
+ const char* mouse_cursors_names[] = { "Arrow", "TextInput", "Move", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE" };
+ IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_Count_);
+
+ ImGui::Text("Current mouse cursor = %d: %s", ImGui::GetMouseCursor(), mouse_cursors_names[ImGui::GetMouseCursor()]);
ImGui::Text("Hover to see mouse cursors:");
+ ImGui::SameLine(); ShowHelpMarker("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];
- sprintf(label, "Mouse cursor %d", i);
+ sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]);
ImGui::Bullet(); ImGui::Selectable(label, false);
if (ImGui::IsItemHovered())
ImGui::SetMouseCursor(i);
@@ -1617,28 +1975,87 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::End();
}
+// 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.
+bool ImGui::ShowStyleSelector(const char* label)
+{
+ static int style_idx = 0;
+ if (ImGui::Combo(label, &style_idx, "Classic\0Dark\0Light\0"))
+ {
+ switch (style_idx)
+ {
+ case 0: ImGui::StyleColorsClassic(); break;
+ case 1: ImGui::StyleColorsDark(); break;
+ case 2: ImGui::StyleColorsLight(); break;
+ }
+ return true;
+ }
+ return false;
+}
+
+// Demo helper function to select among loaded fonts.
+// Here we use the regular BeginCombo()/EndCombo() api which is more the more flexible one.
+void ImGui::ShowFontSelector(const char* label)
+{
+ ImGuiIO& io = ImGui::GetIO();
+ ImFont* font_current = ImGui::GetFont();
+ if (ImGui::BeginCombo(label, font_current->GetDebugName()))
+ {
+ for (int n = 0; n < io.Fonts->Fonts.Size; n++)
+ if (ImGui::Selectable(io.Fonts->Fonts[n]->GetDebugName(), io.Fonts->Fonts[n] == font_current))
+ io.FontDefault = io.Fonts->Fonts[n];
+ ImGui::EndCombo();
+ }
+ ImGui::SameLine();
+ ShowHelpMarker(
+ "- 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 documentation in extra_fonts/ for more details.\n"
+ "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
+}
+
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)
ImGuiStyle& style = ImGui::GetStyle();
+ static ImGuiStyle ref_saved_style;
- // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to the default style)
- const ImGuiStyle default_style; // Default style
- if (ImGui::Button("Revert Style"))
- style = ref ? *ref : default_style;
+ // Default to using internal storage as reference
+ static bool init = true;
+ if (init && ref == NULL)
+ ref_saved_style = style;
+ init = false;
+ if (ref == NULL)
+ ref = &ref_saved_style;
- if (ref)
- {
- ImGui::SameLine();
- if (ImGui::Button("Save Style"))
- *ref = style;
- }
+ ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f);
- ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f);
+ if (ImGui::ShowStyleSelector("Colors##Selector"))
+ ref_saved_style = style;
+ ImGui::ShowFontSelector("Fonts##Selector");
+
+ // Simplified Settings
+ 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; }
+ ImGui::SameLine();
+ { bool frame_border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &frame_border)) style.FrameBorderSize = frame_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; }
+
+ // Save/Revert button
+ if (ImGui::Button("Save Ref"))
+ *ref = ref_saved_style = style;
+ ImGui::SameLine();
+ if (ImGui::Button("Revert Ref"))
+ style = *ref;
+ ImGui::SameLine();
+ ShowHelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. Use \"Export Colors\" below to save them somewhere.");
if (ImGui::TreeNode("Rendering"))
{
- ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines);
- ImGui::Checkbox("Anti-aliased shapes", &style.AntiAliasedShapes);
+ ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); ImGui::SameLine(); ShowHelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.");
+ ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill);
ImGui::PushItemWidth(100);
ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, NULL, 2.0f);
if (style.CurveTessellationTol < 0.0f) style.CurveTessellationTol = 0.10f;
@@ -1650,18 +2067,25 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
if (ImGui::TreeNode("Settings"))
{
ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f");
- ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f");
- ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 16.0f, "%.0f");
ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f");
- ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f");
ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f");
ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f");
ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f");
- ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 16.0f, "%.0f");
ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f");
- ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::Text("BorderSize");
+ ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f");
+ ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f");
+ ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f");
+ ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f");
+ ImGui::Text("Rounding");
+ ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 14.0f, "%.0f");
+ ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 16.0f, "%.0f");
+ ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 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::Text("Alignment");
ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f");
ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a button is larger than its text content.");
@@ -1671,52 +2095,54 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
if (ImGui::TreeNode("Colors"))
{
static int output_dest = 0;
- static bool output_only_modified = false;
- if (ImGui::Button("Copy Colors"))
+ static bool output_only_modified = true;
+ if (ImGui::Button("Export Unsaved"))
{
if (output_dest == 0)
ImGui::LogToClipboard();
else
ImGui::LogToTTY();
- ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" IM_NEWLINE);
+ ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE);
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const ImVec4& col = style.Colors[i];
- const char* name = ImGui::GetStyleColName(i);
- if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0)
- ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 22 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
+ 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::LogFinish();
}
ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); ImGui::PopItemWidth();
- ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified);
+ ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified);
- static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB;
- ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB);
- ImGui::SameLine();
- ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV);
- ImGui::SameLine();
- ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX);
- //ImGui::Text("Tip: Click on colored square to change edit mode.");
+ ImGui::Text("Tip: Left-click on colored square to open color picker,\nRight-click to open edit options menu.");
static ImGuiTextFilter filter;
filter.Draw("Filter colors", 200);
- ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar);
+ static ImGuiColorEditFlags alpha_flags = 0;
+ ImGui::RadioButton("Opaque", &alpha_flags, 0); ImGui::SameLine();
+ ImGui::RadioButton("Alpha", &alpha_flags, ImGuiColorEditFlags_AlphaPreview); ImGui::SameLine();
+ ImGui::RadioButton("Both", &alpha_flags, ImGuiColorEditFlags_AlphaPreviewHalf);
+
+ ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
ImGui::PushItemWidth(-160);
- ImGui::ColorEditMode(edit_mode);
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
- const char* name = ImGui::GetStyleColName(i);
+ const char* name = ImGui::GetStyleColorName(i);
if (!filter.PassFilter(name))
continue;
ImGui::PushID(i);
- ImGui::ColorEdit4(name, (float*)&style.Colors[i], true);
- if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0)
+ ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags);
+ if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0)
{
- ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : default_style.Colors[i];
- if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.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 extra_fonts/README.txt about using icon fonts. It's really easy and super convenient!
+ ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i];
+ ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) style.Colors[i] = ref->Colors[i];
}
+ ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
+ ImGui::TextUnformatted(name);
ImGui::PopID();
}
ImGui::PopItemWidth();
@@ -1725,9 +2151,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::TreePop();
}
- if (ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size))
+ bool fonts_opened = ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size);
+ if (fonts_opened)
{
- ImGui::SameLine(); ShowHelpMarker("Tip: Load fonts with io.Fonts->AddFontFromFileTTF()\nbefore calling io.Fonts->GetTex* functions.");
ImFontAtlas* atlas = ImGui::GetIO().Fonts;
if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
{
@@ -1738,27 +2164,28 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
for (int i = 0; i < atlas->Fonts.Size; i++)
{
ImFont* font = atlas->Fonts[i];
- ImGui::BulletText("Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size);
- ImGui::TreePush((void*)(intptr_t)i);
+ ImGui::PushID(font);
+ bool font_details_opened = ImGui::TreeNode(font, "Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size);
ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) ImGui::GetIO().FontDefault = font;
- ImGui::PushFont(font);
- ImGui::Text("The quick brown fox jumps over the lazy dog");
- ImGui::PopFont();
- if (ImGui::TreeNode("Details"))
+ 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(); ShowHelpMarker("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::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar);
+ ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)sqrtf((float)font->MetricsTotalSurface), (int)sqrtf((float)font->MetricsTotalSurface));
for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
{
ImFontConfig* cfg = &font->ConfigData[config_i];
- ImGui::BulletText("Input %d: \'%s\'\nOversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH);
+ 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 ImFont::Glyph* glyph_fallback = font->FallbackGlyph; // Forcefully/dodgily make FindGlyph() return NULL on fallback, which isn't the default behavior.
+ const ImFontGlyph* glyph_fallback = font->FallbackGlyph; // Forcefully/dodgily make FindGlyph() return NULL on fallback, which isn't the default behavior.
font->FallbackGlyph = NULL;
for (int base = 0; base < 0x10000; base += 256)
{
@@ -1775,7 +2202,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
{
ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size.x + cell_spacing), base_pos.y + (n / 16) * (cell_size.y + cell_spacing));
ImVec2 cell_p2(cell_p1.x + cell_size.x, cell_p1.y + cell_size.y);
- const ImFont::Glyph* glyph = font->FindGlyph((ImWchar)(base+n));;
+ const ImFontGlyph* glyph = font->FindGlyph((ImWchar)(base+n));;
draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255,255,255,100) : IM_COL32(255,255,255,50));
font->RenderChar(draw_list, cell_size.x, 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))
@@ -1783,7 +2210,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
ImGui::BeginTooltip();
ImGui::Text("Codepoint: U+%04X", base+n);
ImGui::Separator();
- ImGui::Text("XAdvance+1: %.1f", glyph->XAdvance);
+ 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();
@@ -1798,7 +2225,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
}
ImGui::TreePop();
}
- ImGui::TreePop();
+ ImGui::PopID();
}
static float window_scale = 1.0f;
ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this window
@@ -1871,15 +2298,24 @@ static void ShowExampleMenuFile()
ImGui::EndChild();
static float f = 0.5f;
static int n = 0;
+ static bool b = true;
ImGui::SliderFloat("Value", &f, 0.0f, 1.0f);
ImGui::InputFloat("Input", &f, 0.1f);
ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0");
+ ImGui::Checkbox("Check", &b);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Colors"))
{
+ ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0));
for (int i = 0; i < ImGuiCol_COUNT; i++)
- ImGui::MenuItem(ImGui::GetStyleColName((ImGuiCol)i));
+ {
+ const char* name = ImGui::GetStyleColorName((ImGuiCol)i);
+ ImGui::ColorButton(name, ImGui::GetStyleColorVec4((ImGuiCol)i));
+ ImGui::SameLine();
+ ImGui::MenuItem(name);
+ }
+ ImGui::PopStyleVar();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Disabled", false)) // Disabled
@@ -1912,76 +2348,97 @@ static void ShowExampleAppConstrainedResize(bool* p_open)
{
struct CustomConstraints // Helper functions to demonstrate programmatic constraints
{
- static void Square(ImGuiSizeConstraintCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); }
- static void Step(ImGuiSizeConstraintCallbackData* 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); }
+ static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(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); }
};
+ static bool auto_resize = false;
static int type = 0;
+ static int display_lines = 10;
if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only
if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only
if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100
- if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(300, 0), ImVec2(400, FLT_MAX)); // Width 300-400
- if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square
- if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step
+ if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)); // Width 400-500
+ if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, 500)); // Height 400-500
+ if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square
+ if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step
- if (ImGui::Begin("Example: Constrained Resize", 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 300-400",
+ "Width 400-500",
+ "Height 400-500",
"Custom: Always Square",
"Custom: Fixed Steps (100)",
};
- ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc));
- 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));
- for (int i = 0; i < 10; i++)
- ImGui::Text("Hello, sailor! Making this line long enough for the example.");
+ 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::PushItemWidth(200);
+ ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc));
+ ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100);
+ ImGui::PopItemWidth();
+ ImGui::Checkbox("Auto-resize", &auto_resize);
+ for (int i = 0; i < display_lines; i++)
+ ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, "");
}
ImGui::End();
}
-// Demonstrate creating a simple static window with no decoration.
+// Demonstrate creating a simple static window with no decoration + a context-menu to choose which corner of the screen to use.
static void ShowExampleAppFixedOverlay(bool* p_open)
{
- ImGui::SetNextWindowPos(ImVec2(10,10));
- if (!ImGui::Begin("Example: Fixed Overlay", p_open, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings))
+ const float DISTANCE = 10.0f;
+ static int corner = 0;
+ ImVec2 window_pos = ImVec2((corner & 1) ? ImGui::GetIO().DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? ImGui::GetIO().DisplaySize.y - DISTANCE : DISTANCE);
+ ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f);
+ ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
+ ImGui::SetNextWindowBgAlpha(0.3f); // Transparent background
+ if (ImGui::Begin("Example: Fixed Overlay", p_open, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings))
{
+ ImGui::Text("Simple overlay\nin the corner of the screen.\n(right-click to change position)");
+ ImGui::Separator();
+ ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y);
+ if (ImGui::BeginPopupContextWindow())
+ {
+ if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0;
+ if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1;
+ if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2;
+ if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3;
+ if (p_open && ImGui::MenuItem("Close")) *p_open = false;
+ ImGui::EndPopup();
+ }
ImGui::End();
- return;
}
- ImGui::Text("Simple overlay\non the top-left side of the screen.");
- ImGui::Separator();
- ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y);
- ImGui::End();
}
// Demonstrate using "##" and "###" in identifiers to manipulate ID generation.
-// Read 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." about ID.
-static void ShowExampleAppManipulatingWindowTitle(bool*)
+// This apply to 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.
+static void ShowExampleAppWindowTitles(bool*)
{
// By default, Windows are uniquely identified by their title.
// You can use the "##" and "###" markers to manipulate the display/ID.
// Using "##" to display same title but have unique identifier.
- ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver);
+ ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiCond_FirstUseEver);
ImGui::Begin("Same title as another window##1");
ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.");
ImGui::End();
- ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver);
+ ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiCond_FirstUseEver);
ImGui::Begin("Same title as another window##2");
ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.");
ImGui::End();
// Using "###" to display a changing title but keep a static identifier "AnimatedTitle"
char buf[128];
- sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand());
- ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver);
+ sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], ImGui::GetFrameCount());
+ ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiCond_FirstUseEver);
ImGui::Begin(buf);
ImGui::Text("This window has a changing title.");
ImGui::End();
@@ -1990,7 +2447,7 @@ static void ShowExampleAppManipulatingWindowTitle(bool*)
// Demonstrate using the low-level ImDrawList to draw custom shapes.
static void ShowExampleAppCustomRendering(bool* p_open)
{
- ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiSetCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Custom rendering", p_open))
{
ImGui::End();
@@ -2017,8 +2474,9 @@ static void ShowExampleAppCustomRendering(bool* p_open)
{
float thickness = (n == 0) ? 1.0f : 4.0f;
draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, thickness); x += sz+spacing;
- draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ~0, thickness); x += sz+spacing;
- draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ~0, thickness); x += sz+spacing;
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ImDrawCornerFlags_All, thickness); x += sz+spacing;
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_All, thickness); x += sz+spacing;
+ draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight, thickness); x += sz+spacing;
draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, thickness); x += sz+spacing;
draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y ), col32, thickness); x += sz+spacing;
draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, thickness); x += sz+spacing;
@@ -2030,8 +2488,9 @@ static void ShowExampleAppCustomRendering(bool* p_open)
draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 32); x += sz+spacing;
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32); x += sz+spacing;
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing;
+ draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotRight); x += sz+spacing;
draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing;
- draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), ImColor(0,0,0), ImColor(255,0,0), ImColor(255,255,0), ImColor(0,255,0));
+ 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)*8, (sz+spacing)*3));
}
ImGui::Separator();
@@ -2050,8 +2509,8 @@ static void ShowExampleAppCustomRendering(bool* p_open)
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), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60));
- draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(255,255,255));
+ 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);
@@ -2060,7 +2519,7 @@ static void ShowExampleAppCustomRendering(bool* p_open)
{
adding_preview = true;
points.push_back(mouse_pos_in_canvas);
- if (!ImGui::GetIO().MouseDown[0])
+ if (!ImGui::IsMouseDown(0))
adding_line = adding_preview = false;
}
if (ImGui::IsItemHovered())
@@ -2077,7 +2536,7 @@ static void ShowExampleAppCustomRendering(bool* p_open)
points.pop_back();
}
}
- draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.)
+ 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);
draw_list->PopClipRect();
@@ -2129,8 +2588,9 @@ struct ExampleAppConsole
ScrollToBottom = true;
}
- void AddLog(const char* fmt, ...) IM_PRINTFARGS(2)
+ void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
+ // FIXME-OPT
char buf[1024];
va_list args;
va_start(args, fmt);
@@ -2143,21 +2603,31 @@ struct ExampleAppConsole
void Draw(const char* title, bool* p_open)
{
- ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_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.
+ // Here we create a context menu only available from the title bar.
+ if (ImGui::BeginPopupContextItem())
+ {
+ if (ImGui::MenuItem("Close"))
+ *p_open = false;
+ 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("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 Dummy Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine();
+ if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine();
+ bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::SameLine();
if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true;
//static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); }
@@ -2169,7 +2639,8 @@ struct ExampleAppConsole
ImGui::PopStyleVar();
ImGui::Separator();
- ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar);
+ 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
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::Selectable("Clear")) ClearLog();
@@ -2188,18 +2659,23 @@ struct ExampleAppConsole
// 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
+ if (copy_to_clipboard)
+ ImGui::LogToClipboard();
+ ImVec4 col_default_text = ImGui::GetStyleColorVec4(ImGuiCol_Text);
for (int i = 0; i < Items.Size; i++)
{
const char* item = Items[i];
if (!filter.PassFilter(item))
continue;
- ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text.
+ ImVec4 col = col_default_text;
if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f);
else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f);
ImGui::PushStyleColor(ImGuiCol_Text, col);
ImGui::TextUnformatted(item);
ImGui::PopStyleColor();
}
+ if (copy_to_clipboard)
+ ImGui::LogFinish();
if (ScrollToBottom)
ImGui::SetScrollHere();
ScrollToBottom = false;
@@ -2211,14 +2687,14 @@ struct ExampleAppConsole
if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this))
{
char* input_end = InputBuf+strlen(InputBuf);
- while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0;
+ while (input_end > InputBuf && input_end[-1] == ' ') { input_end--; } *input_end = 0;
if (InputBuf[0])
ExecCommand(InputBuf);
strcpy(InputBuf, "");
}
// Demonstrate keeping auto focus on the input box
- if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0)))
+ if (ImGui::IsItemHovered() || (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0)))
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
ImGui::End();
@@ -2252,7 +2728,8 @@ struct ExampleAppConsole
}
else if (Stricmp(command_line, "HISTORY") == 0)
{
- for (int i = History.Size >= 10 ? History.Size - 10 : 0; i < History.Size; i++)
+ int first = History.Size - 10;
+ for (int i = first > 0 ? first : 0; i < History.Size; i++)
AddLog("%3d: %s\n", i, History[i]);
}
else
@@ -2386,12 +2863,12 @@ struct ExampleAppLog
void Clear() { Buf.clear(); LineOffsets.clear(); }
- void AddLog(const char* fmt, ...) IM_PRINTFARGS(2)
+ void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
int old_size = Buf.size();
va_list args;
va_start(args, fmt);
- Buf.appendv(fmt, args);
+ Buf.appendfv(fmt, args);
va_end(args);
for (int new_size = Buf.size(); old_size < new_size; old_size++)
if (Buf[old_size] == '\n')
@@ -2401,7 +2878,7 @@ struct ExampleAppLog
void Draw(const char* title, bool* p_open = NULL)
{
- ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiCond_FirstUseEver);
ImGui::Begin(title, p_open);
if (ImGui::Button("Clear")) Clear();
ImGui::SameLine();
@@ -2442,13 +2919,13 @@ static void ShowExampleAppLog(bool* p_open)
{
static ExampleAppLog log;
- // Demo fill
+ // Demo: add random items (unless Ctrl is held)
static float last_time = -1.0f;
float time = ImGui::GetTime();
- if (time - last_time >= 0.3f)
+ if (time - last_time >= 0.20f && !ImGui::GetIO().KeyCtrl)
{
const char* random_words[] = { "system", "info", "warning", "error", "fatal", "notice", "log" };
- log.AddLog("[%s] Hello, time is %.1f, rand() %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, (int)rand());
+ log.AddLog("[%s] Hello, time is %.1f, frame count is %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, ImGui::GetFrameCount());
last_time = time;
}
@@ -2458,7 +2935,7 @@ static void ShowExampleAppLog(bool* p_open)
// Demonstrate create a window with multiple child windows.
static void ShowExampleAppLayout(bool* p_open)
{
- ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiSetCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Example: Layout", p_open, ImGuiWindowFlags_MenuBar))
{
if (ImGui::BeginMenuBar())
@@ -2486,16 +2963,14 @@ static void ShowExampleAppLayout(bool* p_open)
// right
ImGui::BeginGroup();
- ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing())); // Leave room for 1 line below us
+ ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us
ImGui::Text("MyObject: %d", selected);
ImGui::Separator();
ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
ImGui::EndChild();
- ImGui::BeginChild("buttons");
- if (ImGui::Button("Revert")) {}
- ImGui::SameLine();
- if (ImGui::Button("Save")) {}
- ImGui::EndChild();
+ if (ImGui::Button("Revert")) {}
+ ImGui::SameLine();
+ if (ImGui::Button("Save")) {}
ImGui::EndGroup();
}
ImGui::End();
@@ -2504,7 +2979,7 @@ static void ShowExampleAppLayout(bool* p_open)
// Demonstrate create a simple property editor.
static void ShowExampleAppPropertyEditor(bool* p_open)
{
- ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiSetCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Property editor", p_open))
{
ImGui::End();
@@ -2522,10 +2997,10 @@ static void ShowExampleAppPropertyEditor(bool* p_open)
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::AlignFirstTextHeightToWidgets(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high.
+ 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::AlignFirstTextHeightToWidgets();
+ ImGui::AlignTextToFramePadding();
ImGui::Text("my sailor is rich");
ImGui::NextColumn();
if (node_open)
@@ -2540,7 +3015,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open)
}
else
{
- ImGui::AlignFirstTextHeightToWidgets();
+ ImGui::AlignTextToFramePadding();
// Here we use a Selectable (instead of Text) to highlight on hover
//ImGui::Text("Field_%d", i);
char label[32];
@@ -2577,7 +3052,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), ImGuiSetCond_FirstUseEver);
+ ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Long text display", p_open))
{
ImGui::End();
@@ -2588,14 +3063,14 @@ 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 manually\0Multiple calls to Text(), not clipped\0");
+ ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple 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.append("%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");
@@ -2631,7 +3106,7 @@ static void ShowExampleAppLongText(bool* p_open)
// End of Demo code
#else
-void ImGui::ShowTestWindow(bool*) {}
+void ImGui::ShowDemoWindow(bool*) {}
void ImGui::ShowUserGuide() {}
void ImGui::ShowStyleEditor(ImGuiStyle*) {}
diff --git a/imgui_draw.cpp b/imgui_draw.cpp
index 03b679d02..216cf3fd7 100644
--- a/imgui_draw.cpp
+++ b/imgui_draw.cpp
@@ -1,7 +1,8 @@
-// dear imgui, v1.50 WIP
+// dear imgui, v1.54 WIP
// (drawing and font code)
// Contains implementation for
+// - Default styles
// - ImDrawList
// - ImDrawData
// - ImFontAtlas
@@ -14,17 +15,19 @@
#include "imgui.h"
#define IMGUI_DEFINE_MATH_OPERATORS
-#define IMGUI_DEFINE_PLACEMENT_NEW
#include "imgui_internal.h"
#include // vsnprintf, sscanf, printf
#if !defined(alloca)
#ifdef _WIN32
#include // alloca
-#elif (defined(__FreeBSD__) || defined(FreeBSD_kernel) || defined(__DragonFly__)) && !defined(__GLIBC__)
-#include // alloca. FreeBSD uses stdlib.h unless GLIBC
-#else
+#if !defined(alloca)
+#define alloca _alloca // for clang with MS Codegen
+#endif
+#elif defined(__GLIBC__) || defined(__sun)
#include // alloca
+#else
+#include // alloca
#endif
#endif
@@ -39,9 +42,15 @@
#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 it.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
+#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
+#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
@@ -69,9 +78,9 @@ namespace IMGUI_STB_NAMESPACE
#ifdef __clang__
#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
+#pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#endif
#ifdef __GNUC__
@@ -115,16 +124,191 @@ using namespace IMGUI_STB_NAMESPACE;
#endif
//-----------------------------------------------------------------------------
-// ImDrawList
+// Style functions
//-----------------------------------------------------------------------------
-static const ImVec4 GNullClipRect(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Large values that are easy to encode in a few bits+shift
+void ImGui::StyleColorsClassic(ImGuiStyle* dst)
+{
+ ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
+ ImVec4* colors = style->Colors;
+
+ colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
+ colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
+ colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f);
+ colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);
+ colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
+ colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);
+ colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f);
+ colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f);
+ colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
+ colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
+ colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
+ colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
+ colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
+ colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
+ colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
+ colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f);
+ colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
+ colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
+ colors[ImGuiCol_SliderGrabActive] = ImVec4(0.41f, 0.39f, 0.80f, 0.60f);
+ colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f);
+ colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f);
+ colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 1.00f);
+ colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
+ colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
+ colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);
+ colors[ImGuiCol_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
+ colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f);
+ colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f);
+ colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.16f);
+ colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f);
+ colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f);
+ colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
+ colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
+ colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
+ colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
+ colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
+ colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
+ colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
+ colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
+ colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
+ colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
+}
+
+void ImGui::StyleColorsDark(ImGuiStyle* dst)
+{
+ ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
+ ImVec4* colors = style->Colors;
+
+ colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
+ colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
+ colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f);
+ colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
+ colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
+ colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
+ colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f);
+ colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
+ colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
+ colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f);
+ colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f);
+ colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
+ colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
+ colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
+ colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
+ colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
+ colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
+ colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f);
+ colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
+ colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
+ colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
+ colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
+ colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_Separator] = colors[ImGuiCol_Border];//ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
+ colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f);
+ colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f);
+ colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.25f);
+ colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
+ colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
+ colors[ImGuiCol_CloseButton] = ImVec4(0.41f, 0.41f, 0.41f, 0.50f);
+ colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
+ colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
+ colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
+ colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
+ colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
+ colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
+ colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
+ colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
+ colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
+}
+
+// Those light colors are better suited with a thicker font than the default one + FrameBorder
+void ImGui::StyleColorsLight(ImGuiStyle* dst)
+{
+ ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
+ ImVec4* colors = style->Colors;
+
+ colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
+ colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
+ //colors[ImGuiCol_TextHovered] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
+ //colors[ImGuiCol_TextActive] = ImVec4(1.00f, 1.00f, 0.00f, 1.00f);
+ colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f);
+ colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);
+ colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f);
+ colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
+ colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
+ colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
+ colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
+ colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f);
+ colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f);
+ colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f);
+ colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f);
+ colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f);
+ colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f);
+ colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f);
+ colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f);
+ colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f);
+ colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f);
+ colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
+ colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
+ colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
+ colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
+ colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
+ colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
+ colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f);
+ colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f);
+ colors[ImGuiCol_ResizeGrip] = ImVec4(0.80f, 0.80f, 0.80f, 0.56f);
+ colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
+ colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
+ colors[ImGuiCol_CloseButton] = ImVec4(0.59f, 0.59f, 0.59f, 0.50f);
+ colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
+ colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f);
+ colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
+ colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
+ colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
+ colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f);
+ colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
+ colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
+ colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
+}
+
+//-----------------------------------------------------------------------------
+// ImDrawListData
+//-----------------------------------------------------------------------------
+
+ImDrawListSharedData::ImDrawListSharedData()
+{
+ Font = NULL;
+ FontSize = 0.0f;
+ CurveTessellationTol = 0.0f;
+ ClipRectFullscreen = ImVec4(-8192.0f, -8192.0f, +8192.0f, +8192.0f);
+
+ // Const data
+ for (int i = 0; i < IM_ARRAYSIZE(CircleVtx12); i++)
+ {
+ const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(CircleVtx12);
+ CircleVtx12[i] = ImVec2(cosf(a), sinf(a));
+ }
+}
+
+//-----------------------------------------------------------------------------
+// ImDrawList
+//-----------------------------------------------------------------------------
void ImDrawList::Clear()
{
CmdBuffer.resize(0);
IdxBuffer.resize(0);
VtxBuffer.resize(0);
+ Flags = ImDrawListFlags_AntiAliasedLines | ImDrawListFlags_AntiAliasedFill;
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
@@ -158,8 +342,8 @@ void ImDrawList::ClearFreeMemory()
_Channels.clear();
}
-// Use macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug mode
-#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : GNullClipRect)
+// 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] : NULL)
void ImDrawList::AddDrawCmd()
@@ -220,7 +404,7 @@ void ImDrawList::UpdateTextureID()
// Try to merge with previous command if it matches, else use current command
ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL;
- if (prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL)
+ if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL)
CmdBuffer.pop_back();
else
curr_cmd->TextureId = curr_texture_id;
@@ -250,8 +434,7 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_
void ImDrawList::PushClipRectFullScreen()
{
- PushClipRect(ImVec2(GNullClipRect.x, GNullClipRect.y), ImVec2(GNullClipRect.z, GNullClipRect.w));
- //PushClipRect(GetVisibleRect()); // FIXME-OPT: This would be more correct but we're not supposed to access ImGuiContext from here?
+ PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w));
}
void ImDrawList::PopClipRect()
@@ -282,7 +465,7 @@ void ImDrawList::ChannelsSplit(int channels_count)
_Channels.resize(channels_count);
_ChannelsCount = channels_count;
- // _Channels[] (24 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer
+ // _Channels[] (24/32 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer
// The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to.
// When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer
memset(&_Channels[0], 0, sizeof(ImDrawChannel));
@@ -337,7 +520,7 @@ void ImDrawList::ChannelsMerge()
if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; }
if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; }
}
- AddDrawCmd();
+ UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call.
_ChannelsCount = 1;
}
@@ -359,19 +542,19 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count)
ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1];
draw_cmd.ElemCount += idx_count;
- int vtx_buffer_size = VtxBuffer.Size;
- VtxBuffer.resize(vtx_buffer_size + vtx_count);
- _VtxWritePtr = VtxBuffer.Data + vtx_buffer_size;
+ int vtx_buffer_old_size = VtxBuffer.Size;
+ VtxBuffer.resize(vtx_buffer_old_size + vtx_count);
+ _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size;
- int idx_buffer_size = IdxBuffer.Size;
- IdxBuffer.resize(idx_buffer_size + idx_count);
- _IdxWritePtr = IdxBuffer.Data + idx_buffer_size;
+ int idx_buffer_old_size = IdxBuffer.Size;
+ IdxBuffer.resize(idx_buffer_old_size + idx_count);
+ _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;
}
// Fully unrolled with inline call to keep our debug builds decently fast.
void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col)
{
- ImVec2 b(c.x, a.y), d(a.x, c.y), uv(GImGui->FontTexUvWhitePixel);
+ ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel);
ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx;
_IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2);
_IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3);
@@ -414,25 +597,23 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c
}
// TODO: Thickness anti-aliased lines cap are missing their AA fringe.
-void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness, bool anti_aliased)
+void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness)
{
if (points_count < 2)
return;
- const ImVec2 uv = GImGui->FontTexUvWhitePixel;
- anti_aliased &= GImGui->Style.AntiAliasedLines;
- //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug
+ const ImVec2 uv = _Data->TexUvWhitePixel;
int count = points_count;
if (!closed)
count = points_count-1;
const bool thick_line = thickness > 1.0f;
- if (anti_aliased)
+ if (Flags & ImDrawListFlags_AntiAliasedLines)
{
// Anti-aliased stroke
const float AA_SIZE = 1.0f;
- const ImU32 col_trans = col & IM_COL32(255,255,255,0);
+ 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;
@@ -595,17 +776,15 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32
}
}
-void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, bool anti_aliased)
+void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col)
{
- const ImVec2 uv = GImGui->FontTexUvWhitePixel;
- anti_aliased &= GImGui->Style.AntiAliasedShapes;
- //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug
+ const ImVec2 uv = _Data->TexUvWhitePixel;
- if (anti_aliased)
+ if (Flags & ImDrawListFlags_AntiAliasedFill)
{
// Anti-aliased Fill
const float AA_SIZE = 1.0f;
- const ImU32 col_trans = col & IM_COL32(255,255,255,0);
+ 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);
PrimReserve(idx_count, vtx_count);
@@ -678,46 +857,32 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun
}
}
-void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int amin, int amax)
+void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12)
{
- static ImVec2 circle_vtx[12];
- static bool circle_vtx_builds = false;
- const int circle_vtx_count = IM_ARRAYSIZE(circle_vtx);
- if (!circle_vtx_builds)
- {
- for (int i = 0; i < circle_vtx_count; i++)
- {
- const float a = ((float)i / (float)circle_vtx_count) * 2*IM_PI;
- circle_vtx[i].x = cosf(a);
- circle_vtx[i].y = sinf(a);
- }
- circle_vtx_builds = true;
- }
-
- if (amin > amax) return;
- if (radius == 0.0f)
+ if (radius == 0.0f || a_min_of_12 > a_max_of_12)
{
_Path.push_back(centre);
+ return;
}
- else
+ _Path.reserve(_Path.Size + (a_max_of_12 - a_min_of_12 + 1));
+ for (int a = a_min_of_12; a <= a_max_of_12; a++)
{
- _Path.reserve(_Path.Size + (amax - amin + 1));
- for (int a = amin; a <= amax; a++)
- {
- const ImVec2& c = circle_vtx[a % circle_vtx_count];
- _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius));
- }
+ const ImVec2& c = _Data->CircleVtx12[a % IM_ARRAYSIZE(_Data->CircleVtx12)];
+ _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius));
}
}
-void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float amin, float amax, int num_segments)
+void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments)
{
if (radius == 0.0f)
+ {
_Path.push_back(centre);
+ return;
+ }
_Path.reserve(_Path.Size + (num_segments + 1));
for (int i = 0; i <= num_segments; i++)
{
- const float a = amin + ((float)i / (float)num_segments) * (amax - amin);
+ const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min);
_Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(a) * radius));
}
}
@@ -754,7 +919,7 @@ void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImV
if (num_segments == 0)
{
// Auto-tessellated
- PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, GImGui->Style.CurveTessellationTol, 0);
+ PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0);
}
else
{
@@ -774,27 +939,26 @@ void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImV
void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners)
{
- float r = rounding;
- r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f ) - 1.0f);
- r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f ) - 1.0f);
+ rounding = ImMin(rounding, fabsf(b.x - a.x) * ( ((rounding_corners & ImDrawCornerFlags_Top) == ImDrawCornerFlags_Top) || ((rounding_corners & ImDrawCornerFlags_Bot) == ImDrawCornerFlags_Bot) ? 0.5f : 1.0f ) - 1.0f);
+ rounding = ImMin(rounding, fabsf(b.y - a.y) * ( ((rounding_corners & ImDrawCornerFlags_Left) == ImDrawCornerFlags_Left) || ((rounding_corners & ImDrawCornerFlags_Right) == ImDrawCornerFlags_Right) ? 0.5f : 1.0f ) - 1.0f);
- if (r <= 0.0f || rounding_corners == 0)
+ if (rounding <= 0.0f || rounding_corners == 0)
{
PathLineTo(a);
- PathLineTo(ImVec2(b.x,a.y));
+ PathLineTo(ImVec2(b.x, a.y));
PathLineTo(b);
- PathLineTo(ImVec2(a.x,b.y));
+ PathLineTo(ImVec2(a.x, b.y));
}
else
{
- const float r0 = (rounding_corners & 1) ? r : 0.0f;
- const float r1 = (rounding_corners & 2) ? r : 0.0f;
- const float r2 = (rounding_corners & 4) ? r : 0.0f;
- const float r3 = (rounding_corners & 8) ? r : 0.0f;
- PathArcToFast(ImVec2(a.x+r0,a.y+r0), r0, 6, 9);
- PathArcToFast(ImVec2(b.x-r1,a.y+r1), r1, 9, 12);
- PathArcToFast(ImVec2(b.x-r2,b.y-r2), r2, 0, 3);
- PathArcToFast(ImVec2(a.x+r3,b.y-r3), r3, 3, 6);
+ const float rounding_tl = (rounding_corners & ImDrawCornerFlags_TopLeft) ? rounding : 0.0f;
+ const float rounding_tr = (rounding_corners & ImDrawCornerFlags_TopRight) ? rounding : 0.0f;
+ const float rounding_br = (rounding_corners & ImDrawCornerFlags_BotRight) ? rounding : 0.0f;
+ const float rounding_bl = (rounding_corners & ImDrawCornerFlags_BotLeft) ? rounding : 0.0f;
+ PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9);
+ PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12);
+ PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3);
+ PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6);
}
}
@@ -823,7 +987,7 @@ void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, floa
if (rounding > 0.0f)
{
PathRect(a, b, rounding, rounding_corners_flags);
- PathFill(col);
+ PathFillConvex(col);
}
else
{
@@ -837,7 +1001,7 @@ void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32
if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0)
return;
- const ImVec2 uv = GImGui->FontTexUvWhitePixel;
+ 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));
@@ -868,7 +1032,7 @@ void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c
PathLineTo(b);
PathLineTo(c);
PathLineTo(d);
- PathFill(col);
+ PathFillConvex(col);
}
void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness)
@@ -890,7 +1054,7 @@ void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec
PathLineTo(a);
PathLineTo(b);
PathLineTo(c);
- PathFill(col);
+ PathFillConvex(col);
}
void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness)
@@ -910,7 +1074,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col,
const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments;
PathArcTo(centre, radius, 0.0f, a_max, num_segments);
- PathFill(col);
+ PathFillConvex(col);
}
void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments)
@@ -933,12 +1097,11 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos,
if (text_begin == text_end)
return;
- // Note: This is one of the few instance of breaking the encapsulation of ImDrawList, as we pull this from ImGui state, but it is just SO useful.
- // Might just move Font/FontSize to ImDrawList?
+ // Pull default font/size from the shared ImDrawListSharedData instance
if (font == NULL)
- font = GImGui->Font;
+ font = _Data->Font;
if (font_size == 0.0f)
- font_size = GImGui->FontSize;
+ font_size = _Data->FontSize;
IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font.
@@ -955,21 +1118,61 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos,
void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end)
{
- AddText(GImGui->Font, GImGui->FontSize, pos, col, text_begin, text_end);
+ AddText(NULL, 0.0f, pos, col, text_begin, text_end);
}
-void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col)
+void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
- // FIXME-OPT: This is wasting draw calls.
const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
if (push_texture_id)
PushTextureID(user_texture_id);
PrimReserve(6, 4);
- PrimRectUV(a, b, uv0, uv1, col);
+ PrimRectUV(a, b, uv_a, uv_b, col);
+
+ if (push_texture_id)
+ PopTextureID();
+}
+
+void ImDrawList::AddImageQuad(ImTextureID user_texture_id, 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)
+{
+ if ((col & IM_COL32_A_MASK) == 0)
+ return;
+
+ const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
+ if (push_texture_id)
+ PushTextureID(user_texture_id);
+
+ PrimReserve(6, 4);
+ PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col);
+
+ if (push_texture_id)
+ PopTextureID();
+}
+
+void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners)
+{
+ if ((col & IM_COL32_A_MASK) == 0)
+ return;
+
+ if (rounding <= 0.0f || (rounding_corners & ImDrawCornerFlags_All) == 0)
+ {
+ AddImage(user_texture_id, a, b, uv_a, uv_b, col);
+ return;
+ }
+
+ const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back();
+ if (push_texture_id)
+ PushTextureID(user_texture_id);
+
+ int vert_start_idx = VtxBuffer.Size;
+ PathRect(a, b, rounding, rounding_corners);
+ PathFillConvex(col);
+ int vert_end_idx = VtxBuffer.Size;
+ ImGui::ShadeVertsLinearUV(VtxBuffer.Data + vert_start_idx, VtxBuffer.Data + vert_end_idx, a, b, uv_a, uv_b, true);
if (push_texture_id)
PopTextureID();
@@ -1013,7 +1216,68 @@ void ImDrawData::ScaleClipRects(const ImVec2& scale)
}
//-----------------------------------------------------------------------------
-// ImFontAtlas
+// Shade functions
+//-----------------------------------------------------------------------------
+
+// Generic linear color gradient, write to RGB fields, leave A untouched.
+void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawVert* vert_start, ImDrawVert* vert_end, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1)
+{
+ ImVec2 gradient_extent = gradient_p1 - gradient_p0;
+ float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent);
+ for (ImDrawVert* vert = vert_start; vert < vert_end; vert++)
+ {
+ float d = ImDot(vert->pos - gradient_p0, gradient_extent);
+ float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f);
+ int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t);
+ int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t);
+ int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t);
+ vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK);
+ }
+}
+
+// Scan and shade backward from the end of given vertices. Assume vertices are text only (= vert_start..vert_end going left to right) so we can break as soon as we are out the gradient bounds.
+void ImGui::ShadeVertsLinearAlphaGradientForLeftToRightText(ImDrawVert* vert_start, ImDrawVert* vert_end, float gradient_p0_x, float gradient_p1_x)
+{
+ float gradient_extent_x = gradient_p1_x - gradient_p0_x;
+ float gradient_inv_length2 = 1.0f / (gradient_extent_x * gradient_extent_x);
+ int full_alpha_count = 0;
+ for (ImDrawVert* vert = vert_end - 1; vert >= vert_start; vert--)
+ {
+ float d = (vert->pos.x - gradient_p0_x) * (gradient_extent_x);
+ float alpha_mul = 1.0f - ImClamp(d * gradient_inv_length2, 0.0f, 1.0f);
+ if (alpha_mul >= 1.0f && ++full_alpha_count > 2)
+ return; // Early out
+ int a = (int)(((vert->col >> IM_COL32_A_SHIFT) & 0xFF) * alpha_mul);
+ vert->col = (vert->col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
+ }
+}
+
+// Distribute UV over (a, b) rectangle
+void ImGui::ShadeVertsLinearUV(ImDrawVert* vert_start, ImDrawVert* vert_end, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp)
+{
+ const ImVec2 size = b - a;
+ const ImVec2 uv_size = uv_b - uv_a;
+ const ImVec2 scale = ImVec2(
+ size.x != 0.0f ? (uv_size.x / size.x) : 0.0f,
+ size.y != 0.0f ? (uv_size.y / size.y) : 0.0f);
+
+ if (clamp)
+ {
+ const ImVec2 min = ImMin(uv_a, uv_b);
+ const ImVec2 max = ImMax(uv_a, uv_b);
+
+ for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex)
+ vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max);
+ }
+ else
+ {
+ for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex)
+ vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale);
+ }
+}
+
+//-----------------------------------------------------------------------------
+// ImFontConfig
//-----------------------------------------------------------------------------
ImFontConfig::ImFontConfig()
@@ -1027,20 +1291,79 @@ ImFontConfig::ImFontConfig()
OversampleV = 1;
PixelSnapH = false;
GlyphExtraSpacing = ImVec2(0.0f, 0.0f);
+ GlyphOffset = ImVec2(0.0f, 0.0f);
GlyphRanges = NULL;
MergeMode = false;
- MergeGlyphCenterV = false;
- DstFont = NULL;
+ RasterizerFlags = 0x00;
+ RasterizerMultiply = 1.0f;
memset(Name, 0, sizeof(Name));
+ DstFont = NULL;
}
+//-----------------------------------------------------------------------------
+// ImFontAtlas
+//-----------------------------------------------------------------------------
+
+// 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 ImGui to render filled shapes.
+const int FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF = 90;
+const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27;
+const unsigned int FONT_ATLAS_DEFAULT_TEX_DATA_ID = 0x80000000;
+static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] =
+{
+ "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX"
+ "..- -X.....X- X.X - X.X -X.....X - X.....X"
+ "--- -XXX.XXX- X...X - X...X -X....X - X....X"
+ "X - X.X - X.....X - X.....X -X...X - X...X"
+ "XX - X.X -X.......X- X.......X -X..X.X - X.X..X"
+ "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X"
+ "X..X - X.X - X.X - X.X -XX X.X - X.X XX"
+ "X...X - X.X - X.X - XX X.X XX - X.X - X.X "
+ "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X "
+ "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X "
+ "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X "
+ "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X "
+ "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X "
+ "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X "
+ "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X "
+ "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X "
+ "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX "
+ "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------"
+ "X.X X..X - -X.......X- X.......X - XX XX - "
+ "XX X..X - - X.....X - X.....X - X.X X.X - "
+ " X..X - X...X - X...X - X..X X..X - "
+ " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - "
+ "------------ - X - X -X.....................X- "
+ " ----------------------------------- X...XXXXXXXXXXXXX...X - "
+ " - X..X X..X - "
+ " - X.X X.X - "
+ " - XX XX - "
+};
+
+static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_Count_][3] =
+{
+ // Pos ........ Size ......... Offset ......
+ { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow
+ { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput
+ { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move
+ { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS
+ { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW
+ { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW
+ { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE
+};
+
ImFontAtlas::ImFontAtlas()
{
TexID = NULL;
+ TexDesiredWidth = 0;
+ TexGlyphPadding = 1;
TexPixelsAlpha8 = NULL;
TexPixelsRGBA32 = NULL;
- TexWidth = TexHeight = TexDesiredWidth = 0;
- TexUvWhitePixel = ImVec2(0, 0);
+ 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;
}
ImFontAtlas::~ImFontAtlas()
@@ -1057,7 +1380,7 @@ void ImFontAtlas::ClearInputData()
ConfigData[i].FontData = NULL;
}
- // When clearing this we lose access to the font name and other information used to build the font.
+ // When clearing this we lose access to the font name and other information used to build the font.
for (int i = 0; i < Fonts.Size; i++)
if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size)
{
@@ -1065,6 +1388,9 @@ void ImFontAtlas::ClearInputData()
Fonts[i]->ConfigDataCount = 0;
}
ConfigData.clear();
+ CustomRects.clear();
+ for (int n = 0; n < IM_ARRAYSIZE(CustomRectIds); n++)
+ CustomRectIds[n] = -1;
}
void ImFontAtlas::ClearTexData()
@@ -1080,10 +1406,7 @@ void ImFontAtlas::ClearTexData()
void ImFontAtlas::ClearFonts()
{
for (int i = 0; i < Fonts.Size; i++)
- {
- Fonts[i]->~ImFont();
- ImGui::MemFree(Fonts[i]);
- }
+ IM_DELETE(Fonts[i]);
Fonts.clear();
}
@@ -1116,13 +1439,16 @@ void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_wid
// Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp
if (!TexPixelsRGBA32)
{
- unsigned char* pixels;
+ unsigned char* pixels = NULL;
GetTexDataAsAlpha8(&pixels, NULL, NULL);
- TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4));
- const unsigned char* src = pixels;
- unsigned int* dst = TexPixelsRGBA32;
- for (int n = TexWidth * TexHeight; n > 0; n--)
- *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++));
+ if (pixels)
+ {
+ TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4));
+ const unsigned char* src = pixels;
+ unsigned int* dst = TexPixelsRGBA32;
+ for (int n = TexWidth * TexHeight; n > 0; n--)
+ *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++));
+ }
}
*out_pixels = (unsigned char*)TexPixelsRGBA32;
@@ -1138,16 +1464,14 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
// Create new font
if (!font_cfg->MergeMode)
- {
- ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont));
- IM_PLACEMENT_NEW(font) ImFont();
- Fonts.push_back(font);
- }
+ Fonts.push_back(IM_NEW(ImFont));
+ else
+ IM_ASSERT(!Fonts.empty()); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font.
ConfigData.push_back(*font_cfg);
ImFontConfig& new_font_cfg = ConfigData.back();
- if (!new_font_cfg.DstFont)
- new_font_cfg.DstFont = Fonts.back();
+ if (!new_font_cfg.DstFont)
+ new_font_cfg.DstFont = Fonts.back();
if (!new_font_cfg.FontDataOwnedByAtlas)
{
new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize);
@@ -1186,9 +1510,10 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
font_cfg.PixelSnapH = true;
}
if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "ProggyClean.ttf, 13px");
+ if (font_cfg.SizePixels <= 0.0f) font_cfg.SizePixels = 13.0f;
const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
- ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, 13.0f, &font_cfg, GetGlyphRangesDefault());
+ ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, GetGlyphRangesDefault());
return font;
}
@@ -1212,7 +1537,7 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels,
return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges);
}
-// NBM Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build().
+// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build().
ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
@@ -1247,92 +1572,172 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed
return font;
}
+int ImFontAtlas::AddCustomRectRegular(unsigned int id, int width, int height)
+{
+ IM_ASSERT(id >= 0x10000);
+ IM_ASSERT(width > 0 && width <= 0xFFFF);
+ IM_ASSERT(height > 0 && height <= 0xFFFF);
+ CustomRect r;
+ r.ID = id;
+ r.Width = (unsigned short)width;
+ r.Height = (unsigned short)height;
+ CustomRects.push_back(r);
+ return CustomRects.Size - 1; // Return index
+}
+
+int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset)
+{
+ IM_ASSERT(font != NULL);
+ IM_ASSERT(width > 0 && width <= 0xFFFF);
+ IM_ASSERT(height > 0 && height <= 0xFFFF);
+ CustomRect r;
+ r.ID = id;
+ r.Width = (unsigned short)width;
+ r.Height = (unsigned short)height;
+ r.GlyphAdvanceX = advance_x;
+ r.GlyphOffset = offset;
+ r.Font = font;
+ CustomRects.push_back(r);
+ return CustomRects.Size - 1; // Return index
+}
+
+void ImFontAtlas::CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max)
+{
+ IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates
+ IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed
+ *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y);
+ *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y);
+}
+
+bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2])
+{
+ if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_Count_)
+ return false;
+
+ ImFontAtlas::CustomRect& r = CustomRects[CustomRectIds[0]];
+ IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID);
+ ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y);
+ ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1];
+ *out_size = size;
+ *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;
+ out_uv_fill[0] = (pos) * TexUvScale;
+ out_uv_fill[1] = (pos + size) * TexUvScale;
+ return true;
+}
+
bool ImFontAtlas::Build()
{
- IM_ASSERT(ConfigData.Size > 0);
+ return ImFontAtlasBuildWithStbTruetype(this);
+}
- TexID = NULL;
- TexWidth = TexHeight = 0;
- TexUvWhitePixel = ImVec2(0, 0);
- ClearTexData();
+void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor)
+{
+ for (unsigned int i = 0; i < 256; i++)
+ {
+ unsigned int value = (unsigned int)(i * in_brighten_factor);
+ out_table[i] = value > 255 ? 255 : (value & 0xFF);
+ }
+}
+void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride)
+{
+ unsigned char* data = pixels + x + y * stride;
+ for (int j = h; j > 0; j--, data += stride)
+ for (int i = 0; i < w; i++)
+ data[i] = table[data[i]];
+}
+
+bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
+{
+ IM_ASSERT(atlas->ConfigData.Size > 0);
+
+ ImFontAtlasBuildRegisterDefaultCustomRects(atlas);
+
+ atlas->TexID = NULL;
+ atlas->TexWidth = atlas->TexHeight = 0;
+ atlas->TexUvScale = ImVec2(0.0f, 0.0f);
+ atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
+ atlas->ClearTexData();
+
+ // Count glyphs/ranges
+ int total_glyphs_count = 0;
+ int total_ranges_count = 0;
+ for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++)
+ {
+ ImFontConfig& cfg = atlas->ConfigData[input_i];
+ if (!cfg.GlyphRanges)
+ cfg.GlyphRanges = atlas->GetGlyphRangesDefault();
+ for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, total_ranges_count++)
+ total_glyphs_count += (in_range[1] - in_range[0]) + 1;
+ }
+
+ // We need a width for the skyline algorithm. Using a dumb heuristic here to decide of width. User can override TexDesiredWidth and TexGlyphPadding if they wish.
+ // Width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
+ atlas->TexWidth = (atlas->TexDesiredWidth > 0) ? atlas->TexDesiredWidth : (total_glyphs_count > 4000) ? 4096 : (total_glyphs_count > 2000) ? 2048 : (total_glyphs_count > 1000) ? 1024 : 512;
+ atlas->TexHeight = 0;
+
+ // Start packing
+ const int max_tex_height = 1024*32;
+ stbtt_pack_context spc = {};
+ stbtt_PackBegin(&spc, NULL, atlas->TexWidth, max_tex_height, 0, atlas->TexGlyphPadding, NULL);
+ stbtt_PackSetOversampling(&spc, 1, 1);
+
+ // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
+ ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info);
+
+ // Initialize font information (so we can error without any cleanup)
struct ImFontTempBuildData
{
stbtt_fontinfo FontInfo;
stbrp_rect* Rects;
+ int RectsCount;
stbtt_pack_range* Ranges;
int RangesCount;
};
- ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)ConfigData.Size * sizeof(ImFontTempBuildData));
-
- // Initialize font information early (so we can error without any cleanup) + count glyphs
- int total_glyph_count = 0;
- int total_glyph_range_count = 0;
- for (int input_i = 0; input_i < ConfigData.Size; input_i++)
+ ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)atlas->ConfigData.Size * sizeof(ImFontTempBuildData));
+ for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++)
{
- ImFontConfig& cfg = ConfigData[input_i];
+ ImFontConfig& cfg = atlas->ConfigData[input_i];
ImFontTempBuildData& tmp = tmp_array[input_i];
+ IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
- IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == this));
const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo);
IM_ASSERT(font_offset >= 0);
if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset))
- return false;
-
- // Count glyphs
- if (!cfg.GlyphRanges)
- cfg.GlyphRanges = GetGlyphRangesDefault();
- for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2)
{
- total_glyph_count += (in_range[1] - in_range[0]) + 1;
- total_glyph_range_count++;
+ atlas->TexWidth = atlas->TexHeight = 0; // Reset output on failure
+ ImGui::MemFree(tmp_array);
+ return false;
}
}
- // Start packing. We need a known width for the skyline algorithm. Using a cheap heuristic here to decide of width. User can override TexDesiredWidth if they wish.
- // After packing is done, width shouldn't matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
- TexWidth = (TexDesiredWidth > 0) ? TexDesiredWidth : (total_glyph_count > 4000) ? 4096 : (total_glyph_count > 2000) ? 2048 : (total_glyph_count > 1000) ? 1024 : 512;
- TexHeight = 0;
- const int max_tex_height = 1024*32;
- stbtt_pack_context spc;
- stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL);
-
- // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
- ImVector extra_rects;
- RenderCustomTexData(0, &extra_rects);
- stbtt_PackSetOversampling(&spc, 1, 1);
- stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], extra_rects.Size);
- for (int i = 0; i < extra_rects.Size; i++)
- if (extra_rects[i].was_packed)
- TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h);
-
// Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0;
- stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar));
- stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect));
- stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range));
- memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar));
- memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity.
- memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range));
+ stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyphs_count * sizeof(stbtt_packedchar));
+ stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyphs_count * sizeof(stbrp_rect));
+ stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_ranges_count * sizeof(stbtt_pack_range));
+ memset(buf_packedchars, 0, total_glyphs_count * sizeof(stbtt_packedchar));
+ memset(buf_rects, 0, total_glyphs_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity.
+ memset(buf_ranges, 0, total_ranges_count * sizeof(stbtt_pack_range));
// First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point)
- for (int input_i = 0; input_i < ConfigData.Size; input_i++)
+ for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++)
{
- ImFontConfig& cfg = ConfigData[input_i];
+ ImFontConfig& cfg = atlas->ConfigData[input_i];
ImFontTempBuildData& tmp = tmp_array[input_i];
// Setup ranges
- int glyph_count = 0;
- int glyph_ranges_count = 0;
- for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2)
- {
- glyph_count += (in_range[1] - in_range[0]) + 1;
- glyph_ranges_count++;
- }
+ int font_glyphs_count = 0;
+ int font_ranges_count = 0;
+ for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2, font_ranges_count++)
+ font_glyphs_count += (in_range[1] - in_range[0]) + 1;
tmp.Ranges = buf_ranges + buf_ranges_n;
- tmp.RangesCount = glyph_ranges_count;
- buf_ranges_n += glyph_ranges_count;
- for (int i = 0; i < glyph_ranges_count; i++)
+ tmp.RangesCount = font_ranges_count;
+ buf_ranges_n += font_ranges_count;
+ for (int i = 0; i < font_ranges_count; i++)
{
const ImWchar* in_range = &cfg.GlyphRanges[i * 2];
stbtt_pack_range& range = tmp.Ranges[i];
@@ -1345,34 +1750,45 @@ bool ImFontAtlas::Build()
// Pack
tmp.Rects = buf_rects + buf_rects_n;
- buf_rects_n += glyph_count;
+ tmp.RectsCount = font_glyphs_count;
+ buf_rects_n += font_glyphs_count;
stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV);
int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects);
+ IM_ASSERT(n == font_glyphs_count);
stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n);
// Extend texture height
for (int i = 0; i < n; i++)
if (tmp.Rects[i].was_packed)
- TexHeight = ImMax(TexHeight, tmp.Rects[i].y + tmp.Rects[i].h);
+ atlas->TexHeight = ImMax(atlas->TexHeight, tmp.Rects[i].y + tmp.Rects[i].h);
}
- IM_ASSERT(buf_rects_n == total_glyph_count);
- IM_ASSERT(buf_packedchars_n == total_glyph_count);
- IM_ASSERT(buf_ranges_n == total_glyph_range_count);
+ IM_ASSERT(buf_rects_n == total_glyphs_count);
+ IM_ASSERT(buf_packedchars_n == total_glyphs_count);
+ IM_ASSERT(buf_ranges_n == total_ranges_count);
// Create texture
- TexHeight = ImUpperPowerOfTwo(TexHeight);
- TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight);
- memset(TexPixelsAlpha8, 0, TexWidth * TexHeight);
- spc.pixels = TexPixelsAlpha8;
- spc.height = TexHeight;
+ atlas->TexHeight = ImUpperPowerOfTwo(atlas->TexHeight);
+ atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
+ atlas->TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(atlas->TexWidth * atlas->TexHeight);
+ memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
+ spc.pixels = atlas->TexPixelsAlpha8;
+ spc.height = atlas->TexHeight;
- // Second pass: render characters
- for (int input_i = 0; input_i < ConfigData.Size; input_i++)
+ // Second pass: render font characters
+ for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++)
{
- ImFontConfig& cfg = ConfigData[input_i];
+ ImFontConfig& cfg = atlas->ConfigData[input_i];
ImFontTempBuildData& tmp = tmp_array[input_i];
stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV);
stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects);
+ if (cfg.RasterizerMultiply != 1.0f)
+ {
+ unsigned char multiply_table[256];
+ ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
+ for (const stbrp_rect* r = tmp.Rects; r != tmp.Rects + tmp.RectsCount; r++)
+ if (r->was_packed)
+ ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, spc.pixels, r->x, r->y, r->w, r->h, spc.stride_in_bytes);
+ }
tmp.Rects = NULL;
}
@@ -1382,32 +1798,22 @@ bool ImFontAtlas::Build()
buf_rects = NULL;
// Third pass: setup ImFont and glyphs for runtime
- for (int input_i = 0; input_i < ConfigData.Size; input_i++)
+ for (int input_i = 0; input_i < atlas->ConfigData.Size; input_i++)
{
- ImFontConfig& cfg = ConfigData[input_i];
+ ImFontConfig& cfg = atlas->ConfigData[input_i];
ImFontTempBuildData& tmp = tmp_array[input_i];
- ImFont* dst_font = cfg.DstFont;
+ ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true)
- float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels);
+ const float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels);
int unscaled_ascent, unscaled_descent, unscaled_line_gap;
stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);
- float ascent = unscaled_ascent * font_scale;
- float descent = unscaled_descent * font_scale;
- if (!cfg.MergeMode)
- {
- dst_font->ContainerAtlas = this;
- dst_font->ConfigData = &cfg;
- dst_font->ConfigDataCount = 0;
- dst_font->FontSize = cfg.SizePixels;
- dst_font->Ascent = ascent;
- dst_font->Descent = descent;
- dst_font->Glyphs.resize(0);
- }
- dst_font->ConfigDataCount++;
- float off_y = (cfg.MergeMode && cfg.MergeGlyphCenterV) ? (ascent - dst_font->Ascent) * 0.5f : 0.0f;
+ const float ascent = unscaled_ascent * font_scale;
+ const float descent = unscaled_descent * font_scale;
+ ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
+ const float off_x = cfg.GlyphOffset.x;
+ const float off_y = cfg.GlyphOffset.y + (float)(int)(dst_font->Ascent + 0.5f);
- dst_font->FallbackGlyph = NULL; // Always clear fallback so FindGlyph can return NULL. It will be set again in BuildLookupTable()
for (int i = 0; i < tmp.RangesCount; i++)
{
stbtt_pack_range& range = tmp.Ranges[i];
@@ -1423,21 +1829,10 @@ bool ImFontAtlas::Build()
stbtt_aligned_quad q;
float dummy_x = 0.0f, dummy_y = 0.0f;
- stbtt_GetPackedQuad(range.chardata_for_range, TexWidth, TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0);
-
- dst_font->Glyphs.resize(dst_font->Glyphs.Size + 1);
- ImFont::Glyph& glyph = dst_font->Glyphs.back();
- glyph.Codepoint = (ImWchar)codepoint;
- glyph.X0 = q.x0; glyph.Y0 = q.y0; glyph.X1 = q.x1; glyph.Y1 = q.y1;
- glyph.U0 = q.s0; glyph.V0 = q.t0; glyph.U1 = q.s1; glyph.V1 = q.t1;
- glyph.Y0 += (float)(int)(dst_font->Ascent + off_y + 0.5f);
- glyph.Y1 += (float)(int)(dst_font->Ascent + off_y + 0.5f);
- glyph.XAdvance = (pc.xadvance + cfg.GlyphExtraSpacing.x); // Bake spacing into XAdvance
- if (cfg.PixelSnapH)
- glyph.XAdvance = (float)(int)(glyph.XAdvance + 0.5f);
+ stbtt_GetPackedQuad(range.chardata_for_range, atlas->TexWidth, atlas->TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0);
+ dst_font->AddGlyph((ImWchar)codepoint, q.x0 + off_x, q.y0 + off_y, q.x1 + off_x, q.y1 + off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance);
}
}
- cfg.DstFont->BuildLookupTable();
}
// Cleanup temporaries
@@ -1445,102 +1840,100 @@ bool ImFontAtlas::Build()
ImGui::MemFree(buf_ranges);
ImGui::MemFree(tmp_array);
- // Render into our custom data block
- RenderCustomTexData(1, &extra_rects);
+ ImFontAtlasBuildFinish(atlas);
return true;
}
-void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects)
+void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas)
{
- // 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 ImGui to render filled shapes.
- const int TEX_DATA_W = 90;
- const int TEX_DATA_H = 27;
- const char texture_data[TEX_DATA_W*TEX_DATA_H+1] =
- {
- "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX"
- "..- -X.....X- X.X - X.X -X.....X - X.....X"
- "--- -XXX.XXX- X...X - X...X -X....X - X....X"
- "X - X.X - X.....X - X.....X -X...X - X...X"
- "XX - X.X -X.......X- X.......X -X..X.X - X.X..X"
- "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X"
- "X..X - X.X - X.X - X.X -XX X.X - X.X XX"
- "X...X - X.X - X.X - XX X.X XX - X.X - X.X "
- "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X "
- "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X "
- "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X "
- "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X "
- "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X "
- "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X "
- "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X "
- "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X "
- "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX "
- "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------"
- "X.X X..X - -X.......X- X.......X - XX XX - "
- "XX X..X - - X.....X - X.....X - X.X X.X - "
- " X..X - X...X - X...X - X..X X..X - "
- " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - "
- "------------ - X - X -X.....................X- "
- " ----------------------------------- X...XXXXXXXXXXXXX...X - "
- " - X..X X..X - "
- " - X.X X.X - "
- " - XX XX - "
- };
+ if (atlas->CustomRectIds[0] < 0)
+ 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);
+}
- ImVector& rects = *(ImVector*)p_rects;
- if (pass == 0)
+void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)
+{
+ if (!font_config->MergeMode)
{
- // Request rectangles
- stbrp_rect r;
- memset(&r, 0, sizeof(r));
- r.w = (TEX_DATA_W*2)+1;
- r.h = TEX_DATA_H+1;
- rects.push_back(r);
+ font->ClearOutputData();
+ font->FontSize = font_config->SizePixels;
+ font->ConfigData = font_config;
+ font->ContainerAtlas = atlas;
+ font->Ascent = ascent;
+ font->Descent = descent;
}
- else if (pass == 1)
+ font->ConfigDataCount++;
+}
+
+void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* pack_context_opaque)
+{
+ stbrp_context* pack_context = (stbrp_context*)pack_context_opaque;
+
+ ImVector& user_rects = atlas->CustomRects;
+ IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong.
+
+ ImVector pack_rects;
+ pack_rects.resize(user_rects.Size);
+ memset(pack_rects.Data, 0, sizeof(stbrp_rect) * user_rects.Size);
+ for (int i = 0; i < user_rects.Size; i++)
{
- // Render/copy pixels
- const stbrp_rect& r = rects[0];
- for (int y = 0, n = 0; y < TEX_DATA_H; y++)
- for (int x = 0; x < TEX_DATA_W; x++, n++)
- {
- const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth;
- const int offset1 = offset0 + 1 + TEX_DATA_W;
- TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00;
- TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00;
- }
- const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight);
- TexUvWhitePixel = ImVec2((r.x + 0.5f) * tex_uv_scale.x, (r.y + 0.5f) * tex_uv_scale.y);
-
- // Setup mouse cursors
- const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] =
+ pack_rects[i].w = user_rects[i].Width;
+ pack_rects[i].h = user_rects[i].Height;
+ }
+ stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size);
+ for (int i = 0; i < pack_rects.Size; i++)
+ if (pack_rects[i].was_packed)
{
- // Pos ........ Size ......... Offset ......
- { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow
- { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput
- { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move
- { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS
- { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW
- { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW
- { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE
- };
-
- for (int type = 0; type < ImGuiMouseCursor_Count_; type++)
- {
- ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type];
- ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y);
- const ImVec2 size = cursor_datas[type][1];
- cursor_data.Type = type;
- cursor_data.Size = size;
- cursor_data.HotOffset = cursor_datas[type][2];
- cursor_data.TexUvMin[0] = (pos) * tex_uv_scale;
- cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale;
- pos.x += TEX_DATA_W+1;
- cursor_data.TexUvMin[1] = (pos) * tex_uv_scale;
- cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale;
+ user_rects[i].X = pack_rects[i].x;
+ user_rects[i].Y = pack_rects[i].y;
+ IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height);
+ atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h);
}
+}
+
+static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)
+{
+ IM_ASSERT(atlas->CustomRectIds[0] >= 0);
+ ImFontAtlas::CustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]];
+ IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID);
+ IM_ASSERT(r.Width == FONT_ATLAS_DEFAULT_TEX_DATA_W_HALF*2+1);
+ IM_ASSERT(r.Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);
+ IM_ASSERT(r.IsPacked());
+ IM_ASSERT(atlas->TexPixelsAlpha8 != NULL);
+
+ // Render/copy pixels
+ 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) * atlas->TexWidth;
+ 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;
+ }
+ atlas->TexUvWhitePixel = ImVec2((r.X + 0.5f) * atlas->TexUvScale.x, (r.Y + 0.5f) * atlas->TexUvScale.y);
+}
+
+void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
+{
+ // Render into our custom data block
+ ImFontAtlasBuildRenderDefaultTexData(atlas);
+
+ // Register custom rectangle glyphs
+ for (int i = 0; i < atlas->CustomRects.Size; i++)
+ {
+ const ImFontAtlas::CustomRect& r = atlas->CustomRects[i];
+ if (r.Font == NULL || r.ID > 0x10000)
+ continue;
+
+ IM_ASSERT(r.Font->ContainerAtlas == atlas);
+ ImVec2 uv0, uv1;
+ atlas->CalcCustomRectUV(&r, &uv0, &uv1);
+ r.Font->AddGlyph((ImWchar)r.ID, r.GlyphOffset.x, r.GlyphOffset.y, r.GlyphOffset.x + r.Width, r.GlyphOffset.y + r.Height, uv0.x, uv0.y, uv1.x, uv1.y, r.GlyphAdvanceX);
}
+
+ // Build all fonts lookup tables
+ for (int i = 0; i < atlas->Fonts.Size; i++)
+ atlas->Fonts[i]->BuildLookupTable();
}
// Retrieve list of range (2 int per range, values are inclusive)
@@ -1583,7 +1976,10 @@ const ImWchar* ImFontAtlas::GetGlyphRangesChinese()
const ImWchar* ImFontAtlas::GetGlyphRangesJapanese()
{
// Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1.
- // This encoding helps us reduce the source code size.
+ // This encoding is designed to helps us reduce the source code size.
+ // FIXME: Source a list of the revised 2136 joyo kanji list from 2010 and rebuild this.
+ // The current list was sourced from http://theinstructionlimit.com/author/renaudbedardrenaudbedard/page/3
+ // Note that you may use ImFontAtlas::GlyphRangesBuilder to create your own ranges, by merging existing ranges or adding new characters.
static const short offsets_from_0x4E00[] =
{
-1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17,
@@ -1660,12 +2056,51 @@ const ImWchar* ImFontAtlas::GetGlyphRangesThai()
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin
+ 0x2010, 0x205E, // Punctuations
0x0E00, 0x0E7F, // Thai
0,
};
return &ranges[0];
}
+//-----------------------------------------------------------------------------
+// ImFontAtlas::GlyphRangesBuilder
+//-----------------------------------------------------------------------------
+
+void ImFontAtlas::GlyphRangesBuilder::AddText(const char* text, const char* text_end)
+{
+ while (text_end ? (text < text_end) : *text)
+ {
+ unsigned int c = 0;
+ int c_len = ImTextCharFromUtf8(&c, text, text_end);
+ text += c_len;
+ if (c_len == 0)
+ break;
+ if (c < 0x10000)
+ AddChar((ImWchar)c);
+ }
+}
+
+void ImFontAtlas::GlyphRangesBuilder::AddRanges(const ImWchar* ranges)
+{
+ for (; ranges[0]; ranges += 2)
+ for (ImWchar c = ranges[0]; c <= ranges[1]; c++)
+ AddChar(c);
+}
+
+void ImFontAtlas::GlyphRangesBuilder::BuildRanges(ImVector* out_ranges)
+{
+ for (int n = 0; n < 0x10000; n++)
+ if (GetBit(n))
+ {
+ out_ranges->push_back((ImWchar)n);
+ while (n < 0x10000 && GetBit(n + 1))
+ n++;
+ out_ranges->push_back((ImWchar)n);
+ }
+ out_ranges->push_back(0);
+}
+
//-----------------------------------------------------------------------------
// ImFont
//-----------------------------------------------------------------------------
@@ -1674,7 +2109,8 @@ ImFont::ImFont()
{
Scale = 1.0f;
FallbackChar = (ImWchar)'?';
- Clear();
+ DisplayOffset = ImVec2(0.0f, 1.0f);
+ ClearOutputData();
}
ImFont::~ImFont()
@@ -1687,22 +2123,22 @@ ImFont::~ImFont()
if (g.Font == this)
g.Font = NULL;
*/
- Clear();
+ ClearOutputData();
}
-void ImFont::Clear()
+void ImFont::ClearOutputData()
{
FontSize = 0.0f;
- DisplayOffset = ImVec2(0.0f, 1.0f);
- ConfigData = NULL;
- ConfigDataCount = 0;
- Ascent = Descent = 0.0f;
- ContainerAtlas = NULL;
Glyphs.clear();
- FallbackGlyph = NULL;
- FallbackXAdvance = 0.0f;
- IndexXAdvance.clear();
+ IndexAdvanceX.clear();
IndexLookup.clear();
+ FallbackGlyph = NULL;
+ FallbackAdvanceX = 0.0f;
+ ConfigDataCount = 0;
+ ConfigData = NULL;
+ ContainerAtlas = NULL;
+ Ascent = Descent = 0.0f;
+ MetricsTotalSurface = 0;
}
void ImFont::BuildLookupTable()
@@ -1712,13 +2148,13 @@ void ImFont::BuildLookupTable()
max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint);
IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved
- IndexXAdvance.clear();
+ IndexAdvanceX.clear();
IndexLookup.clear();
GrowIndex(max_codepoint + 1);
for (int i = 0; i < Glyphs.Size; i++)
{
int codepoint = (int)Glyphs[i].Codepoint;
- IndexXAdvance[codepoint] = Glyphs[i].XAdvance;
+ IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX;
IndexLookup[codepoint] = (unsigned short)i;
}
@@ -1728,20 +2164,20 @@ void ImFont::BuildLookupTable()
{
if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times
Glyphs.resize(Glyphs.Size + 1);
- ImFont::Glyph& tab_glyph = Glyphs.back();
+ ImFontGlyph& tab_glyph = Glyphs.back();
tab_glyph = *FindGlyph((unsigned short)' ');
tab_glyph.Codepoint = '\t';
- tab_glyph.XAdvance *= 4;
- IndexXAdvance[(int)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance;
+ tab_glyph.AdvanceX *= 4;
+ IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX;
IndexLookup[(int)tab_glyph.Codepoint] = (unsigned short)(Glyphs.Size-1);
}
FallbackGlyph = NULL;
FallbackGlyph = FindGlyph(FallbackChar);
- FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f;
+ FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f;
for (int i = 0; i < max_codepoint + 1; i++)
- if (IndexXAdvance[i] < 0.0f)
- IndexXAdvance[i] = FallbackXAdvance;
+ if (IndexAdvanceX[i] < 0.0f)
+ IndexAdvanceX[i] = FallbackAdvanceX;
}
void ImFont::SetFallbackChar(ImWchar c)
@@ -1752,17 +2188,33 @@ void ImFont::SetFallbackChar(ImWchar c)
void ImFont::GrowIndex(int new_size)
{
- IM_ASSERT(IndexXAdvance.Size == IndexLookup.Size);
- int old_size = IndexLookup.Size;
- if (new_size <= old_size)
+ IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size);
+ if (new_size <= IndexLookup.Size)
return;
- IndexXAdvance.resize(new_size);
- IndexLookup.resize(new_size);
- for (int i = old_size; i < new_size; i++)
- {
- IndexXAdvance[i] = -1.0f;
- IndexLookup[i] = (unsigned short)-1;
- }
+ IndexAdvanceX.resize(new_size, -1.0f);
+ IndexLookup.resize(new_size, (unsigned short)-1);
+}
+
+void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x)
+{
+ Glyphs.resize(Glyphs.Size + 1);
+ ImFontGlyph& glyph = Glyphs.back();
+ glyph.Codepoint = (ImWchar)codepoint;
+ glyph.X0 = x0;
+ glyph.Y0 = y0;
+ glyph.X1 = x1;
+ glyph.Y1 = y1;
+ glyph.U0 = u0;
+ glyph.V0 = v0;
+ glyph.U1 = u1;
+ glyph.V1 = v1;
+ glyph.AdvanceX = advance_x + ConfigData->GlyphExtraSpacing.x; // Bake spacing into AdvanceX
+
+ if (ConfigData->PixelSnapH)
+ glyph.AdvanceX = (float)(int)(glyph.AdvanceX + 0.5f);
+
+ // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round)
+ MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + 1.99f);
}
void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
@@ -1777,10 +2229,10 @@ void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
GrowIndex(dst + 1);
IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (unsigned short)-1;
- IndexXAdvance[dst] = (src < index_size) ? IndexXAdvance.Data[src] : 1.0f;
+ IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f;
}
-const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const
+const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
{
if (c < IndexLookup.Size)
{
@@ -1811,6 +2263,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
float line_width = 0.0f;
float word_width = 0.0f;
float blank_width = 0.0f;
+ wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters
const char* word_end = text;
const char* prev_word_end = NULL;
@@ -1844,7 +2297,7 @@ const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const c
}
}
- const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale;
+ const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX[(int)c] : FallbackAdvanceX);
if (ImCharIsSpace(c))
{
if (inside_word)
@@ -1961,7 +2414,7 @@ ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, cons
continue;
}
- const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale;
+ const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX[(int)c] : FallbackAdvanceX) * scale;
if (line_width + char_width >= max_width)
{
s = prev_s;
@@ -1987,15 +2440,13 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col
{
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded.
return;
- if (const Glyph* glyph = FindGlyph(c))
+ if (const ImFontGlyph* glyph = FindGlyph(c))
{
float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;
pos.x = (float)(int)pos.x + DisplayOffset.x;
pos.y = (float)(int)pos.y + DisplayOffset.y;
- ImVec2 pos_tl(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale);
- ImVec2 pos_br(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale);
draw_list->PrimReserve(6, 4);
- draw_list->PrimRectUV(pos_tl, pos_br, ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
+ draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
}
}
@@ -2093,9 +2544,9 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col
}
float char_width = 0.0f;
- if (const Glyph* glyph = FindGlyph((unsigned short)c))
+ if (const ImFontGlyph* glyph = FindGlyph((unsigned short)c))
{
- char_width = glyph->XAdvance * scale;
+ char_width = glyph->AdvanceX * scale;
// Arbitrarily assume that both space and tabs are empty glyphs as an optimization
if (c != ' ' && c != '\t')
@@ -2143,8 +2594,7 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col
}
}
- // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug build.
- // Inlined here:
+ // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here:
{
idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2);
idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3);
@@ -2172,6 +2622,78 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col
draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size;
}
+//-----------------------------------------------------------------------------
+// Internals Drawing Helpers
+//-----------------------------------------------------------------------------
+
+static inline float ImAcos01(float x)
+{
+ if (x <= 0.0f) return IM_PI * 0.5f;
+ if (x >= 1.0f) return 0.0f;
+ return acosf(x);
+ //return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do.
+}
+
+// FIXME: Cleanup and move code to ImDrawList.
+void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding)
+{
+ if (x_end_norm == x_start_norm)
+ return;
+ if (x_start_norm > x_end_norm)
+ ImSwap(x_start_norm, x_end_norm);
+
+ ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y);
+ ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y);
+ if (rounding == 0.0f)
+ {
+ draw_list->AddRectFilled(p0, p1, col, 0.0f);
+ return;
+ }
+
+ rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding);
+ const float inv_rounding = 1.0f / rounding;
+ const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding);
+ const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding);
+ const float x0 = ImMax(p0.x, rect.Min.x + rounding);
+ if (arc0_b == arc0_e)
+ {
+ draw_list->PathLineTo(ImVec2(x0, p1.y));
+ draw_list->PathLineTo(ImVec2(x0, p0.y));
+ }
+ else if (arc0_b == 0.0f && arc0_e == IM_PI*0.5f)
+ {
+ draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL
+ draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR
+ }
+ else
+ {
+ draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL
+ draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR
+ }
+ if (p1.x > rect.Min.x + rounding)
+ {
+ const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding);
+ const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding);
+ const float x1 = ImMin(p1.x, rect.Max.x - rounding);
+ if (arc1_b == arc1_e)
+ {
+ draw_list->PathLineTo(ImVec2(x1, p0.y));
+ draw_list->PathLineTo(ImVec2(x1, p1.y));
+ }
+ else if (arc1_b == 0.0f && arc1_e == IM_PI*0.5f)
+ {
+ draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR
+ draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR
+ }
+ else
+ {
+ draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR
+ draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR
+ }
+ }
+ draw_list->PathFillConvex(col);
+}
+
//-----------------------------------------------------------------------------
// DEFAULT FONT DATA
//-----------------------------------------------------------------------------
diff --git a/imgui_internal.h b/imgui_internal.h
index effc5ce7f..a00a88a09 100644
--- a/imgui_internal.h
+++ b/imgui_internal.h
@@ -1,9 +1,10 @@
-// dear imgui, v1.50 WIP
+// dear imgui, v1.54 WIP
// (internals)
// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
-// Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)
+// Set:
// #define IMGUI_DEFINE_MATH_OPERATORS
+// To implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)
#pragma once
@@ -34,18 +35,18 @@ struct ImRect;
struct ImGuiColMod;
struct ImGuiStyleMod;
struct ImGuiGroupData;
-struct ImGuiSimpleColumns;
+struct ImGuiMenuColumns;
struct ImGuiDrawContext;
struct ImGuiTextEditState;
-struct ImGuiIniData;
-struct ImGuiMouseCursorData;
struct ImGuiPopupRef;
struct ImGuiWindow;
+struct ImGuiWindowSettings;
-typedef int ImGuiLayoutType; // enum ImGuiLayoutType_
-typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_
-typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_
-typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_
+typedef int ImGuiLayoutType; // enum: horizontal or vertical // enum ImGuiLayoutType_
+typedef int ImGuiButtonFlags; // flags: for ButtonEx(), ButtonBehavior() // enum ImGuiButtonFlags_
+typedef int ImGuiItemFlags; // flags: for PushItemFlag() // enum ImGuiItemFlags_
+typedef int ImGuiSeparatorFlags; // flags: for Separator() - internal // enum ImGuiSeparatorFlags_
+typedef int ImGuiSliderFlags; // flags: for SliderBehavior() // enum ImGuiSliderFlags_
//-------------------------------------------------------------------------
// STB libraries
@@ -75,9 +76,7 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointe
// Helpers
//-----------------------------------------------------------------------------
-#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
-#define IM_PI 3.14159265358979323846f
-#define IM_OFFSETOF(_TYPE,_ELM) ((size_t)&(((_TYPE*)0)->_ELM))
+#define IM_PI 3.14159265358979323846f
// Helpers: UTF-8 <> wchar
IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count
@@ -89,20 +88,28 @@ IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, cons
// Helpers: Misc
IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings
IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0);
-IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode);
-IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c);
+IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode);
static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; }
+static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; }
static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
+// Helpers: Geometry
+IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p);
+IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
+IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
+IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w);
+
// Helpers: String
IMGUI_API int ImStricmp(const char* str1, const char* str2);
-IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count);
+IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count);
+IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count);
IMGUI_API char* ImStrdup(const char* str);
+IMGUI_API char* ImStrchrRange(const char* str_begin, const char* str_end, char c);
IMGUI_API int ImStrlenW(const ImWchar* str);
IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line
IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);
-IMGUI_API int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3);
-IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args);
+IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3);
+IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3);
// Helpers: Math
// We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined)
@@ -117,35 +124,46 @@ static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs)
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 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 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
static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; }
static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; }
static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; }
static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; }
-static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); }
-static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); }
+static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); }
+static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); }
static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
+static inline void ImSwap(int& a, int& b) { int tmp = a; a = b; b = tmp; }
+static inline void ImSwap(float& a, float& b) { float tmp = a; a = b; b = tmp; }
+static inline int ImLerp(int a, int b, float t) { return (int)(a + (b - a) * t); }
static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; }
+static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * 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 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 / sqrtf(d); return fail_value; }
static inline float ImFloor(float f) { return (float)(int)f; }
-static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); }
+static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)v.x, (float)(int)v.y); }
+static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; }
+static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); }
+static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; }
+static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
// 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.
-#ifdef IMGUI_DEFINE_PLACEMENT_NEW
-struct ImPlacementNewDummy {};
-inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; }
-inline void operator delete(void*, ImPlacementNewDummy, void*) {}
-#define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR)
-#endif
+struct ImNewPlacementDummy {};
+inline void* operator new(size_t, ImNewPlacementDummy, void* ptr) { return ptr; }
+inline void operator delete(void*, ImNewPlacementDummy, void*) {} // This is only required so we can use the symetrical new()
+#define IM_PLACEMENT_NEW(_PTR) new(ImNewPlacementDummy(), _PTR)
+#define IM_NEW(_TYPE) new(ImNewPlacementDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE
+template void IM_DELETE(T*& p) { if (p) { p->~T(); ImGui::MemFree(p); p = NULL; } }
//-----------------------------------------------------------------------------
// Types
@@ -154,16 +172,18 @@ inline void operator delete(void*, ImPlacementNewDummy, void*) {}
enum ImGuiButtonFlags_
{
ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat
- ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set)
- ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release)
- ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release)
- ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release)
- ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping
- ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press
- ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction
- ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only
- ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held
- ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable
+ ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // return true on click + release on same item [DEFAULT if no PressedOn* flag is set]
+ ImGuiButtonFlags_PressedOnClick = 1 << 2, // return true on click (default requires click+release)
+ ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return true on release (default requires click+release)
+ ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return true on double-click (default requires click+release)
+ ImGuiButtonFlags_FlattenChildren = 1 << 5, // allow interactions even if a child window is overlapping
+ ImGuiButtonFlags_AllowItemOverlap = 1 << 6, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap()
+ ImGuiButtonFlags_DontClosePopups = 1 << 7, // disable automatically closing parent popup on press // [UNUSED]
+ ImGuiButtonFlags_Disabled = 1 << 8, // disable interactions
+ ImGuiButtonFlags_AlignTextBaseLine = 1 << 9, // 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 << 10, // disable interaction if a key modifier is held
+ ImGuiButtonFlags_NoHoldingActiveID = 1 << 11, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)
+ ImGuiButtonFlags_PressedOnDragDropHold = 1 << 12 // press when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)
};
enum ImGuiSliderFlags_
@@ -171,15 +191,31 @@ enum ImGuiSliderFlags_
ImGuiSliderFlags_Vertical = 1 << 0
};
+enum ImGuiColumnsFlags_
+{
+ // Default: 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.
+};
+
enum ImGuiSelectableFlagsPrivate_
{
// NB: need to be in sync with last value of ImGuiSelectableFlags_
- ImGuiSelectableFlags_Menu = 1 << 3,
- ImGuiSelectableFlags_MenuItem = 1 << 4,
+ ImGuiSelectableFlags_Menu = 1 << 3, // -> PressedOnClick
+ ImGuiSelectableFlags_MenuItem = 1 << 4, // -> PressedOnRelease
ImGuiSelectableFlags_Disabled = 1 << 5,
ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6
};
+enum ImGuiSeparatorFlags_
+{
+ ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar
+ ImGuiSeparatorFlags_Vertical = 1 << 1
+};
+
// FIXME: this is in development, not exposed/functional as a generic feature yet.
enum ImGuiLayoutType_
{
@@ -187,6 +223,13 @@ enum ImGuiLayoutType_
ImGuiLayoutType_Horizontal
};
+enum ImGuiAxis
+{
+ ImGuiAxis_None = -1,
+ ImGuiAxis_X = 0,
+ ImGuiAxis_Y = 1
+};
+
enum ImGuiPlotType
{
ImGuiPlotType_Lines,
@@ -197,16 +240,17 @@ enum ImGuiDataType
{
ImGuiDataType_Int,
ImGuiDataType_Float,
- ImGuiDataType_Float2,
+ ImGuiDataType_Float2
};
-enum ImGuiCorner
+enum ImGuiDir
{
- ImGuiCorner_TopLeft = 1 << 0, // 1
- ImGuiCorner_TopRight = 1 << 1, // 2
- ImGuiCorner_BottomRight = 1 << 2, // 4
- ImGuiCorner_BottomLeft = 1 << 3, // 8
- ImGuiCorner_All = 0x0F
+ ImGuiDir_None = -1,
+ ImGuiDir_Left = 0,
+ ImGuiDir_Right = 1,
+ ImGuiDir_Up = 2,
+ ImGuiDir_Down = 3,
+ ImGuiDir_Count_
};
// 2D axis aligned bounding-box
@@ -221,34 +265,27 @@ struct IMGUI_API ImRect
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& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; }
- void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.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 Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; }
- void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; }
- void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; }
- ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const
- {
- if (!on_edge && Contains(p))
- return p;
- if (p.x > Max.x) p.x = Max.x;
- else if (p.x < Min.x) p.x = Min.x;
- if (p.y > Max.y) p.y = Max.y;
- else if (p.y < Min.y) p.y = Min.y;
- return p;
- }
+ 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& v) { Min.x += v.x; Min.y += v.y; Max.x += v.x; Max.y += v.y; }
+ 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 = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; }
+ void FixInverted() { if (Min.x > Max.x) ImSwap(Min.x, Max.x); if (Min.y > Max.y) ImSwap(Min.y, Max.y); }
+ bool IsFinite() const { return Min.x != FLT_MAX; }
};
// Stacked color modifier, backup of modified data so we can restore it
@@ -282,22 +319,15 @@ struct ImGuiGroupData
bool AdvanceCursor;
};
-// Per column data for Columns()
-struct ImGuiColumnData
-{
- float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
- //float IndentX;
-};
-
// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper.
-struct IMGUI_API ImGuiSimpleColumns
+struct IMGUI_API ImGuiMenuColumns
{
int Count;
float Spacing;
float Width, NextWidth;
- float Pos[8], NextWidths[8];
+ float Pos[4], NextWidths[4];
- ImGuiSimpleColumns();
+ ImGuiMenuColumns();
void Update(int count, float spacing, bool clear);
float DeclColumns(float w0, float w1, float w2);
float CalcExtraSpace(float avail_w);
@@ -323,40 +353,147 @@ struct IMGUI_API ImGuiTextEditState
void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); }
bool HasSelection() const { return StbState.select_start != StbState.select_end; }
void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; }
- void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; }
+ void SelectAll() { StbState.select_start = 0; StbState.cursor = StbState.select_end = CurLenW; StbState.has_preferred_x = false; }
void OnKeyPressed(int key);
};
// Data saved in imgui.ini file
-struct ImGuiIniData
+struct ImGuiWindowSettings
{
char* Name;
ImGuiID Id;
ImVec2 Pos;
ImVec2 Size;
bool Collapsed;
+
+ ImGuiWindowSettings() { Name = NULL; Id = 0; Pos = Size = ImVec2(0,0); Collapsed = false; }
};
-// Mouse cursor data (used when io.MouseDrawCursor is set)
-struct ImGuiMouseCursorData
+struct ImGuiSettingsHandler
{
- ImGuiMouseCursor Type;
- ImVec2 HotOffset;
- ImVec2 Size;
- ImVec2 TexUvMin[2];
- ImVec2 TexUvMax[2];
+ const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']'
+ ImGuiID TypeHash; // == ImHash(TypeName, 0, 0)
+ void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name);
+ void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line);
+ void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf);
+ void* UserData;
+
+ ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }
};
// Storage for current popup stack
struct ImGuiPopupRef
{
- ImGuiID PopupId; // Set on OpenPopup()
- ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()
- ImGuiWindow* ParentWindow; // Set on OpenPopup()
- ImGuiID ParentMenuSet; // Set on OpenPopup()
- ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup
+ ImGuiID PopupId; // Set on OpenPopup()
+ ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()
+ ImGuiWindow* ParentWindow; // Set on OpenPopup()
+ int OpenFrameCount; // Set on OpenPopup()
+ ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differenciate multiple menu sets from each others (e.g. inside menu bar vs loose menu items)
+ ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse)
+ ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup
+};
- ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupId = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; }
+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 = 0; }
+};
+
+struct ImGuiColumnsSet
+{
+ ImGuiID ID;
+ ImGuiColumnsFlags Flags;
+ bool IsFirstFrame;
+ bool IsBeingResized;
+ int Current;
+ int Count;
+ float MinX, MaxX;
+ float StartPosY;
+ float StartMaxPosX; // Backup of CursorMaxPos
+ float CellMinY, CellMaxY;
+ ImVector Columns;
+
+ ImGuiColumnsSet() { Clear(); }
+ void Clear()
+ {
+ ID = 0;
+ Flags = 0;
+ IsFirstFrame = false;
+ IsBeingResized = false;
+ Current = 0;
+ Count = 1;
+ MinX = MaxX = 0.0f;
+ StartPosY = 0.0f;
+ StartMaxPosX = 0.0f;
+ CellMinY = CellMaxY = 0.0f;
+ Columns.clear();
+ }
+};
+
+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;
+ ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen()
+
+ // Const data
+ // FIXME: Bake rounded corners fill/borders in atlas
+ ImVec2 CircleVtx12[12];
+
+ ImDrawListSharedData();
+};
+
+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();
+};
+
+// Storage for SetNexWindow** functions
+struct ImGuiNextWindowData
+{
+ ImGuiCond PosCond;
+ ImGuiCond SizeCond;
+ ImGuiCond ContentSizeCond;
+ ImGuiCond CollapsedCond;
+ ImGuiCond SizeConstraintCond;
+ ImGuiCond FocusCond;
+ ImGuiCond BgAlphaCond;
+ ImVec2 PosVal;
+ ImVec2 PosPivotVal;
+ ImVec2 SizeVal;
+ ImVec2 ContentSizeVal;
+ bool CollapsedVal;
+ ImRect SizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true
+ ImGuiSizeCallback SizeCallback;
+ void* SizeCallbackUserData;
+ float BgAlphaVal;
+
+ ImGuiNextWindowData()
+ {
+ PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0;
+ PosVal = PosPivotVal = SizeVal = ImVec2(0.0f, 0.0f);
+ ContentSizeVal = ImVec2(0.0f, 0.0f);
+ CollapsedVal = false;
+ SizeConstraintRect = ImRect();
+ SizeCallback = NULL;
+ SizeCallbackUserData = NULL;
+ BgAlphaVal = FLT_MAX;
+ }
+
+ void Clear()
+ {
+ PosCond = SizeCond = ContentSizeCond = CollapsedCond = SizeConstraintCond = FocusCond = BgAlphaCond = 0;
+ }
};
// Main state for ImGui
@@ -366,9 +503,9 @@ struct ImGuiContext
ImGuiIO IO;
ImGuiStyle Style;
ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
- float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize()
- float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters.
- ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel
+ float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window.
+ float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height.
+ ImDrawListSharedData DrawListSharedData;
float Time;
int FrameCount;
@@ -376,71 +513,77 @@ struct ImGuiContext
int FrameCountRendered;
ImVector Windows;
ImVector WindowsSortBuffer;
- ImGuiWindow* CurrentWindow; // Being drawn into
ImVector CurrentWindowStack;
- ImGuiWindow* FocusedWindow; // Will catch keyboard inputs
+ ImGuiStorage WindowsById;
+ int WindowsActiveCount;
+ ImGuiWindow* CurrentWindow; // Being drawn into
+ ImGuiWindow* NavWindow; // Nav/focused window for navigation
ImGuiWindow* HoveredWindow; // Will catch mouse inputs
ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
ImGuiID HoveredId; // Hovered widget
bool HoveredIdAllowOverlap;
ImGuiID HoveredIdPreviousFrame;
+ float HoveredIdTimer;
ImGuiID ActiveId; // Active widget
ImGuiID ActiveIdPreviousFrame;
- bool ActiveIdIsAlive;
+ float ActiveIdTimer;
+ bool ActiveIdIsAlive; // Active widget has been seen this frame
bool ActiveIdIsJustActivated; // Set at the time of activation for one frame
- bool ActiveIdAllowOverlap; // Set only by active widget
+ bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always)
ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
ImGuiWindow* ActiveIdWindow;
- ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window.
- ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId
- ImVector Settings; // .ini Settings
- float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero
+ ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow.
ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
ImVector FontStack; // Stack for PushFont()/PopFont()
ImVector OpenPopupStack; // Which popups are open (persistent)
ImVector CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame)
-
- // Storage for SetNexWindow** and SetNextTreeNode*** functions
- ImVec2 SetNextWindowPosVal;
- ImVec2 SetNextWindowSizeVal;
- ImVec2 SetNextWindowContentSizeVal;
- bool SetNextWindowCollapsedVal;
- ImGuiSetCond SetNextWindowPosCond;
- ImGuiSetCond SetNextWindowSizeCond;
- ImGuiSetCond SetNextWindowContentSizeCond;
- ImGuiSetCond SetNextWindowCollapsedCond;
- ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true
- ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback;
- void* SetNextWindowSizeConstraintCallbackUserData;
- bool SetNextWindowSizeConstraint;
- bool SetNextWindowFocus;
- bool SetNextTreeNodeOpenVal;
- ImGuiSetCond SetNextTreeNodeOpenCond;
+ ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions
+ bool NextTreeNodeOpenVal; // Storage for SetNextTreeNode** functions
+ ImGuiCond NextTreeNodeOpenCond;
// Render
- ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user
- ImVector RenderDrawLists[3];
+ ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user
+ ImDrawDataBuilder DrawDataBuilder;
float ModalWindowDarkeningRatio;
ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays
ImGuiMouseCursor MouseCursor;
- ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_];
+
+ // Drag and Drop
+ bool DragDropActive;
+ ImGuiDragDropFlags DragDropSourceFlags;
+ int DragDropMouseButton;
+ ImGuiPayload DragDropPayload;
+ ImRect DragDropTargetRect;
+ ImGuiID DragDropTargetId;
+ float DragDropAcceptIdCurrRectSurface;
+ ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload)
+ ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets)
+ int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source
+ ImVector DragDropPayloadBufHeap; // We don't expose the ImVector<> directly
+ unsigned char DragDropPayloadBufLocal[8];
// Widget state
ImGuiTextEditState InputTextState;
ImFont InputTextPasswordFont;
ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc.
- ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode
+ ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets
+ ImVec4 ColorPickerRef;
float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings
ImVec2 DragLastMouseDelta;
float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
float DragSpeedScaleSlow;
float DragSpeedScaleFast;
ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage?
- char Tooltip[1024];
- char* PrivateClipboard; // If no custom clipboard handler is defined
+ int TooltipOverrideCount;
+ ImVector PrivateClipboard; // If no custom clipboard handler is defined
ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor
+ // Settings
+ float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero
+ ImVector SettingsWindows; // .ini settings for ImGuiWindow
+ ImVector SettingsHandlers; // List of .ini settings handlers
+
// Logging
bool LogEnabled;
FILE* LogFile; // If != NULL log to stdout/ file
@@ -452,68 +595,67 @@ struct ImGuiContext
float FramerateSecPerFrame[120]; // calculate estimate of framerate for user
int FramerateSecPerFrameIdx;
float FramerateSecPerFrameAccum;
- int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags
- int CaptureKeyboardNextFrame;
+ int WantCaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags
+ int WantCaptureKeyboardNextFrame;
+ int WantTextInputNextFrame;
char TempBuffer[1024*3+1]; // temporary text buffer
- ImGuiContext()
+ ImGuiContext() : OverlayDrawList(NULL)
{
Initialized = false;
Font = NULL;
FontSize = FontBaseSize = 0.0f;
- FontTexUvWhitePixel = ImVec2(0.0f, 0.0f);
Time = 0.0f;
FrameCount = 0;
FrameCountEnded = FrameCountRendered = -1;
+ WindowsActiveCount = 0;
CurrentWindow = NULL;
- FocusedWindow = NULL;
+ NavWindow = NULL;
HoveredWindow = NULL;
HoveredRootWindow = NULL;
HoveredId = 0;
HoveredIdAllowOverlap = false;
HoveredIdPreviousFrame = 0;
+ HoveredIdTimer = 0.0f;
ActiveId = 0;
ActiveIdPreviousFrame = 0;
+ ActiveIdTimer = 0.0f;
ActiveIdIsAlive = false;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
ActiveIdClickOffset = ImVec2(-1,-1);
ActiveIdWindow = NULL;
- MovedWindow = NULL;
- MovedWindowMoveId = 0;
- SettingsDirtyTimer = 0.0f;
+ MovingWindow = NULL;
+ NextTreeNodeOpenVal = false;
+ NextTreeNodeOpenCond = 0;
- SetNextWindowPosVal = ImVec2(0.0f, 0.0f);
- SetNextWindowSizeVal = ImVec2(0.0f, 0.0f);
- SetNextWindowCollapsedVal = false;
- SetNextWindowPosCond = 0;
- SetNextWindowSizeCond = 0;
- SetNextWindowContentSizeCond = 0;
- SetNextWindowCollapsedCond = 0;
- SetNextWindowSizeConstraintRect = ImRect();
- SetNextWindowSizeConstraintCallback = NULL;
- SetNextWindowSizeConstraintCallbackUserData = NULL;
- SetNextWindowSizeConstraint = false;
- SetNextWindowFocus = false;
- SetNextTreeNodeOpenVal = false;
- SetNextTreeNodeOpenCond = 0;
+ ModalWindowDarkeningRatio = 0.0f;
+ OverlayDrawList._Data = &DrawListSharedData;
+ OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging
+ MouseCursor = ImGuiMouseCursor_Arrow;
+
+ DragDropActive = false;
+ DragDropSourceFlags = 0;
+ DragDropMouseButton = -1;
+ DragDropTargetId = 0;
+ DragDropAcceptIdCurrRectSurface = 0.0f;
+ DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
+ DragDropAcceptFrameCount = -1;
+ memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
ScalarAsInputTextId = 0;
+ ColorEditOptions = ImGuiColorEditFlags__OptionsDefault;
DragCurrentValue = 0.0f;
DragLastMouseDelta = ImVec2(0.0f, 0.0f);
DragSpeedDefaultRatio = 1.0f / 100.0f;
- DragSpeedScaleSlow = 0.01f;
+ DragSpeedScaleSlow = 1.0f / 100.0f;
DragSpeedScaleFast = 10.0f;
ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f);
- memset(Tooltip, 0, sizeof(Tooltip));
- PrivateClipboard = NULL;
+ TooltipOverrideCount = 0;
OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f);
- ModalWindowDarkeningRatio = 0.0f;
- OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging
- MouseCursor = ImGuiMouseCursor_Arrow;
- memset(MouseCursorData, 0, sizeof(MouseCursorData));
+ SettingsDirtyTimer = 0.0f;
LogEnabled = false;
LogFile = NULL;
@@ -524,11 +666,23 @@ struct ImGuiContext
memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
FramerateSecPerFrameIdx = 0;
FramerateSecPerFrameAccum = 0.0f;
- CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1;
+ WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
memset(TempBuffer, 0, sizeof(TempBuffer));
}
};
+// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin().
+enum ImGuiItemFlags_
+{
+ ImGuiItemFlags_AllowKeyboardFocus = 1 << 0, // true
+ ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings.
+ ImGuiItemFlags_Disabled = 1 << 2, // false // FIXME-WIP: Disable interactions but doesn't affect visuals. Should be: grey out and disable interactions with widgets that affect data + view widgets (WIP)
+ //ImGuiItemFlags_NoNav = 1 << 3, // false
+ //ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false
+ ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window
+ ImGuiItemFlags_Default_ = ImGuiItemFlags_AllowKeyboardFocus
+};
+
// Transient per-window data, reset at the beginning of the frame
// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered.
struct IMGUI_API ImGuiDrawContext
@@ -536,7 +690,7 @@ struct IMGUI_API ImGuiDrawContext
ImVec2 CursorPos;
ImVec2 CursorPosPrevLine;
ImVec2 CursorStartPos;
- ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame
+ ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Turned into window->SizeContents at the beginning of next frame
float CurrentLineHeight;
float CurrentLineTextBaseOffset;
float PrevLineHeight;
@@ -545,8 +699,7 @@ struct IMGUI_API ImGuiDrawContext
int TreeDepth;
ImGuiID LastItemId;
ImRect LastItemRect;
- bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window)
- bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window)
+ bool LastItemRectHoveredRect;
bool MenuBarAppending;
float MenuBarOffsetX;
ImVector ChildWindows;
@@ -554,31 +707,19 @@ struct IMGUI_API ImGuiDrawContext
ImGuiLayoutType LayoutType;
// We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings.
+ ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default]
float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window
float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f]
- bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true]
- bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false]
+ ImVectorItemFlagsStack;
ImVector ItemWidthStack;
ImVector TextWrapPosStack;
- ImVector AllowKeyboardFocusStack;
- ImVector ButtonRepeatStack;
ImVectorGroupStack;
- ImGuiColorEditMode ColorEditMode;
int StackSizesBackup[6]; // Store size of various stacks for asserting
float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
float GroupOffsetX;
float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.
- int ColumnsCurrent;
- int ColumnsCount;
- float ColumnsMinX;
- float ColumnsMaxX;
- float ColumnsStartPosY;
- float ColumnsCellMinY;
- float ColumnsCellMaxY;
- bool ColumnsShowBorders;
- ImGuiID ColumnsSetId;
- ImVector ColumnsData;
+ ImGuiColumnsSet* ColumnsSet; // Current columns set
ImGuiDrawContext()
{
@@ -588,29 +729,21 @@ struct IMGUI_API ImGuiDrawContext
LogLinePosY = -1.0f;
TreeDepth = 0;
LastItemId = 0;
- LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f);
- LastItemHoveredAndUsable = LastItemHoveredRect = false;
+ LastItemRect = ImRect();
+ LastItemRectHoveredRect = false;
MenuBarAppending = false;
MenuBarOffsetX = 0.0f;
StateStorage = NULL;
LayoutType = ImGuiLayoutType_Vertical;
ItemWidth = 0.0f;
- ButtonRepeat = false;
- AllowKeyboardFocus = true;
+ ItemFlags = ImGuiItemFlags_Default_;
TextWrapPos = -1.0f;
- ColorEditMode = ImGuiColorEditMode_RGB;
memset(StackSizesBackup, 0, sizeof(StackSizesBackup));
IndentX = 0.0f;
GroupOffsetX = 0.0f;
ColumnsOffsetX = 0.0f;
- ColumnsCurrent = 0;
- ColumnsCount = 1;
- ColumnsMinX = ColumnsMaxX = 0.0f;
- ColumnsStartPosY = 0.0f;
- ColumnsCellMinY = ColumnsCellMaxY = 0.0f;
- ColumnsShowBorders = true;
- ColumnsSetId = 0;
+ ColumnsSet = NULL;
}
};
@@ -620,51 +753,60 @@ struct IMGUI_API ImGuiWindow
char* Name;
ImGuiID ID; // == ImHash(Name)
ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_
- int IndexWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0.
ImVec2 PosFloat;
ImVec2 Pos; // Position rounded-up to nearest pixel
ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
ImVec2 SizeFull; // Size when non collapsed
- ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame
+ ImVec2 SizeFullAtLastBegin; // Copy of SizeFull at the end of Begin. This is the reference value we'll use on the next frame to decide if we need scrollbars.
+ ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame. Include decoration, window title, border, menu, etc.
ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize()
ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis
- ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect
+ ImVec2 WindowPadding; // Window padding at the time of begin.
+ float WindowRounding; // Window rounding at the time of begin.
+ float WindowBorderSize; // Window border size at the time of begin.
ImGuiID MoveId; // == window->GetID("#MOVE")
ImVec2 Scroll;
ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change)
ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered
bool ScrollbarX, ScrollbarY;
ImVec2 ScrollbarSizes;
- float BorderSize;
- bool Active; // Set to true on Begin()
+ bool Active; // Set to true on Begin(), unless Collapsed
bool WasActive;
- bool Accessed; // Set to true when any widget access the current window
+ bool WriteAccessed; // Set to true when any widget access the current window
bool Collapsed; // Set when collapsing window to become only title-bar
- bool SkipItems; // == Visible && !Collapsed
+ 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 CloseButton; // Set when the window has a close button (p_open != NULL)
+ int BeginOrderWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0.
+ int BeginOrderWithinContext; // Order within entire imgui context. This is mostly used for debugging submission order related issues.
int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)
ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling)
int AutoFitFramesX, AutoFitFramesY;
bool AutoFitOnlyGrows;
- int AutoPosLastDirection;
+ int AutoFitChildAxises;
+ ImGuiDir AutoPosLastDirection;
int HiddenFrames;
- int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag.
- int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag.
- int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag.
- bool SetWindowPosCenterWanted;
+ ImGuiCond SetWindowPosAllowFlags; // store condition flags for next SetWindowPos() call.
+ ImGuiCond SetWindowSizeAllowFlags; // store condition flags for next SetWindowSize() call.
+ ImGuiCond SetWindowCollapsedAllowFlags; // store condition flags for next SetWindowCollapsed() call.
+ 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.
ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame
ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack
ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2.
ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window.
+ ImRect InnerRect;
int LastFrameActive;
float ItemWidthDefault;
- ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items
+ ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items
ImGuiStorage StateStorage;
+ ImVector ColumnsStorage;
float FontWindowScale; // Scale multiplier per-window
ImDrawList* DrawList;
- ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself.
- ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself.
- ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL.
+ ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL.
+ ImGuiWindow* RootWindow; // Generally point to ourself. If we are a child window, this is pointing to the first non-child parent window.
+ ImGuiWindow* RootNonPopupWindow; // Generally point to ourself. Used to display TitleBgActive color and for selecting which window to use for NavWindowing
// Navigation / Focus
int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister()
@@ -675,13 +817,15 @@ struct IMGUI_API ImGuiWindow
int FocusIdxTabRequestNext; // "
public:
- ImGuiWindow(const char* name);
+ ImGuiWindow(ImGuiContext* context, const char* name);
~ImGuiWindow();
ImGuiID GetID(const char* str, const char* str_end = NULL);
ImGuiID GetID(const void* ptr);
ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL);
+ 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 { return GImGui->FontBaseSize * FontWindowScale; }
float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; }
@@ -690,6 +834,18 @@ public:
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
+{
+ ImGuiID LastItemId;
+ ImRect LastItemRect;
+ bool LastItemRectHoveredRect;
+
+ ImGuiItemHoveredDataBackup() { Backup(); }
+ void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemRect = window->DC.LastItemRect; LastItemRectHoveredRect = window->DC.LastItemRectHoveredRect; }
+ void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemRect = LastItemRect; window->DC.LastItemRectHoveredRect = LastItemRectHoveredRect; }
+};
+
//-----------------------------------------------------------------------------
// Internal API
// No guarantee of forward compatibility here.
@@ -702,45 +858,79 @@ namespace ImGui
// - ImGui::NewFrame() has never been called, which is illegal.
// - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; }
- inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; }
- IMGUI_API ImGuiWindow* GetParentWindow();
+ inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; }
IMGUI_API ImGuiWindow* FindWindowByName(const char* name);
IMGUI_API void FocusWindow(ImGuiWindow* window);
+ IMGUI_API void BringWindowToFront(ImGuiWindow* window);
+ IMGUI_API void BringWindowToBack(ImGuiWindow* window);
+ IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent);
- IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead!
+ IMGUI_API void Initialize();
+
+ IMGUI_API void MarkIniSettingsDirty();
+ IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name);
+ IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id);
IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
- IMGUI_API void ClearActiveID();
+ IMGUI_API void ClearActiveID();
IMGUI_API void SetHoveredID(ImGuiID id);
+ IMGUI_API ImGuiID GetHoveredID();
IMGUI_API void KeepAliveID(ImGuiID id);
IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f);
IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f);
- IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id);
- IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged);
- IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false);
- IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop = true); // Return true if focus is requested
+ IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id);
+ 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 bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop = true); // Return true if focus is requested
IMGUI_API void FocusableItemUnregister(ImGuiWindow* window);
IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y);
IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x);
+ IMGUI_API void PushMultiItemsWidths(int components, float width_full = 0.0f);
+ IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled);
+ IMGUI_API void PopItemFlag();
- IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing);
+ IMGUI_API void SetCurrentFont(ImFont* font);
- // NB: All position are in absolute pixels coordinates (not window coordinates)
- // FIXME: All those functions are a mess and needs to be refactored into something decent. AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION.
- // We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers.
+ IMGUI_API void OpenPopupEx(ImGuiID id);
+ IMGUI_API void ClosePopup(ImGuiID id);
+ IMGUI_API bool IsPopupOpen(ImGuiID id);
+ IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags);
+ IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip = true);
+
+ IMGUI_API int CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate);
+
+ IMGUI_API void Scrollbar(ImGuiLayoutType direction);
+ IMGUI_API void VerticalSeparator(); // Vertical separator, for menu bars (use current line height). not exposed because it is misleading what it doesn't have an effect on regular layout.
+ IMGUI_API bool SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f);
+
+ IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id);
+ IMGUI_API void ClearDragDrop();
+ IMGUI_API bool IsDragDropPayloadBeingAccepted();
+
+ // FIXME-WIP: New Columns API
+ IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns().
+ IMGUI_API void EndColumns(); // close columns
+ IMGUI_API void PushColumnClipRect(int column_index = -1);
+
+ // NB: All position are in absolute pixels coordinates (never using window coordinates internally)
+ // 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.
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 RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
- IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f);
+ IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f);
+ IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0);
+ IMGUI_API void RenderTriangle(ImVec2 pos, ImGuiDir dir, float scale = 1.0f);
IMGUI_API void RenderBullet(ImVec2 pos);
- IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col);
+ IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col, float sz);
+ IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding);
IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.
IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, 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, float radius);
+ IMGUI_API bool ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags = 0);
IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0);
IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power);
@@ -756,6 +946,9 @@ namespace ImGui
IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags);
IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision);
+ IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags);
+ IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags);
+
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 SetNextTreeNodeOpened() data, if any. May return true when logging
IMGUI_API void TreePushRawID(ImGuiID id);
@@ -765,8 +958,22 @@ namespace ImGui
IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value);
IMGUI_API float RoundScalar(float value, int decimal_precision);
+ // Shade functions
+ IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawVert* vert_start, ImDrawVert* vert_end, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1);
+ IMGUI_API void ShadeVertsLinearAlphaGradientForLeftToRightText(ImDrawVert* vert_start, ImDrawVert* vert_end, float gradient_p0_x, float gradient_p1_x);
+ IMGUI_API void ShadeVertsLinearUV(ImDrawVert* vert_start, ImDrawVert* vert_end, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp);
+
} // namespace ImGui
+// ImFontAtlas internals
+IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildRegisterDefaultCustomRects(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent);
+IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* spc);
+IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas);
+IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor);
+IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride);
+
#ifdef __clang__
#pragma clang diagnostic pop
#endif
diff --git a/stb_truetype.h b/stb_truetype.h
index 88a2da16e..92b9a8754 100644
--- a/stb_truetype.h
+++ b/stb_truetype.h
@@ -1,4 +1,4 @@
-// stb_truetype.h - v1.12 - public domain
+// stb_truetype.h - v1.14 - public domain
// authored from 2009-2016 by Sean Barrett / RAD Game Tools
//
// This library processes TrueType files:
@@ -20,10 +20,12 @@
//
// Mikko Mononen: compound shape support, more cmap formats
// Tor Andersson: kerning, subpixel rendering
+// Dougall Johnson: OpenType / Type 2 font handling
//
// Misc other:
// Ryan Gordon
// Simon Glass
+// github:IntellectualKitty
//
// Bug/warning reports/fixes:
// "Zer" on mollyrocket (with fix)
@@ -51,6 +53,7 @@
//
// VERSION HISTORY
//
+// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts, num-fonts-in-TTC function
// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.11 (2016-04-02) fix unused-variable warning
// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef
@@ -95,7 +98,8 @@
//
// "Load" a font file from a memory buffer (you have to keep the buffer loaded)
// stbtt_InitFont()
-// stbtt_GetFontOffsetForIndex() -- use for TTC font collections
+// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections
+// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections
//
// Render a unicode codepoint to a bitmap
// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
@@ -453,6 +457,14 @@ int main(int arg, char **argv)
extern "C" {
#endif
+// private structure
+typedef struct
+{
+ unsigned char *data;
+ int cursor;
+ int size;
+} stbtt__buf;
+
//////////////////////////////////////////////////////////////////////////////
//
// TEXTURE BAKING API
@@ -522,7 +534,7 @@ typedef struct stbrp_rect stbrp_rect;
STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
// Initializes a packing context stored in the passed-in stbtt_pack_context.
// Future calls using this context will pack characters into the bitmap passed
-// in here: a 1-channel bitmap that is weight x height. stride_in_bytes is
+// in here: a 1-channel bitmap that is width * height. stride_in_bytes is
// the distance from one row to the next (or 0 to mean they are packed tightly
// together). "padding" is the amount of padding to leave between each
// character (normally you want '1' for bitmaps you'll use as textures with
@@ -621,14 +633,19 @@ struct stbtt_pack_context {
//
//
+STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);
+// This function will determine the number of fonts in a font file. TrueType
+// collection (.ttc) files may contain multiple fonts, while TrueType font
+// (.ttf) files only contain one font. The number of fonts can be used for
+// indexing with the previous function where the index is between zero and one
+// less than the total fonts. If an error occurs, -1 is returned.
+
STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
// Each .ttf/.ttc file may have more than one font. Each font has a sequential
// index number starting from 0. Call this function to get the font offset for
// a given index; it returns -1 if the index is out of range. A regular .ttf
// file will only define one font and it always be at offset 0, so it will
-// return '0' for index 0, and -1 for all other indices. You can just skip
-// this step if you know it's that kind of font.
-
+// return '0' for index 0, and -1 for all other indices.
// The following structure is defined publically so you can declare one on
// the stack or as a global or etc, but you should treat it as opaque.
@@ -643,6 +660,13 @@ struct stbtt_fontinfo
int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
int index_map; // a cmap mapping for our chosen character encoding
int indexToLocFormat; // format needed to map from glyph index to glyph
+
+ stbtt__buf cff; // cff font data
+ stbtt__buf charstrings; // the charstring index
+ stbtt__buf gsubrs; // global charstring subroutines index
+ stbtt__buf subrs; // private charstring subroutines index
+ stbtt__buf fontdicts; // array of font dicts
+ stbtt__buf fdselect; // map from glyph to fontdict
};
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
@@ -720,7 +744,8 @@ STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, in
enum {
STBTT_vmove=1,
STBTT_vline,
- STBTT_vcurve
+ STBTT_vcurve,
+ STBTT_vcubic
};
#endif
@@ -729,7 +754,7 @@ STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, in
#define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
typedef struct
{
- stbtt_vertex_type x,y,cx,cy;
+ stbtt_vertex_type x,y,cx,cy,cx1,cy1;
unsigned char type,padding;
} stbtt_vertex;
#endif
@@ -951,6 +976,152 @@ typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERS
#define STBTT__NOTUSED(v) (void)sizeof(v)
#endif
+//////////////////////////////////////////////////////////////////////////
+//
+// stbtt__buf helpers to parse data from file
+//
+
+static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)
+{
+ if (b->cursor >= b->size)
+ return 0;
+ return b->data[b->cursor++];
+}
+
+static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)
+{
+ if (b->cursor >= b->size)
+ return 0;
+ return b->data[b->cursor];
+}
+
+static void stbtt__buf_seek(stbtt__buf *b, int o)
+{
+ STBTT_assert(!(o > b->size || o < 0));
+ b->cursor = (o > b->size || o < 0) ? b->size : o;
+}
+
+static void stbtt__buf_skip(stbtt__buf *b, int o)
+{
+ stbtt__buf_seek(b, b->cursor + o);
+}
+
+static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)
+{
+ stbtt_uint32 v = 0;
+ int i;
+ STBTT_assert(n >= 1 && n <= 4);
+ for (i = 0; i < n; i++)
+ v = (v << 8) | stbtt__buf_get8(b);
+ return v;
+}
+
+static stbtt__buf stbtt__new_buf(const void *p, size_t size)
+{
+ stbtt__buf r;
+ STBTT_assert(size < 0x40000000);
+ r.data = (stbtt_uint8*) p;
+ r.size = (int) size;
+ r.cursor = 0;
+ return r;
+}
+
+#define stbtt__buf_get16(b) stbtt__buf_get((b), 2)
+#define stbtt__buf_get32(b) stbtt__buf_get((b), 4)
+
+static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)
+{
+ stbtt__buf r = stbtt__new_buf(NULL, 0);
+ if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;
+ r.data = b->data + o;
+ r.size = s;
+ return r;
+}
+
+static stbtt__buf stbtt__cff_get_index(stbtt__buf *b)
+{
+ int count, start, offsize;
+ start = b->cursor;
+ count = stbtt__buf_get16(b);
+ if (count) {
+ offsize = stbtt__buf_get8(b);
+ STBTT_assert(offsize >= 1 && offsize <= 4);
+ stbtt__buf_skip(b, offsize * count);
+ stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);
+ }
+ return stbtt__buf_range(b, start, b->cursor - start);
+}
+
+static stbtt_uint32 stbtt__cff_int(stbtt__buf *b)
+{
+ int b0 = stbtt__buf_get8(b);
+ if (b0 >= 32 && b0 <= 246) return b0 - 139;
+ else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;
+ else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;
+ else if (b0 == 28) return stbtt__buf_get16(b);
+ else if (b0 == 29) return stbtt__buf_get32(b);
+ STBTT_assert(0);
+ return 0;
+}
+
+static void stbtt__cff_skip_operand(stbtt__buf *b) {
+ int v, b0 = stbtt__buf_peek8(b);
+ STBTT_assert(b0 >= 28);
+ if (b0 == 30) {
+ stbtt__buf_skip(b, 1);
+ while (b->cursor < b->size) {
+ v = stbtt__buf_get8(b);
+ if ((v & 0xF) == 0xF || (v >> 4) == 0xF)
+ break;
+ }
+ } else {
+ stbtt__cff_int(b);
+ }
+}
+
+static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)
+{
+ stbtt__buf_seek(b, 0);
+ while (b->cursor < b->size) {
+ int start = b->cursor, end, op;
+ while (stbtt__buf_peek8(b) >= 28)
+ stbtt__cff_skip_operand(b);
+ end = b->cursor;
+ op = stbtt__buf_get8(b);
+ if (op == 12) op = stbtt__buf_get8(b) | 0x100;
+ if (op == key) return stbtt__buf_range(b, start, end-start);
+ }
+ return stbtt__buf_range(b, 0, 0);
+}
+
+static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)
+{
+ int i;
+ stbtt__buf operands = stbtt__dict_get(b, key);
+ for (i = 0; i < outcount && operands.cursor < operands.size; i++)
+ out[i] = stbtt__cff_int(&operands);
+}
+
+static int stbtt__cff_index_count(stbtt__buf *b)
+{
+ stbtt__buf_seek(b, 0);
+ return stbtt__buf_get16(b);
+}
+
+static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)
+{
+ int count, offsize, start, end;
+ stbtt__buf_seek(&b, 0);
+ count = stbtt__buf_get16(&b);
+ offsize = stbtt__buf_get8(&b);
+ STBTT_assert(i >= 0 && i < count);
+ STBTT_assert(offsize >= 1 && offsize <= 4);
+ stbtt__buf_skip(&b, i*offsize);
+ start = stbtt__buf_get(&b, offsize);
+ end = stbtt__buf_get(&b, offsize);
+ return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);
+}
+
//////////////////////////////////////////////////////////////////////////
//
// accessors to parse data from file
@@ -978,6 +1149,7 @@ static int stbtt__isfont(stbtt_uint8 *font)
if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
+ if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts
return 0;
}
@@ -1014,6 +1186,35 @@ static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection,
return -1;
}
+static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)
+{
+ // if it's just a font, there's only one valid font
+ if (stbtt__isfont(font_collection))
+ return 1;
+
+ // check if it's a TTC
+ if (stbtt_tag(font_collection, "ttcf")) {
+ // version 1?
+ if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
+ return ttLONG(font_collection+8);
+ }
+ }
+ return 0;
+}
+
+static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)
+{
+ stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };
+ stbtt__buf pdict;
+ stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);
+ if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);
+ pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);
+ stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);
+ if (!subrsoff) return stbtt__new_buf(NULL, 0);
+ stbtt__buf_seek(&cff, private_loc[1]+subrsoff);
+ return stbtt__cff_get_index(&cff);
+}
+
static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)
{
stbtt_uint32 cmap, t;
@@ -1021,6 +1222,7 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in
info->data = data;
info->fontstart = fontstart;
+ info->cff = stbtt__new_buf(NULL, 0);
cmap = stbtt__find_table(data, fontstart, "cmap"); // required
info->loca = stbtt__find_table(data, fontstart, "loca"); // required
@@ -1029,8 +1231,61 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in
info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
- if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
+
+ if (!cmap || !info->head || !info->hhea || !info->hmtx)
return 0;
+ if (info->glyf) {
+ // required for truetype
+ if (!info->loca) return 0;
+ } else {
+ // initialization for CFF / Type2 fonts (OTF)
+ stbtt__buf b, topdict, topdictidx;
+ stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;
+ stbtt_uint32 cff;
+
+ cff = stbtt__find_table(data, fontstart, "CFF ");
+ if (!cff) return 0;
+
+ info->fontdicts = stbtt__new_buf(NULL, 0);
+ info->fdselect = stbtt__new_buf(NULL, 0);
+
+ // @TODO this should use size from table (not 512MB)
+ info->cff = stbtt__new_buf(data+cff, 512*1024*1024);
+ b = info->cff;
+
+ // read the header
+ stbtt__buf_skip(&b, 2);
+ stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize
+
+ // @TODO the name INDEX could list multiple fonts,
+ // but we just use the first one.
+ stbtt__cff_get_index(&b); // name INDEX
+ topdictidx = stbtt__cff_get_index(&b);
+ topdict = stbtt__cff_index_get(topdictidx, 0);
+ stbtt__cff_get_index(&b); // string INDEX
+ info->gsubrs = stbtt__cff_get_index(&b);
+
+ stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);
+ stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);
+ stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);
+ stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);
+ info->subrs = stbtt__get_subrs(b, topdict);
+
+ // we only support Type 2 charstrings
+ if (cstype != 2) return 0;
+ if (charstrings == 0) return 0;
+
+ if (fdarrayoff) {
+ // looks like a CID font
+ if (!fdselectoff) return 0;
+ stbtt__buf_seek(&b, fdarrayoff);
+ info->fontdicts = stbtt__cff_get_index(&b);
+ info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);
+ }
+
+ stbtt__buf_seek(&b, charstrings);
+ info->charstrings = stbtt__cff_get_index(&b);
+ }
t = stbtt__find_table(data, fontstart, "maxp");
if (t)
@@ -1181,6 +1436,8 @@ static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
{
int g1,g2;
+ STBTT_assert(!info->cff.size);
+
if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
@@ -1195,15 +1452,21 @@ static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
return g1==g2 ? -1 : g1; // if length is 0, return -1
}
+static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
+
STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
{
- int g = stbtt__GetGlyfOffset(info, glyph_index);
- if (g < 0) return 0;
+ if (info->cff.size) {
+ stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);
+ } else {
+ int g = stbtt__GetGlyfOffset(info, glyph_index);
+ if (g < 0) return 0;
- if (x0) *x0 = ttSHORT(info->data + g + 2);
- if (y0) *y0 = ttSHORT(info->data + g + 4);
- if (x1) *x1 = ttSHORT(info->data + g + 6);
- if (y1) *y1 = ttSHORT(info->data + g + 8);
+ if (x0) *x0 = ttSHORT(info->data + g + 2);
+ if (y0) *y0 = ttSHORT(info->data + g + 4);
+ if (x1) *x1 = ttSHORT(info->data + g + 6);
+ if (y1) *y1 = ttSHORT(info->data + g + 8);
+ }
return 1;
}
@@ -1215,7 +1478,10 @@ STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, i
STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
{
stbtt_int16 numberOfContours;
- int g = stbtt__GetGlyfOffset(info, glyph_index);
+ int g;
+ if (info->cff.size)
+ return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;
+ g = stbtt__GetGlyfOffset(info, glyph_index);
if (g < 0) return 1;
numberOfContours = ttSHORT(info->data + g);
return numberOfContours == 0;
@@ -1237,7 +1503,7 @@ static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_
return num_vertices;
}
-STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
+static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
{
stbtt_int16 numberOfContours;
stbtt_uint8 *endPtsOfContours;
@@ -1463,6 +1729,416 @@ STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, s
return num_vertices;
}
+typedef struct
+{
+ int bounds;
+ int started;
+ float first_x, first_y;
+ float x, y;
+ stbtt_int32 min_x, max_x, min_y, max_y;
+
+ stbtt_vertex *pvertices;
+ int num_vertices;
+} stbtt__csctx;
+
+#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}
+
+static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)
+{
+ if (x > c->max_x || !c->started) c->max_x = x;
+ if (y > c->max_y || !c->started) c->max_y = y;
+ if (x < c->min_x || !c->started) c->min_x = x;
+ if (y < c->min_y || !c->started) c->min_y = y;
+ c->started = 1;
+}
+
+static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)
+{
+ if (c->bounds) {
+ stbtt__track_vertex(c, x, y);
+ if (type == STBTT_vcubic) {
+ stbtt__track_vertex(c, cx, cy);
+ stbtt__track_vertex(c, cx1, cy1);
+ }
+ } else {
+ stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);
+ c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;
+ c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;
+ }
+ c->num_vertices++;
+}
+
+static void stbtt__csctx_close_shape(stbtt__csctx *ctx)
+{
+ if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)
+ stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);
+}
+
+static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)
+{
+ stbtt__csctx_close_shape(ctx);
+ ctx->first_x = ctx->x = ctx->x + dx;
+ ctx->first_y = ctx->y = ctx->y + dy;
+ stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
+}
+
+static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)
+{
+ ctx->x += dx;
+ ctx->y += dy;
+ stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);
+}
+
+static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)
+{
+ float cx1 = ctx->x + dx1;
+ float cy1 = ctx->y + dy1;
+ float cx2 = cx1 + dx2;
+ float cy2 = cy1 + dy2;
+ ctx->x = cx2 + dx3;
+ ctx->y = cy2 + dy3;
+ stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);
+}
+
+static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)
+{
+ int count = stbtt__cff_index_count(&idx);
+ int bias = 107;
+ if (count >= 33900)
+ bias = 32768;
+ else if (count >= 1240)
+ bias = 1131;
+ n += bias;
+ if (n < 0 || n >= count)
+ return stbtt__new_buf(NULL, 0);
+ return stbtt__cff_index_get(idx, n);
+}
+
+static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)
+{
+ stbtt__buf fdselect = info->fdselect;
+ int nranges, start, end, v, fmt, fdselector = -1, i;
+
+ stbtt__buf_seek(&fdselect, 0);
+ fmt = stbtt__buf_get8(&fdselect);
+ if (fmt == 0) {
+ // untested
+ stbtt__buf_skip(&fdselect, glyph_index);
+ fdselector = stbtt__buf_get8(&fdselect);
+ } else if (fmt == 3) {
+ nranges = stbtt__buf_get16(&fdselect);
+ start = stbtt__buf_get16(&fdselect);
+ for (i = 0; i < nranges; i++) {
+ v = stbtt__buf_get8(&fdselect);
+ end = stbtt__buf_get16(&fdselect);
+ if (glyph_index >= start && glyph_index < end) {
+ fdselector = v;
+ break;
+ }
+ start = end;
+ }
+ }
+ if (fdselector == -1) stbtt__new_buf(NULL, 0);
+ return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));
+}
+
+static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)
+{
+ int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;
+ int has_subrs = 0, clear_stack;
+ float s[48];
+ stbtt__buf subr_stack[10], subrs = info->subrs, b;
+ float f;
+
+#define STBTT__CSERR(s) (0)
+
+ // this currently ignores the initial width value, which isn't needed if we have hmtx
+ b = stbtt__cff_index_get(info->charstrings, glyph_index);
+ while (b.cursor < b.size) {
+ i = 0;
+ clear_stack = 1;
+ b0 = stbtt__buf_get8(&b);
+ switch (b0) {
+ // @TODO implement hinting
+ case 0x13: // hintmask
+ case 0x14: // cntrmask
+ if (in_header)
+ maskbits += (sp / 2); // implicit "vstem"
+ in_header = 0;
+ stbtt__buf_skip(&b, (maskbits + 7) / 8);
+ break;
+
+ case 0x01: // hstem
+ case 0x03: // vstem
+ case 0x12: // hstemhm
+ case 0x17: // vstemhm
+ maskbits += (sp / 2);
+ break;
+
+ case 0x15: // rmoveto
+ in_header = 0;
+ if (sp < 2) return STBTT__CSERR("rmoveto stack");
+ stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);
+ break;
+ case 0x04: // vmoveto
+ in_header = 0;
+ if (sp < 1) return STBTT__CSERR("vmoveto stack");
+ stbtt__csctx_rmove_to(c, 0, s[sp-1]);
+ break;
+ case 0x16: // hmoveto
+ in_header = 0;
+ if (sp < 1) return STBTT__CSERR("hmoveto stack");
+ stbtt__csctx_rmove_to(c, s[sp-1], 0);
+ break;
+
+ case 0x05: // rlineto
+ if (sp < 2) return STBTT__CSERR("rlineto stack");
+ for (; i + 1 < sp; i += 2)
+ stbtt__csctx_rline_to(c, s[i], s[i+1]);
+ break;
+
+ // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
+ // starting from a different place.
+
+ case 0x07: // vlineto
+ if (sp < 1) return STBTT__CSERR("vlineto stack");
+ goto vlineto;
+ case 0x06: // hlineto
+ if (sp < 1) return STBTT__CSERR("hlineto stack");
+ for (;;) {
+ if (i >= sp) break;
+ stbtt__csctx_rline_to(c, s[i], 0);
+ i++;
+ vlineto:
+ if (i >= sp) break;
+ stbtt__csctx_rline_to(c, 0, s[i]);
+ i++;
+ }
+ break;
+
+ case 0x1F: // hvcurveto
+ if (sp < 4) return STBTT__CSERR("hvcurveto stack");
+ goto hvcurveto;
+ case 0x1E: // vhcurveto
+ if (sp < 4) return STBTT__CSERR("vhcurveto stack");
+ for (;;) {
+ if (i + 3 >= sp) break;
+ stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);
+ i += 4;
+ hvcurveto:
+ if (i + 3 >= sp) break;
+ stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);
+ i += 4;
+ }
+ break;
+
+ case 0x08: // rrcurveto
+ if (sp < 6) return STBTT__CSERR("rcurveline stack");
+ for (; i + 5 < sp; i += 6)
+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
+ break;
+
+ case 0x18: // rcurveline
+ if (sp < 8) return STBTT__CSERR("rcurveline stack");
+ for (; i + 5 < sp - 2; i += 6)
+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
+ if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack");
+ stbtt__csctx_rline_to(c, s[i], s[i+1]);
+ break;
+
+ case 0x19: // rlinecurve
+ if (sp < 8) return STBTT__CSERR("rlinecurve stack");
+ for (; i + 1 < sp - 6; i += 2)
+ stbtt__csctx_rline_to(c, s[i], s[i+1]);
+ if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack");
+ stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);
+ break;
+
+ case 0x1A: // vvcurveto
+ case 0x1B: // hhcurveto
+ if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack");
+ f = 0.0;
+ if (sp & 1) { f = s[i]; i++; }
+ for (; i + 3 < sp; i += 4) {
+ if (b0 == 0x1B)
+ stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);
+ else
+ stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);
+ f = 0.0;
+ }
+ break;
+
+ case 0x0A: // callsubr
+ if (!has_subrs) {
+ if (info->fdselect.size)
+ subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);
+ has_subrs = 1;
+ }
+ // fallthrough
+ case 0x1D: // callgsubr
+ if (sp < 1) return STBTT__CSERR("call(g|)subr stack");
+ v = (int) s[--sp];
+ if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit");
+ subr_stack[subr_stack_height++] = b;
+ b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);
+ if (b.size == 0) return STBTT__CSERR("subr not found");
+ b.cursor = 0;
+ clear_stack = 0;
+ break;
+
+ case 0x0B: // return
+ if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr");
+ b = subr_stack[--subr_stack_height];
+ clear_stack = 0;
+ break;
+
+ case 0x0E: // endchar
+ stbtt__csctx_close_shape(c);
+ return 1;
+
+ case 0x0C: { // two-byte escape
+ float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;
+ float dx, dy;
+ int b1 = stbtt__buf_get8(&b);
+ switch (b1) {
+ // @TODO These "flex" implementations ignore the flex-depth and resolution,
+ // and always draw beziers.
+ case 0x22: // hflex
+ if (sp < 7) return STBTT__CSERR("hflex stack");
+ dx1 = s[0];
+ dx2 = s[1];
+ dy2 = s[2];
+ dx3 = s[3];
+ dx4 = s[4];
+ dx5 = s[5];
+ dx6 = s[6];
+ stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);
+ stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);
+ break;
+
+ case 0x23: // flex
+ if (sp < 13) return STBTT__CSERR("flex stack");
+ dx1 = s[0];
+ dy1 = s[1];
+ dx2 = s[2];
+ dy2 = s[3];
+ dx3 = s[4];
+ dy3 = s[5];
+ dx4 = s[6];
+ dy4 = s[7];
+ dx5 = s[8];
+ dy5 = s[9];
+ dx6 = s[10];
+ dy6 = s[11];
+ //fd is s[12]
+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
+ stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
+ break;
+
+ case 0x24: // hflex1
+ if (sp < 9) return STBTT__CSERR("hflex1 stack");
+ dx1 = s[0];
+ dy1 = s[1];
+ dx2 = s[2];
+ dy2 = s[3];
+ dx3 = s[4];
+ dx4 = s[5];
+ dx5 = s[6];
+ dy5 = s[7];
+ dx6 = s[8];
+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);
+ stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));
+ break;
+
+ case 0x25: // flex1
+ if (sp < 11) return STBTT__CSERR("flex1 stack");
+ dx1 = s[0];
+ dy1 = s[1];
+ dx2 = s[2];
+ dy2 = s[3];
+ dx3 = s[4];
+ dy3 = s[5];
+ dx4 = s[6];
+ dy4 = s[7];
+ dx5 = s[8];
+ dy5 = s[9];
+ dx6 = dy6 = s[10];
+ dx = dx1+dx2+dx3+dx4+dx5;
+ dy = dy1+dy2+dy3+dy4+dy5;
+ if (STBTT_fabs(dx) > STBTT_fabs(dy))
+ dy6 = -dy;
+ else
+ dx6 = -dx;
+ stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);
+ stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);
+ break;
+
+ default:
+ return STBTT__CSERR("unimplemented");
+ }
+ } break;
+
+ default:
+ if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254))
+ return STBTT__CSERR("reserved operator");
+
+ // push immediate
+ if (b0 == 255) {
+ f = (float)stbtt__buf_get32(&b) / 0x10000;
+ } else {
+ stbtt__buf_skip(&b, -1);
+ f = (float)(stbtt_int16)stbtt__cff_int(&b);
+ }
+ if (sp >= 48) return STBTT__CSERR("push stack overflow");
+ s[sp++] = f;
+ clear_stack = 0;
+ break;
+ }
+ if (clear_stack) sp = 0;
+ }
+ return STBTT__CSERR("no endchar");
+
+#undef STBTT__CSERR
+}
+
+static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
+{
+ // runs the charstring twice, once to count and once to output (to avoid realloc)
+ stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);
+ stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);
+ if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {
+ *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);
+ output_ctx.pvertices = *pvertices;
+ if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {
+ STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);
+ return output_ctx.num_vertices;
+ }
+ }
+ *pvertices = NULL;
+ return 0;
+}
+
+static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
+{
+ stbtt__csctx c = STBTT__CSCTX_INIT(1);
+ int r = stbtt__run_charstring(info, glyph_index, &c);
+ if (x0) {
+ *x0 = r ? c.min_x : 0;
+ *y0 = r ? c.min_y : 0;
+ *x1 = r ? c.max_x : 0;
+ *y1 = r ? c.max_y : 0;
+ }
+ return r ? c.num_vertices : 0;
+}
+
+STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
+{
+ if (!info->cff.size)
+ return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);
+ else
+ return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);
+}
+
STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
{
stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
@@ -2333,6 +3009,48 @@ static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x
return 1;
}
+static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)
+{
+ // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
+ float dx0 = x1-x0;
+ float dy0 = y1-y0;
+ float dx1 = x2-x1;
+ float dy1 = y2-y1;
+ float dx2 = x3-x2;
+ float dy2 = y3-y2;
+ float dx = x3-x0;
+ float dy = y3-y0;
+ float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));
+ float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);
+ float flatness_squared = longlen*longlen-shortlen*shortlen;
+
+ if (n > 16) // 65536 segments on one curve better be enough!
+ return;
+
+ if (flatness_squared > objspace_flatness_squared) {
+ float x01 = (x0+x1)/2;
+ float y01 = (y0+y1)/2;
+ float x12 = (x1+x2)/2;
+ float y12 = (y1+y2)/2;
+ float x23 = (x2+x3)/2;
+ float y23 = (y2+y3)/2;
+
+ float xa = (x01+x12)/2;
+ float ya = (y01+y12)/2;
+ float xb = (x12+x23)/2;
+ float yb = (y12+y23)/2;
+
+ float mx = (xa+xb)/2;
+ float my = (ya+yb)/2;
+
+ stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);
+ stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);
+ } else {
+ stbtt__add_point(points, *num_points,x3,y3);
+ *num_points = *num_points+1;
+ }
+}
+
// returns number of contours
static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
{
@@ -2389,6 +3107,14 @@ static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts,
objspace_flatness_squared, 0);
x = vertices[i].x, y = vertices[i].y;
break;
+ case STBTT_vcubic:
+ stbtt__tesselate_cubic(points, &num_points, x,y,
+ vertices[i].cx, vertices[i].cy,
+ vertices[i].cx1, vertices[i].cy1,
+ vertices[i].x, vertices[i].y,
+ objspace_flatness_squared, 0);
+ x = vertices[i].x, y = vertices[i].y;
+ break;
}
}
(*contour_lengths)[n] = num_points - start;
@@ -3214,6 +3940,11 @@ STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)
return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);
}
+STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)
+{
+ return stbtt_GetNumberOfFonts_internal((unsigned char *) data);
+}
+
STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)
{
return stbtt_InitFont_internal(info, (unsigned char *) data, offset);