Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/cimgui.zig
repos/cimgui.zig/cimgui/imgui_internal.h
// dear imgui, v1.91.1 // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. /* Index of this file: // [SECTION] Header mess // [SECTION] Forward declarations // [SECTION] Context pointer // [SECTION] STB libraries includes // [SECTION] Macros // [SECTION] Generic helpers // [SECTION] ImDrawList support // [SECTION] Data types support // [SECTION] Widgets support: flags, enums, data structures // [SECTION] Popup support // [SECTION] Inputs support // [SECTION] Clipper support // [SECTION] Navigation support // [SECTION] Typing-select support // [SECTION] Columns support // [SECTION] Box-select support // [SECTION] Multi-select support // [SECTION] Docking support // [SECTION] Viewport support // [SECTION] Settings support // [SECTION] Localization support // [SECTION] Metrics, Debug tools // [SECTION] Generic context hooks // [SECTION] ImGuiContext (main imgui context) // [SECTION] ImGuiWindowTempData, ImGuiWindow // [SECTION] Tab bar, Tab item support // [SECTION] Table support // [SECTION] ImGui internal API // [SECTION] ImFontAtlas internal API // [SECTION] Test Engine specific hooks (imgui_test_engine) */ #pragma once #ifndef IMGUI_DISABLE //----------------------------------------------------------------------------- // [SECTION] Header mess //----------------------------------------------------------------------------- #ifndef IMGUI_VERSION #include "imgui.h" #endif #include <stdio.h> // FILE*, sscanf #include <stdlib.h> // NULL, malloc, free, qsort, atoi, atof #include <math.h> // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf #include <limits.h> // INT_MIN, INT_MAX // Enable SSE intrinsics if available #if (defined __SSE__ || defined __x86_64__ || defined _M_X64 || (defined(_M_IX86_FP) && (_M_IX86_FP >= 1))) && !defined(IMGUI_DISABLE_SSE) #define IMGUI_ENABLE_SSE #include <immintrin.h> #endif // Visual Studio warnings #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) #pragma warning (disable: 26812) // The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer) #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types #endif #endif // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #if __has_warning("-Wunknown-warning-option") #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok, for ImFloor() #pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h #pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #pragma clang diagnostic ignored "-Wdouble-promotion" #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #pragma clang diagnostic ignored "-Wmissing-noreturn" // warning: function 'xxx' could be declared with attribute 'noreturn' #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated #endif // In 1.89.4, we moved the implementation of "courtesy maths operators" from imgui_internal.h in imgui.h // As they are frequently requested, we do not want to encourage to many people using imgui_internal.h #if defined(IMGUI_DEFINE_MATH_OPERATORS) && !defined(IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED) #error Please '#define IMGUI_DEFINE_MATH_OPERATORS' _BEFORE_ including imgui.h! #endif // Legacy defines #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74 #error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS #endif #ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74 #error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS #endif // Enable stb_truetype by default unless FreeType is enabled. // You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together. #ifndef IMGUI_ENABLE_FREETYPE #define IMGUI_ENABLE_STB_TRUETYPE #endif //----------------------------------------------------------------------------- // [SECTION] Forward declarations //----------------------------------------------------------------------------- struct ImBitVector; // Store 1-bit per value struct ImRect; // An axis-aligned rectangle (2 points) struct ImDrawDataBuilder; // Helper to build a ImDrawData instance struct ImDrawListSharedData; // Data shared between all ImDrawList instances struct ImGuiBoxSelectState; // Box-selection state (currently used by multi-selection, could potentially be used by others) struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it struct ImGuiContext; // Main Dear ImGui context struct ImGuiContextHook; // Hook for extensions like ImGuiTestEngine struct ImGuiDataVarInfo; // Variable information (e.g. to access style variables from an enum) struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup() struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box struct ImGuiInputTextDeactivateData;// Short term storage to backup text of a deactivating InputText() while another is stealing active id struct ImGuiLastItemData; // Status storage for last submitted items struct ImGuiLocEntry; // A localization entry. struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only struct ImGuiMultiSelectState; // Multi-selection persistent state (for focused selection). struct ImGuiMultiSelectTempData; // Multi-selection temporary state (while traversing). struct ImGuiNavItemData; // Result of a gamepad/keyboard directional navigation move query result struct ImGuiMetricsConfig; // Storage for ShowMetricsWindow() and DebugNodeXXX() functions struct ImGuiNextWindowData; // Storage for SetNextWindow** functions struct ImGuiNextItemData; // Storage for SetNextItem** functions struct ImGuiOldColumnData; // Storage data for a single column for legacy Columns() api struct ImGuiOldColumns; // Storage data for a columns set for legacy Columns() api struct ImGuiPopupData; // Storage for current popup stack struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file struct ImGuiStackSizes; // Storage of stack sizes for debugging/asserting struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it struct ImGuiTabBar; // Storage for a tab bar struct ImGuiTabItem; // Storage for a tab item (within a tab bar) struct ImGuiTable; // Storage for a table struct ImGuiTableHeaderData; // Storage for TableAngledHeadersRow() struct ImGuiTableColumn; // Storage for one column of a table struct ImGuiTableInstanceData; // Storage for one instance of a same table struct ImGuiTableTempData; // Temporary storage for one table (one per table in the stack), shared between tables. struct ImGuiTableSettings; // Storage for a table .ini settings struct ImGuiTableColumnsSettings; // Storage for a column .ini settings struct ImGuiTreeNodeStackData; // Temporary storage for TreeNode(). struct ImGuiTypingSelectState; // Storage for GetTypingSelectRequest() struct ImGuiTypingSelectRequest; // Storage for GetTypingSelectRequest() (aimed to be public) struct ImGuiWindow; // Storage for one window struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame, in practice we currently keep it for each window) struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session) // Enumerations // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. enum ImGuiLocKey : int; // -> enum ImGuiLocKey // Enum: a localization entry for translation. typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical // Flags typedef int ImGuiActivateFlags; // -> enum ImGuiActivateFlags_ // Flags: for navigation/focus function (will be for ActivateItem() later) typedef int ImGuiDebugLogFlags; // -> enum ImGuiDebugLogFlags_ // Flags: for ShowDebugLogWindow(), g.DebugLogFlags typedef int ImGuiFocusRequestFlags; // -> enum ImGuiFocusRequestFlags_ // Flags: for FocusWindow(); typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for g.LastItemData.StatusFlags typedef int ImGuiOldColumnFlags; // -> enum ImGuiOldColumnFlags_ // Flags: for BeginColumns() typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight() typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions typedef int ImGuiScrollFlags; // -> enum ImGuiScrollFlags_ // Flags: for ScrollToItem() and navigation requests typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx() typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx() typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx() typedef int ImGuiTypingSelectFlags; // -> enum ImGuiTypingSelectFlags_ // Flags: for GetTypingSelectRequest() typedef int ImGuiWindowRefreshFlags; // -> enum ImGuiWindowRefreshFlags_ // Flags: for SetNextWindowRefreshPolicy() typedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...); //----------------------------------------------------------------------------- // [SECTION] Context pointer // See implementation of this variable in imgui.cpp for comments and details. //----------------------------------------------------------------------------- #ifndef GImGui extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #endif //------------------------------------------------------------------------- // [SECTION] STB libraries includes //------------------------------------------------------------------------- namespace ImStb { #undef IMSTB_TEXTEDIT_STRING #undef IMSTB_TEXTEDIT_CHARTYPE #define IMSTB_TEXTEDIT_STRING ImGuiInputTextState #define IMSTB_TEXTEDIT_CHARTYPE ImWchar #define IMSTB_TEXTEDIT_GETWIDTH_NEWLINE (-1.0f) #define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99 #define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999 #include "imstb_textedit.h" } // namespace ImStb //----------------------------------------------------------------------------- // [SECTION] Macros //----------------------------------------------------------------------------- // Debug Printing Into TTY // (since IMGUI_VERSION_NUM >= 18729: IMGUI_DEBUG_LOG was reworked into IMGUI_DEBUG_PRINTF (and removed framecount from it). If you were using a #define IMGUI_DEBUG_LOG please rename) #ifndef IMGUI_DEBUG_PRINTF #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS #define IMGUI_DEBUG_PRINTF(_FMT,...) printf(_FMT, __VA_ARGS__) #else #define IMGUI_DEBUG_PRINTF(_FMT,...) ((void)0) #endif #endif // Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. #ifndef IMGUI_DISABLE_DEBUG_TOOLS #define IMGUI_DEBUG_LOG(...) ImGui::DebugLog(__VA_ARGS__) #else #define IMGUI_DEBUG_LOG(...) ((void)0) #endif #define IMGUI_DEBUG_LOG_ACTIVEID(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventActiveId) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_FOCUS(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventFocus) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_POPUP(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventPopup) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_NAV(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventNav) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_SELECTION(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_CLIPPER(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventClipper) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_IO(...) do { if (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO) IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) #define IMGUI_DEBUG_LOG_INPUTROUTING(...) do{if (g.DebugLogFlags & ImGuiDebugLogFlags_EventInputRouting)IMGUI_DEBUG_LOG(__VA_ARGS__); } while (0) // Static Asserts #define IM_STATIC_ASSERT(_COND) static_assert(_COND, "") // "Paranoid" Debug Asserts are meant to only be enabled during specific debugging/work, otherwise would slow down the code too much. // We currently don't have many of those so the effect is currently negligible, but onward intent to add more aggressive ones in the code. //#define IMGUI_DEBUG_PARANOID #ifdef IMGUI_DEBUG_PARANOID #define IM_ASSERT_PARANOID(_EXPR) IM_ASSERT(_EXPR) #else #define IM_ASSERT_PARANOID(_EXPR) #endif // Error handling // Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults. #ifndef IM_ASSERT_USER_ERROR #define IM_ASSERT_USER_ERROR(_EXP,_MSG) IM_ASSERT((_EXP) && _MSG) // Recoverable User Error #endif // Misc Macros #define IM_PI 3.14159265358979323846f #ifdef _WIN32 #define IM_NEWLINE "\r\n" // Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!) #else #define IM_NEWLINE "\n" #endif #ifndef IM_TABSIZE // Until we move this to runtime and/or add proper tab support, at least allow users to compile-time override #define IM_TABSIZE (4) #endif #define IM_MEMALIGN(_OFF,_ALIGN) (((_OFF) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8 #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 #define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // ImTrunc() is not inlined in MSVC debug builds #define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // #define IM_STRINGIFY_HELPER(_X) #_X #define IM_STRINGIFY(_X) IM_STRINGIFY_HELPER(_X) // Preprocessor idiom to stringify e.g. an integer. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS #define IM_FLOOR IM_TRUNC #endif // Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall #ifdef _MSC_VER #define IMGUI_CDECL __cdecl #else #define IMGUI_CDECL #endif // Warnings #if defined(_MSC_VER) && !defined(__clang__) #define IM_MSVC_WARNING_SUPPRESS(XXXX) __pragma(warning(suppress: XXXX)) #else #define IM_MSVC_WARNING_SUPPRESS(XXXX) #endif // Debug Tools // Use 'Metrics/Debugger->Tools->Item Picker' to break into the call-stack of a specific item. // This will call IM_DEBUG_BREAK() which you may redefine yourself. See https://github.com/scottt/debugbreak for more reference. #ifndef IM_DEBUG_BREAK #if defined (_MSC_VER) #define IM_DEBUG_BREAK() __debugbreak() #elif defined(__clang__) #define IM_DEBUG_BREAK() __builtin_debugtrap() #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) #define IM_DEBUG_BREAK() __asm__ volatile("int3;nop") #elif defined(__GNUC__) && defined(__thumb__) #define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xde01") #elif defined(__GNUC__) && defined(__arm__) && !defined(__thumb__) #define IM_DEBUG_BREAK() __asm__ volatile(".inst 0xe7f001f0") #else #define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger! #endif #endif // #ifndef IM_DEBUG_BREAK // Format specifiers, printing 64-bit hasn't been decently standardized... // In a real application you should be using PRId64 and PRIu64 from <inttypes.h> (non-windows) and on Windows define them yourself. #if defined(_MSC_VER) && !defined(__clang__) #define IM_PRId64 "I64d" #define IM_PRIu64 "I64u" #define IM_PRIX64 "I64X" #else #define IM_PRId64 "lld" #define IM_PRIu64 "llu" #define IM_PRIX64 "llX" #endif //----------------------------------------------------------------------------- // [SECTION] Generic helpers // Note that the ImXXX helpers functions are lower-level than ImGui functions. // ImGui functions or the ImGui context are never called/used from other ImXXX functions. //----------------------------------------------------------------------------- // - Helpers: Hashing // - Helpers: Sorting // - Helpers: Bit manipulation // - Helpers: String // - Helpers: Formatting // - Helpers: UTF-8 <> wchar conversions // - Helpers: ImVec2/ImVec4 operators // - Helpers: Maths // - Helpers: Geometry // - Helper: ImVec1 // - Helper: ImVec2ih // - Helper: ImRect // - Helper: ImBitArray // - Helper: ImBitVector // - Helper: ImSpan<>, ImSpanAllocator<> // - Helper: ImPool<> // - Helper: ImChunkStream<> // - Helper: ImGuiTextIndex // - Helper: ImGuiStorage //----------------------------------------------------------------------------- // Helpers: Hashing IMGUI_API ImGuiID ImHashData(const void* data, size_t data_size, ImGuiID seed = 0); IMGUI_API ImGuiID ImHashStr(const char* data, size_t data_size = 0, ImGuiID seed = 0); // Helpers: Sorting #ifndef ImQsort static inline void ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); } #endif // Helpers: Color Blending IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b); // Helpers: Bit manipulation static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; } static inline bool ImIsPowerOfTwo(ImU64 v) { return v != 0 && (v & (v - 1)) == 0; } static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } // Helpers: String IMGUI_API int ImStricmp(const char* str1, const char* str2); // Case insensitive compare. IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count); // Case insensitive compare to a certain count. IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count); // Copy to a certain count and always zero terminate (strncpy doesn't). IMGUI_API char* ImStrdup(const char* str); // Duplicate a string. IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str); // Copy in provided buffer, recreate buffer if needed. IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c); // Find first occurrence of 'c' in string range. IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); // Find a substring in a string range. IMGUI_API void ImStrTrimBlanks(char* str); // Remove leading and trailing blanks from a buffer. IMGUI_API const char* ImStrSkipBlank(const char* str); // Find first non-blank character. IMGUI_API int ImStrlenW(const ImWchar* str); // Computer string length (ImWchar string) IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line (ImWchar string) IM_MSVC_RUNTIME_CHECKS_OFF static inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; } static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } static inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Formatting 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); IMGUI_API void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API const char* ImParseFormatFindStart(const char* format); IMGUI_API const char* ImParseFormatFindEnd(const char* format); IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size); IMGUI_API void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size); IMGUI_API const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size); IMGUI_API int ImParseFormatPrecision(const char* format, int default_value); // Helpers: UTF-8 <> wchar conversions IMGUI_API const char* ImTextCharToUtf8(char out_buf[5], unsigned int c); // return out_buf IMGUI_API int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count IMGUI_API int ImTextStrFromUtf8(ImWchar* out_buf, int out_buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8 IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8 IMGUI_API const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr); // return previous UTF-8 code-point. IMGUI_API int ImTextCountLines(const char* in_text, const char* in_text_end); // return number of lines taken by text. trailing carriage return doesn't count as an extra line. // Helpers: File System #ifdef IMGUI_DISABLE_FILE_FUNCTIONS #define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef void* ImFileHandle; static inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; } static inline bool ImFileClose(ImFileHandle) { return false; } static inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; } static inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; } static inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; } #endif #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS typedef FILE* ImFileHandle; IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode); IMGUI_API bool ImFileClose(ImFileHandle file); IMGUI_API ImU64 ImFileGetSize(ImFileHandle file); IMGUI_API ImU64 ImFileRead(void* data, ImU64 size, ImU64 count, ImFileHandle file); IMGUI_API ImU64 ImFileWrite(const void* data, ImU64 size, ImU64 count, ImFileHandle file); #else #define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions #endif IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size = NULL, int padding_bytes = 0); // Helpers: Maths IM_MSVC_RUNTIME_CHECKS_OFF // - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) #ifndef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS #define ImFabs(X) fabsf(X) #define ImSqrt(X) sqrtf(X) #define ImFmod(X, Y) fmodf((X), (Y)) #define ImCos(X) cosf(X) #define ImSin(X) sinf(X) #define ImAcos(X) acosf(X) #define ImAtan2(Y, X) atan2f((Y), (X)) #define ImAtof(STR) atof(STR) #define ImCeil(X) ceilf(X) static inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision static inline double ImPow(double x, double y) { return pow(x, y); } static inline float ImLog(float x) { return logf(x); } // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision static inline double ImLog(double x) { return log(x); } static inline int ImAbs(int x) { return x < 0 ? -x : x; } static inline float ImAbs(float x) { return fabsf(x); } static inline double ImAbs(double x) { return fabs(x); } static inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f : 0.0f; } // Sign operator - returns -1, 0 or 1 based on sign of argument static inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } #ifdef IMGUI_ENABLE_SSE static inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } #else static inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } #endif static inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } #endif // - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double // (Exceptionally using templates here but we could also redefine them for those types) template<typename T> static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } template<typename T> static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } template<typename T> static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } template<typename T> static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); } template<typename T> static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template<typename T> static inline T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; } template<typename T> static inline T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; } // - Misc maths helpers 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 ImVec2 ImClamp(const ImVec2& v, const ImVec2&mn, const ImVec2&mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); } 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 ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } static inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } static inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; } static inline float ImTrunc(float f) { return (float)(int)(f); } static inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } static inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } static inline int ImModPositive(int a, int b) { return (a + b) % b; } static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } 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 float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x) { return ImSaturate((x - s0) / (s1 - s0)) * (d1 - d0) + d0; } static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } static inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } static inline float ImExponentialMovingAverage(float avg, float sample, int n) { avg -= avg / n; avg += sample / n; return avg; } IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Geometry IMGUI_API ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t); IMGUI_API ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments); // For curves with explicit number of segments IMGUI_API ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol);// For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol IMGUI_API ImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t); 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); inline float ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; } inline bool ImTriangleIsClockwise(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ((b.x - a.x) * (c.y - b.y)) - ((c.x - b.x) * (b.y - a.y)) > 0.0f; } // Helper: ImVec1 (1D vector) // (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) IM_MSVC_RUNTIME_CHECKS_OFF struct ImVec1 { float x; constexpr ImVec1() : x(0.0f) { } constexpr ImVec1(float _x) : x(_x) { } }; // Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage) struct ImVec2ih { short x, y; constexpr ImVec2ih() : x(0), y(0) {} constexpr ImVec2ih(short _x, short _y) : x(_x), y(_y) {} constexpr explicit ImVec2ih(const ImVec2& rhs) : x((short)rhs.x), y((short)rhs.y) {} }; // Helper: ImRect (2D axis aligned bounding-box) // NB: we can't rely on ImVec2 math operators being available here! struct IMGUI_API ImRect { ImVec2 Min; // Upper-left ImVec2 Max; // Lower-right constexpr ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {} constexpr ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} constexpr ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} constexpr 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; } float GetArea() const { return (Max.x - Min.x) * (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 ContainsWithPad(const ImVec2& p, const ImVec2& pad) const { return p.x >= Min.x - pad.x && p.y >= Min.y - pad.y && p.x < Max.x + pad.x && p.y < Max.y + pad.y; } bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; } void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; } void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; } void TranslateX(float dx) { Min.x += dx; Max.x += dx; } void TranslateY(float dy) { Min.y += dy; Max.y += dy; } void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. void Floor() { Min.x = IM_TRUNC(Min.x); Min.y = IM_TRUNC(Min.y); Max.x = IM_TRUNC(Max.x); Max.y = IM_TRUNC(Max.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } }; // Helper: ImBitArray #define IM_BITARRAY_TESTBIT(_ARRAY, _N) ((_ARRAY[(_N) >> 5] & ((ImU32)1 << ((_N) & 31))) != 0) // Macro version of ImBitArrayTestBit(): ensure args have side-effect or are costly! #define IM_BITARRAY_CLEARBIT(_ARRAY, _N) ((_ARRAY[(_N) >> 5] &= ~((ImU32)1 << ((_N) & 31)))) // Macro version of ImBitArrayClearBit(): ensure args have side-effect or are costly! inline size_t ImBitArrayGetStorageSizeInBytes(int bitcount) { return (size_t)((bitcount + 31) >> 5) << 2; } inline void ImBitArrayClearAllBits(ImU32* arr, int bitcount){ memset(arr, 0, ImBitArrayGetStorageSizeInBytes(bitcount)); } inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; } inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; } inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; } inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2) // Works on range [n..n2) { n2--; while (n <= n2) { int a_mod = (n & 31); int b_mod = (n2 > (n | 31) ? 31 : (n2 & 31)) + 1; ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1); arr[n >> 5] |= mask; n = (n + 32) & ~31; } } typedef ImU32* ImBitArrayPtr; // Name for use in structs // Helper: ImBitArray class (wrapper over ImBitArray functions) // Store 1-bit per value. template<int BITCOUNT, int OFFSET = 0> struct ImBitArray { ImU32 Storage[(BITCOUNT + 31) >> 5]; ImBitArray() { ClearAllBits(); } void ClearAllBits() { memset(Storage, 0, sizeof(Storage)); } void SetAllBits() { memset(Storage, 255, sizeof(Storage)); } bool TestBit(int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Storage, n); } void SetBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArraySetBit(Storage, n); } void ClearBit(int n) { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); ImBitArrayClearBit(Storage, n); } void SetBitRange(int n, int n2) { n += OFFSET; n2 += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT && n2 > n && n2 <= BITCOUNT); ImBitArraySetBitRange(Storage, n, n2); } // Works on range [n..n2) bool operator[](int n) const { n += OFFSET; IM_ASSERT(n >= 0 && n < BITCOUNT); return IM_BITARRAY_TESTBIT(Storage, n); } }; // Helper: ImBitVector // Store 1-bit per value. struct IMGUI_API ImBitVector { ImVector<ImU32> Storage; void Create(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); } void Clear() { Storage.clear(); } bool TestBit(int n) const { IM_ASSERT(n < (Storage.Size << 5)); return IM_BITARRAY_TESTBIT(Storage.Data, n); } void SetBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArraySetBit(Storage.Data, n); } void ClearBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArrayClearBit(Storage.Data, n); } }; IM_MSVC_RUNTIME_CHECKS_RESTORE // Helper: ImSpan<> // Pointing to a span of data we don't own. template<typename T> struct ImSpan { T* Data; T* DataEnd; // Constructors, destructor inline ImSpan() { Data = DataEnd = NULL; } inline ImSpan(T* data, int size) { Data = data; DataEnd = data + size; } inline ImSpan(T* data, T* data_end) { Data = data; DataEnd = data_end; } inline void set(T* data, int size) { Data = data; DataEnd = data + size; } inline void set(T* data, T* data_end) { Data = data; DataEnd = data_end; } inline int size() const { return (int)(ptrdiff_t)(DataEnd - Data); } inline int size_in_bytes() const { return (int)(ptrdiff_t)(DataEnd - Data) * (int)sizeof(T); } inline T& operator[](int i) { T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } inline const T& operator[](int i) const { const T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; } inline T* begin() { return Data; } inline const T* begin() const { return Data; } inline T* end() { return DataEnd; } inline const T* end() const { return DataEnd; } // Utilities inline int index_from_ptr(const T* it) const { IM_ASSERT(it >= Data && it < DataEnd); const ptrdiff_t off = it - Data; return (int)off; } }; // Helper: ImSpanAllocator<> // Facilitate storing multiple chunks into a single large block (the "arena") // - Usage: call Reserve() N times, allocate GetArenaSizeInBytes() worth, pass it to SetArenaBasePtr(), call GetSpan() N times to retrieve the aligned ranges. template<int CHUNKS> struct ImSpanAllocator { char* BasePtr; int CurrOff; int CurrIdx; int Offsets[CHUNKS]; int Sizes[CHUNKS]; ImSpanAllocator() { memset(this, 0, sizeof(*this)); } inline void Reserve(int n, size_t sz, int a=4) { IM_ASSERT(n == CurrIdx && n < CHUNKS); CurrOff = IM_MEMALIGN(CurrOff, a); Offsets[n] = CurrOff; Sizes[n] = (int)sz; CurrIdx++; CurrOff += (int)sz; } inline int GetArenaSizeInBytes() { return CurrOff; } inline void SetArenaBasePtr(void* base_ptr) { BasePtr = (char*)base_ptr; } inline void* GetSpanPtrBegin(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n]); } inline void* GetSpanPtrEnd(int n) { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n] + Sizes[n]); } template<typename T> inline void GetSpan(int n, ImSpan<T>* span) { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); } }; // Helper: ImPool<> // Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, // Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object. typedef int ImPoolIdx; template<typename T> struct ImPool { ImVector<T> Buf; // Contiguous data ImGuiStorage Map; // ID->Index ImPoolIdx FreeIdx; // Next free idx to use ImPoolIdx AliveCount; // Number of active/alive items (for display purpose) ImPool() { FreeIdx = AliveCount = 0; } ~ImPool() { Clear(); } T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Buf[idx] : NULL; } T* GetByIndex(ImPoolIdx n) { return &Buf[n]; } ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Buf.Data && p < Buf.Data + Buf.Size); return (ImPoolIdx)(p - Buf.Data); } T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Buf[*p_idx]; *p_idx = FreeIdx; return Add(); } bool Contains(const T* p) const { return (p >= Buf.Data && p < Buf.Data + Buf.Size); } void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Buf[idx].~T(); } Map.Clear(); Buf.clear(); FreeIdx = AliveCount = 0; } T* Add() { int idx = FreeIdx; if (idx == Buf.Size) { Buf.resize(Buf.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Buf[idx]; } IM_PLACEMENT_NEW(&Buf[idx]) T(); AliveCount++; return &Buf[idx]; } void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); } void Remove(ImGuiID key, ImPoolIdx idx) { Buf[idx].~T(); *(int*)&Buf[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); AliveCount--; } void Reserve(int capacity) { Buf.reserve(capacity); Map.Data.reserve(capacity); } // To iterate a ImPool: for (int n = 0; n < pool.GetMapSize(); n++) if (T* t = pool.TryGetMapData(n)) { ... } // Can be avoided if you know .Remove() has never been called on the pool, or AliveCount == GetMapSize() int GetAliveCount() const { return AliveCount; } // Number of active/alive items in the pool (for display purpose) int GetBufSize() const { return Buf.Size; } int GetMapSize() const { return Map.Data.Size; } // It is the map we need iterate to find valid items, since we don't have "alive" storage anywhere T* TryGetMapData(ImPoolIdx n) { int idx = Map.Data[n].val_i; if (idx == -1) return NULL; return GetByIndex(idx); } }; // Helper: ImChunkStream<> // Build and iterate a contiguous stream of variable-sized structures. // This is used by Settings to store persistent data while reducing allocation count. // We store the chunk size first, and align the final size on 4 bytes boundaries. // The tedious/zealous amount of casting is to avoid -Wcast-align warnings. template<typename T> struct ImChunkStream { ImVector<char> Buf; void clear() { Buf.clear(); } bool empty() const { return Buf.Size == 0; } int size() const { return Buf.Size; } T* alloc_chunk(size_t sz) { size_t HDR_SZ = 4; sz = IM_MEMALIGN(HDR_SZ + sz, 4u); int off = Buf.Size; Buf.resize(off + (int)sz); ((int*)(void*)(Buf.Data + off))[0] = (int)sz; return (T*)(void*)(Buf.Data + off + (int)HDR_SZ); } T* begin() { size_t HDR_SZ = 4; if (!Buf.Data) return NULL; return (T*)(void*)(Buf.Data + HDR_SZ); } T* next_chunk(T* p) { size_t HDR_SZ = 4; IM_ASSERT(p >= begin() && p < end()); p = (T*)(void*)((char*)(void*)p + chunk_size(p)); if (p == (T*)(void*)((char*)end() + HDR_SZ)) return (T*)0; IM_ASSERT(p < end()); return p; } int chunk_size(const T* p) { return ((const int*)p)[-1]; } T* end() { return (T*)(void*)(Buf.Data + Buf.Size); } int offset_from_ptr(const T* p) { IM_ASSERT(p >= begin() && p < end()); const ptrdiff_t off = (const char*)p - Buf.Data; return (int)off; } T* ptr_from_offset(int off) { IM_ASSERT(off >= 4 && off < Buf.Size); return (T*)(void*)(Buf.Data + off); } void swap(ImChunkStream<T>& rhs) { rhs.Buf.swap(Buf); } }; // Helper: ImGuiTextIndex // Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. struct ImGuiTextIndex { ImVector<int> LineOffsets; int EndOffset = 0; // Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?) void clear() { LineOffsets.clear(); EndOffset = 0; } int size() { return LineOffsets.Size; } const char* get_line_begin(const char* base, int n) { return base + LineOffsets[n]; } const char* get_line_end(const char* base, int n) { return base + (n + 1 < LineOffsets.Size ? (LineOffsets[n + 1] - 1) : EndOffset); } void append(const char* base, int old_size, int new_size); }; // Helper: ImGuiStorage IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key); //----------------------------------------------------------------------------- // [SECTION] ImDrawList support //----------------------------------------------------------------------------- // ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value. // Estimation of number of circle segment based on error is derived using method described in https://stackoverflow.com/a/2244088/15194693 // Number of segments (N) is calculated using equation: // N = ceil ( pi / acos(1 - error / r) ) where r > 0, error <= r // Our equation is significantly simpler that one in the post thanks for choosing segment that is // perpendicular to X axis. Follow steps in the article from this starting condition and you will // will get this result. // // Rendering circles with an odd number of segments, while mathematically correct will produce // asymmetrical results on the raster grid. Therefore we're rounding N to next even number (7->8, 8->8, 9->10 etc.) #define IM_ROUNDUP_TO_EVEN(_V) ((((_V) + 1) / 2) * 2) #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 4 #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512 #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp(IM_ROUNDUP_TO_EVEN((int)ImCeil(IM_PI / ImAcos(1 - ImMin((_MAXERROR), (_RAD)) / (_RAD)))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) // Raw equation from IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC rewritten for 'r' and 'error'. #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N,_MAXERROR) ((_MAXERROR) / (1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI)))) #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N,_RAD) ((1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))) / (_RAD)) // ImDrawList: Lookup table size for adaptive arc drawing, cover full circle. #ifndef IM_DRAWLIST_ARCFAST_TABLE_SIZE #define IM_DRAWLIST_ARCFAST_TABLE_SIZE 48 // Number of samples in lookup table. #endif #define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. // Data shared between all ImDrawList instances // You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure. struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas ImFont* Font; // Current/default font (optional, for simplified AddText overload) float FontSize; // Current/default font size (optional, for simplified AddText overload) float FontScale; // Current/default font scale (== FontSize / Font->FontSize) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) // [Internal] Temp write buffer ImVector<ImVec2> TempBuffer; // [Internal] Lookup tables ImVec2 ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle. float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas ImDrawListSharedData(); void SetCircleTessellationMaxError(float max_error); }; struct ImDrawDataBuilder { ImVector<ImDrawList*>* Layers[2]; // Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. ImVector<ImDrawList*> LayerData1; ImDrawDataBuilder() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- // [SECTION] Data types support //----------------------------------------------------------------------------- struct ImGuiDataVarInfo { ImGuiDataType Type; ImU32 Count; // 1+ ImU32 Offset; // Offset in parent structure void* GetVarPtr(void* parent) const { return (void*)((unsigned char*)parent + Offset); } }; struct ImGuiDataTypeStorage { ImU8 Data[8]; // Opaque storage to fit any data up to ImGuiDataType_COUNT }; // Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). struct ImGuiDataTypeInfo { size_t Size; // Size in bytes const char* Name; // Short descriptive name for the type, for debugging const char* PrintFmt; // Default printf format for the type const char* ScanFmt; // Default scanf format for the type }; // Extend ImGuiDataType_ enum ImGuiDataTypePrivate_ { ImGuiDataType_String = ImGuiDataType_COUNT + 1, ImGuiDataType_Pointer, ImGuiDataType_ID, }; //----------------------------------------------------------------------------- // [SECTION] Widgets support: flags, enums, data structures //----------------------------------------------------------------------------- // Extend ImGuiItemFlags // - input: PushItemFlag() manipulates g.CurrentItemFlags, ItemAdd() calls may add extra flags. // - output: stored in g.LastItemData.InFlags enum ImGuiItemFlagsPrivate_ { // Controlled by user ImGuiItemFlags_Disabled = 1 << 10, // false // Disable interactions (DOES NOT affect visuals, see BeginDisabled()/EndDisabled() for full disable feature, and github #211). ImGuiItemFlags_ReadOnly = 1 << 11, // false // [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags_MixedValue = 1 << 12, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets) ImGuiItemFlags_NoWindowHoverableCheck = 1 << 13, // false // Disable hoverable check in ItemHoverable() ImGuiItemFlags_AllowOverlap = 1 << 14, // false // Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. // Controlled by widget code ImGuiItemFlags_Inputable = 1 << 20, // false // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature. ImGuiItemFlags_HasSelectionUserData = 1 << 21, // false // Set by SetNextItemSelectionUserData() ImGuiItemFlags_IsMultiSelect = 1 << 22, // false // Set by SetNextItemSelectionUserData() ImGuiItemFlags_Default_ = ImGuiItemFlags_AutoClosePopups, // Please don't change, use PushItemFlag() instead. // Obsolete //ImGuiItemFlags_SelectableDontClosePopup = !ImGuiItemFlags_AutoClosePopups, // Can't have a redirect as we inverted the behavior }; // Status flags for an already submitted item // - output: stored in g.LastItemData.StatusFlags enum ImGuiItemStatusFlags_ { ImGuiItemStatusFlags_None = 0, ImGuiItemStatusFlags_HoveredRect = 1 << 0, // Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test) ImGuiItemStatusFlags_HasDisplayRect = 1 << 1, // g.LastItemData.DisplayRect is valid ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets) ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected", only state changes, in order to easily handle clipping with less issues. ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state. ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. ImGuiItemStatusFlags_Deactivated = 1 << 6, // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. ImGuiItemStatusFlags_HoveredWindow = 1 << 7, // Override the HoveredWindow test to allow cross-window hover testing. ImGuiItemStatusFlags_Visible = 1 << 8, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()). ImGuiItemStatusFlags_HasClipRect = 1 << 9, // g.LastItemData.ClipRect is valid. ImGuiItemStatusFlags_HasShortcut = 1 << 10, // g.LastItemData.Shortcut valid. Set by SetNextItemShortcut() -> ItemAdd(). // Additional status + semantic for ImGuiTestEngine #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiItemStatusFlags_Openable = 1 << 20, // Item is an openable (e.g. TreeNode) ImGuiItemStatusFlags_Opened = 1 << 21, // Opened status ImGuiItemStatusFlags_Checkable = 1 << 22, // Item is a checkable (e.g. CheckBox, MenuItem) ImGuiItemStatusFlags_Checked = 1 << 23, // Checked status ImGuiItemStatusFlags_Inputable = 1 << 24, // Item is a text-inputable (e.g. InputText, SliderXXX, DragXXX) #endif }; // Extend ImGuiHoveredFlags_ enum ImGuiHoveredFlagsPrivate_ { ImGuiHoveredFlags_DelayMask_ = ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay, ImGuiHoveredFlags_AllowedMaskForIsWindowHovered = ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary, ImGuiHoveredFlags_AllowedMaskForIsItemHovered = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayMask_, }; // Extend ImGuiInputTextFlags_ enum ImGuiInputTextFlagsPrivate_ { // [Internal] ImGuiInputTextFlags_Multiline = 1 << 26, // For internal use by InputTextMultiline() ImGuiInputTextFlags_NoMarkEdited = 1 << 27, // For internal use by functions using InputText() before reformatting data ImGuiInputTextFlags_MergedItem = 1 << 28, // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. ImGuiInputTextFlags_LocalizeDecimalPoint= 1 << 29, // For internal use by InputScalar() and TempInputScalar() }; // Extend ImGuiButtonFlags_ enum ImGuiButtonFlagsPrivate_ { ImGuiButtonFlags_PressedOnClick = 1 << 4, // return true on click (mouse down event) ImGuiButtonFlags_PressedOnClickRelease = 1 << 5, // [Default] return true on click + release on same item <-- this is what the majority of Button are using ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item ImGuiButtonFlags_PressedOnRelease = 1 << 7, // return true on release (default requires click+release) ImGuiButtonFlags_PressedOnDoubleClick = 1 << 8, // return true on double-click (default requires click+release) ImGuiButtonFlags_PressedOnDragDropHold = 1 << 9, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers) ImGuiButtonFlags_Repeat = 1 << 10, // hold to repeat ImGuiButtonFlags_FlattenChildren = 1 << 11, // allow interactions even if a child window is overlapping ImGuiButtonFlags_AllowOverlap = 1 << 12, // require previous frame HoveredId to either match id or be null before being usable. ImGuiButtonFlags_DontClosePopups = 1 << 13, // disable automatically closing parent popup on press // [UNUSED] //ImGuiButtonFlags_Disabled = 1 << 14, // disable interactions -> use BeginDisabled() or ImGuiItemFlags_Disabled ImGuiButtonFlags_AlignTextBaseLine = 1 << 15, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine ImGuiButtonFlags_NoKeyModifiers = 1 << 16, // disable mouse interaction if a key modifier is held ImGuiButtonFlags_NoHoldingActiveId = 1 << 17, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only) ImGuiButtonFlags_NoNavFocus = 1 << 18, // don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags_NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.InFlags) ImGuiButtonFlags_NoHoveredOnFocus = 1 << 19, // don't report as hovered when nav focus is on this item ImGuiButtonFlags_NoSetKeyOwner = 1 << 20, // don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) ImGuiButtonFlags_NoTestKeyOwner = 1 << 21, // don't test key/input owner when polling the key (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold, ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease, }; // Extend ImGuiComboFlags_ enum ImGuiComboFlagsPrivate_ { ImGuiComboFlags_CustomPreview = 1 << 20, // enable BeginComboPreview() }; // Extend ImGuiSliderFlags_ enum ImGuiSliderFlagsPrivate_ { ImGuiSliderFlags_Vertical = 1 << 20, // Should this slider be orientated vertically? ImGuiSliderFlags_ReadOnly = 1 << 21, // Consider using g.NextItemData.ItemFlags |= ImGuiItemFlags_ReadOnly instead. }; // Extend ImGuiSelectableFlags_ enum ImGuiSelectableFlagsPrivate_ { // NB: need to be in sync with last value of ImGuiSelectableFlags_ ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20, ImGuiSelectableFlags_SelectOnNav = 1 << 21, // (WIP) Auto-select when moved into. This is not exposed in public API as to handle multi-select and modifiers we will need user to explicitly control focus scope. May be replaced with a BeginSelection() API. ImGuiSelectableFlags_SelectOnClick = 1 << 22, // Override button behavior to react on Click (default is Click+Release) ImGuiSelectableFlags_SelectOnRelease = 1 << 23, // Override button behavior to react on Release (default is Click+Release) ImGuiSelectableFlags_SpanAvailWidth = 1 << 24, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus) ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25, // Set Nav/Focus ID on mouse hover (used by MenuItem) ImGuiSelectableFlags_NoPadWithHalfSpacing = 1 << 26, // Disable padding each side with ItemSpacing * 0.5f ImGuiSelectableFlags_NoSetKeyOwner = 1 << 27, // Don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey_MouseLeft!) }; // Extend ImGuiTreeNodeFlags_ enum ImGuiTreeNodeFlagsPrivate_ { ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 28,// FIXME-WIP: Hard-coded for CollapsingHeader() ImGuiTreeNodeFlags_UpsideDownArrow = 1 << 29,// FIXME-WIP: Turn Down arrow into an Up arrow, but reversed trees (#6517) ImGuiTreeNodeFlags_OpenOnMask_ = ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_OpenOnArrow, }; enum ImGuiSeparatorFlags_ { ImGuiSeparatorFlags_None = 0, ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar ImGuiSeparatorFlags_Vertical = 1 << 1, ImGuiSeparatorFlags_SpanAllColumns = 1 << 2, // Make separator cover all columns of a legacy Columns() set. }; // Flags for FocusWindow(). This is not called ImGuiFocusFlags to avoid confusion with public-facing ImGuiFocusedFlags. // FIXME: Once we finishing replacing more uses of GetTopMostPopupModal()+IsWindowWithinBeginStackOf() // and FindBlockingModal() with this, we may want to change the flag to be opt-out instead of opt-in. enum ImGuiFocusRequestFlags_ { ImGuiFocusRequestFlags_None = 0, ImGuiFocusRequestFlags_RestoreFocusedChild = 1 << 0, // Find last focused child (if any) and focus it instead. ImGuiFocusRequestFlags_UnlessBelowModal = 1 << 1, // Do not set focus if the window is below a modal. }; enum ImGuiTextFlags_ { ImGuiTextFlags_None = 0, ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0, }; enum ImGuiTooltipFlags_ { ImGuiTooltipFlags_None = 0, ImGuiTooltipFlags_OverridePrevious = 1 << 1, // Clear/ignore previously submitted tooltip (defaults to append) }; // FIXME: this is in development, not exposed/functional as a generic feature yet. // Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 enum ImGuiLayoutType_ { ImGuiLayoutType_Horizontal = 0, ImGuiLayoutType_Vertical = 1 }; enum ImGuiLogType { ImGuiLogType_None = 0, ImGuiLogType_TTY, ImGuiLogType_File, ImGuiLogType_Buffer, ImGuiLogType_Clipboard, }; // X/Y enums are fixed to 0/1 so they may be used to index ImVec2 enum ImGuiAxis { ImGuiAxis_None = -1, ImGuiAxis_X = 0, ImGuiAxis_Y = 1 }; enum ImGuiPlotType { ImGuiPlotType_Lines, ImGuiPlotType_Histogram, }; // Stacked color modifier, backup of modified data so we can restore it struct ImGuiColorMod { ImGuiCol Col; ImVec4 BackupValue; }; // Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. struct ImGuiStyleMod { ImGuiStyleVar VarIdx; union { int BackupInt[2]; float BackupFloat[2]; }; ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } }; // Storage data for BeginComboPreview()/EndComboPreview() struct IMGUI_API ImGuiComboPreviewData { ImRect PreviewRect; ImVec2 BackupCursorPos; ImVec2 BackupCursorMaxPos; ImVec2 BackupCursorPosPrevLine; float BackupPrevLineTextBaseOffset; ImGuiLayoutType BackupLayout; ImGuiComboPreviewData() { memset(this, 0, sizeof(*this)); } }; // Stacked storage data for BeginGroup()/EndGroup() struct IMGUI_API ImGuiGroupData { ImGuiID WindowID; ImVec2 BackupCursorPos; ImVec2 BackupCursorMaxPos; ImVec2 BackupCursorPosPrevLine; ImVec1 BackupIndent; ImVec1 BackupGroupOffset; ImVec2 BackupCurrLineSize; float BackupCurrLineTextBaseOffset; ImGuiID BackupActiveIdIsAlive; bool BackupActiveIdPreviousFrameIsAlive; bool BackupHoveredIdIsAlive; bool BackupIsSameLine; bool EmitItem; }; // Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. struct IMGUI_API ImGuiMenuColumns { ImU32 TotalWidth; ImU32 NextTotalWidth; ImU16 Spacing; ImU16 OffsetIcon; // Always zero for now ImU16 OffsetLabel; // Offsets are locked in Update() ImU16 OffsetShortcut; ImU16 OffsetMark; ImU16 Widths[4]; // Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); } void Update(float spacing, bool window_reappearing); float DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark); void CalcNextTotalWidth(bool update_offsets); }; // Internal temporary state for deactivating InputText() instances. struct IMGUI_API ImGuiInputTextDeactivatedState { ImGuiID ID; // widget id owning the text state (which just got deactivated) ImVector<char> TextA; // text buffer ImGuiInputTextDeactivatedState() { memset(this, 0, sizeof(*this)); } void ClearFreeMemory() { ID = 0; TextA.clear(); } }; // Internal state of the currently focused/edited text input box // For a given item ID, access with ImGui::GetInputTextState() struct IMGUI_API ImGuiInputTextState { ImGuiContext* Ctx; // parent UI context (needs to be set explicitly by parent). ImGuiID ID; // widget id owning the text state int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not. ImVector<ImWchar> TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. ImVector<char> TextA; // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity. ImVector<char> InitialTextA; // value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument) int BufCapacityA; // end-user buffer capacity ImVec2 Scroll; // horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) ImStb::STB_TexteditState Stb; // state for stb_textedit.h float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!) bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection bool Edited; // edited this frame ImGuiInputTextFlags Flags; // copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags_Password is set. bool ReloadUserBuf; // force a reload of user buf so it may be modified externally. may be automatic in future version. int ReloadSelectionStart; // POSITIONS ARE IN IMWCHAR units *NOT* UTF-8 this is why this is not exposed yet. int ReloadSelectionEnd; ImGuiInputTextState() { memset(this, 0, sizeof(*this)); } void ClearText() { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); } void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); } int GetUndoAvailCount() const { return Stb.undostate.undo_point; } int GetRedoAvailCount() const { return IMSTB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; } void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation // Cursor & Selection void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); } bool HasSelection() const { return Stb.select_start != Stb.select_end; } void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; } int GetCursorPos() const { return Stb.cursor; } int GetSelectionStart() const { return Stb.select_start; } int GetSelectionEnd() const { return Stb.select_end; } void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; } // Reload user buf (WIP #2890) // If you modify underlying user-passed const char* while active you need to call this (InputText V2 may lift this) // strcpy(my_buf, "hello"); // if (ImGuiInputTextState* state = ImGui::GetInputTextState(id)) // id may be ImGui::GetItemID() is last item // state->ReloadUserBufAndSelectAll(); void ReloadUserBufAndSelectAll() { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; } void ReloadUserBufAndKeepSelection() { ReloadUserBuf = true; ReloadSelectionStart = Stb.select_start; ReloadSelectionEnd = Stb.select_end; } void ReloadUserBufAndMoveToEnd() { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; } }; enum ImGuiWindowRefreshFlags_ { ImGuiWindowRefreshFlags_None = 0, ImGuiWindowRefreshFlags_TryToAvoidRefresh = 1 << 0, // [EXPERIMENTAL] Try to keep existing contents, USER MUST NOT HONOR BEGIN() RETURNING FALSE AND NOT APPEND. ImGuiWindowRefreshFlags_RefreshOnHover = 1 << 1, // [EXPERIMENTAL] Always refresh on hover ImGuiWindowRefreshFlags_RefreshOnFocus = 1 << 2, // [EXPERIMENTAL] Always refresh on focus // Refresh policy/frequency, Load Balancing etc. }; enum ImGuiNextWindowDataFlags_ { ImGuiNextWindowDataFlags_None = 0, ImGuiNextWindowDataFlags_HasPos = 1 << 0, ImGuiNextWindowDataFlags_HasSize = 1 << 1, ImGuiNextWindowDataFlags_HasContentSize = 1 << 2, ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3, ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4, ImGuiNextWindowDataFlags_HasFocus = 1 << 5, ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6, ImGuiNextWindowDataFlags_HasScroll = 1 << 7, ImGuiNextWindowDataFlags_HasChildFlags = 1 << 8, ImGuiNextWindowDataFlags_HasRefreshPolicy = 1 << 9, }; // Storage for SetNexWindow** functions struct ImGuiNextWindowData { ImGuiNextWindowDataFlags Flags; ImGuiCond PosCond; ImGuiCond SizeCond; ImGuiCond CollapsedCond; ImVec2 PosVal; ImVec2 PosPivotVal; ImVec2 SizeVal; ImVec2 ContentSizeVal; ImVec2 ScrollVal; ImGuiChildFlags ChildFlags; bool CollapsedVal; ImRect SizeConstraintRect; ImGuiSizeCallback SizeCallback; void* SizeCallbackUserData; float BgAlphaVal; // Override background alpha ImVec2 MenuBarOffsetMinVal; // (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) ImGuiWindowRefreshFlags RefreshFlagsVal; ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); } inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; } }; enum ImGuiNextItemDataFlags_ { ImGuiNextItemDataFlags_None = 0, ImGuiNextItemDataFlags_HasWidth = 1 << 0, ImGuiNextItemDataFlags_HasOpen = 1 << 1, ImGuiNextItemDataFlags_HasShortcut = 1 << 2, ImGuiNextItemDataFlags_HasRefVal = 1 << 3, ImGuiNextItemDataFlags_HasStorageID = 1 << 4, }; struct ImGuiNextItemData { ImGuiNextItemDataFlags Flags; ImGuiItemFlags ItemFlags; // Currently only tested/used for ImGuiItemFlags_AllowOverlap and ImGuiItemFlags_HasSelectionUserData. // Non-flags members are NOT cleared by ItemAdd() meaning they are still valid during NavProcessItem() ImGuiID FocusScopeId; // Set by SetNextItemSelectionUserData() ImGuiSelectionUserData SelectionUserData; // Set by SetNextItemSelectionUserData() (note that NULL/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) float Width; // Set by SetNextItemWidth() ImGuiKeyChord Shortcut; // Set by SetNextItemShortcut() ImGuiInputFlags ShortcutFlags; // Set by SetNextItemShortcut() bool OpenVal; // Set by SetNextItemOpen() ImU8 OpenCond; // Set by SetNextItemOpen() ImGuiDataTypeStorage RefVal; // Not exposed yet, for ImGuiInputTextFlags_ParseEmptyAsRefVal ImGuiID StorageId; // Set by SetNextItemStorageID() ImGuiNextItemData() { memset(this, 0, sizeof(*this)); SelectionUserData = -1; } inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; ItemFlags = ImGuiItemFlags_None; } // Also cleared manually by ItemAdd()! }; // Status storage for the last submitted item struct ImGuiLastItemData { ImGuiID ID; ImGuiItemFlags InFlags; // See ImGuiItemFlags_ ImGuiItemStatusFlags StatusFlags; // See ImGuiItemStatusFlags_ ImRect Rect; // Full rectangle ImRect NavRect; // Navigation scoring rectangle (not displayed) // Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags ar set. ImRect DisplayRect; // Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) is set. ImRect ClipRect; // Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasClipRect) is set.. ImGuiKeyChord Shortcut; // Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags_HasShortcut) is set.. ImGuiLastItemData() { memset(this, 0, sizeof(*this)); } }; // Store data emitted by TreeNode() for usage by TreePop() // - To implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere: store the minimum amount of data // which we can't infer in TreePop(), to perform the equivalent of NavApplyItemToResult(). // Only stored when the node is a potential candidate for landing on a Left arrow jump. struct ImGuiTreeNodeStackData { ImGuiID ID; ImGuiTreeNodeFlags TreeFlags; ImGuiItemFlags InFlags; // Used for nav landing ImRect NavRect; // Used for nav landing }; struct IMGUI_API ImGuiStackSizes { short SizeOfIDStack; short SizeOfColorStack; short SizeOfStyleVarStack; short SizeOfFontStack; short SizeOfFocusScopeStack; short SizeOfGroupStack; short SizeOfItemFlagsStack; short SizeOfBeginPopupStack; short SizeOfDisabledStack; ImGuiStackSizes() { memset(this, 0, sizeof(*this)); } void SetToContextState(ImGuiContext* ctx); void CompareWithContextState(ImGuiContext* ctx); }; // Data saved for each window pushed into the stack struct ImGuiWindowStackData { ImGuiWindow* Window; ImGuiLastItemData ParentLastItemDataBackup; ImGuiStackSizes StackSizesOnBegin; // Store size of various stacks for asserting bool DisabledOverrideReenable; // Non-child window override disabled flag }; struct ImGuiShrinkWidthItem { int Index; float Width; float InitialWidth; }; struct ImGuiPtrOrIndex { void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool. int Index; // Usually index in a main pool. ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; } ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; } }; //----------------------------------------------------------------------------- // [SECTION] Popup support //----------------------------------------------------------------------------- enum ImGuiPopupPositionPolicy { ImGuiPopupPositionPolicy_Default, ImGuiPopupPositionPolicy_ComboBox, ImGuiPopupPositionPolicy_Tooltip, }; // Storage for popup stacks (g.OpenPopupStack and g.BeginPopupStack) struct ImGuiPopupData { ImGuiID PopupId; // Set on OpenPopup() ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() ImGuiWindow* RestoreNavWindow;// Set on OpenPopup(), a NavWindow that will be restored on popup close int ParentNavLayer; // Resolved on BeginPopup(). Actually a ImGuiNavLayer type (declared down below), initialized to -1 which is not part of an enum, but serves well-enough as "not any of layers" value int OpenFrameCount; // Set on OpenPopup() ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate 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 ImGuiPopupData() { memset(this, 0, sizeof(*this)); ParentNavLayer = OpenFrameCount = -1; } }; //----------------------------------------------------------------------------- // [SECTION] Inputs support //----------------------------------------------------------------------------- // Bit array for named keys typedef ImBitArray<ImGuiKey_NamedKey_COUNT, -ImGuiKey_NamedKey_BEGIN> ImBitArrayForNamedKeys; // [Internal] Key ranges #define ImGuiKey_LegacyNativeKey_BEGIN 0 #define ImGuiKey_LegacyNativeKey_END 512 #define ImGuiKey_Keyboard_BEGIN (ImGuiKey_NamedKey_BEGIN) #define ImGuiKey_Keyboard_END (ImGuiKey_GamepadStart) #define ImGuiKey_Gamepad_BEGIN (ImGuiKey_GamepadStart) #define ImGuiKey_Gamepad_END (ImGuiKey_GamepadRStickDown + 1) #define ImGuiKey_Mouse_BEGIN (ImGuiKey_MouseLeft) #define ImGuiKey_Mouse_END (ImGuiKey_MouseWheelY + 1) #define ImGuiKey_Aliases_BEGIN (ImGuiKey_Mouse_BEGIN) #define ImGuiKey_Aliases_END (ImGuiKey_Mouse_END) // [Internal] Named shortcuts for Navigation #define ImGuiKey_NavKeyboardTweakSlow ImGuiMod_Ctrl #define ImGuiKey_NavKeyboardTweakFast ImGuiMod_Shift #define ImGuiKey_NavGamepadTweakSlow ImGuiKey_GamepadL1 #define ImGuiKey_NavGamepadTweakFast ImGuiKey_GamepadR1 #define ImGuiKey_NavGamepadActivate (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceRight : ImGuiKey_GamepadFaceDown) #define ImGuiKey_NavGamepadCancel (g.IO.ConfigNavSwapGamepadButtons ? ImGuiKey_GamepadFaceDown : ImGuiKey_GamepadFaceRight) #define ImGuiKey_NavGamepadMenu ImGuiKey_GamepadFaceLeft #define ImGuiKey_NavGamepadInput ImGuiKey_GamepadFaceUp enum ImGuiInputEventType { ImGuiInputEventType_None = 0, ImGuiInputEventType_MousePos, ImGuiInputEventType_MouseWheel, ImGuiInputEventType_MouseButton, ImGuiInputEventType_Key, ImGuiInputEventType_Text, ImGuiInputEventType_Focus, ImGuiInputEventType_COUNT }; enum ImGuiInputSource { ImGuiInputSource_None = 0, ImGuiInputSource_Mouse, // Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them. ImGuiInputSource_Keyboard, ImGuiInputSource_Gamepad, ImGuiInputSource_COUNT }; // FIXME: Structures in the union below need to be declared as anonymous unions appears to be an extension? // Using ImVec2() would fail on Clang 'union member 'MousePos' has a non-trivial default constructor' struct ImGuiInputEventMousePos { float PosX, PosY; ImGuiMouseSource MouseSource; }; struct ImGuiInputEventMouseWheel { float WheelX, WheelY; ImGuiMouseSource MouseSource; }; struct ImGuiInputEventMouseButton { int Button; bool Down; ImGuiMouseSource MouseSource; }; struct ImGuiInputEventKey { ImGuiKey Key; bool Down; float AnalogValue; }; struct ImGuiInputEventText { unsigned int Char; }; struct ImGuiInputEventAppFocused { bool Focused; }; struct ImGuiInputEvent { ImGuiInputEventType Type; ImGuiInputSource Source; ImU32 EventId; // Unique, sequential increasing integer to identify an event (if you need to correlate them to other data). union { ImGuiInputEventMousePos MousePos; // if Type == ImGuiInputEventType_MousePos ImGuiInputEventMouseWheel MouseWheel; // if Type == ImGuiInputEventType_MouseWheel ImGuiInputEventMouseButton MouseButton; // if Type == ImGuiInputEventType_MouseButton ImGuiInputEventKey Key; // if Type == ImGuiInputEventType_Key ImGuiInputEventText Text; // if Type == ImGuiInputEventType_Text ImGuiInputEventAppFocused AppFocused; // if Type == ImGuiInputEventType_Focus }; bool AddedByTestEngine; ImGuiInputEvent() { memset(this, 0, sizeof(*this)); } }; // Input function taking an 'ImGuiID owner_id' argument defaults to (ImGuiKeyOwner_Any == 0) aka don't test ownership, which matches legacy behavior. #define ImGuiKeyOwner_Any ((ImGuiID)0) // Accept key that have an owner, UNLESS a call to SetKeyOwner() explicitly used ImGuiInputFlags_LockThisFrame or ImGuiInputFlags_LockUntilRelease. #define ImGuiKeyOwner_NoOwner ((ImGuiID)-1) // Require key to have no owner. //#define ImGuiKeyOwner_None ImGuiKeyOwner_NoOwner // We previously called this 'ImGuiKeyOwner_None' but it was inconsistent with our pattern that _None values == 0 and quite dangerous. Also using _NoOwner makes the IsKeyPressed() calls more explicit. typedef ImS16 ImGuiKeyRoutingIndex; // Routing table entry (sizeof() == 16 bytes) struct ImGuiKeyRoutingData { ImGuiKeyRoutingIndex NextEntryIndex; ImU16 Mods; // Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. ImU8 RoutingCurrScore; // [DEBUG] For debug display ImU8 RoutingNextScore; // Lower is better (0: perfect score) ImGuiID RoutingCurr; ImGuiID RoutingNext; ImGuiKeyRoutingData() { NextEntryIndex = -1; Mods = 0; RoutingCurrScore = RoutingNextScore = 255; RoutingCurr = RoutingNext = ImGuiKeyOwner_NoOwner; } }; // Routing table: maintain a desired owner for each possible key-chord (key + mods), and setup owner in NewFrame() when mods are matching. // Stored in main context (1 instance) struct ImGuiKeyRoutingTable { ImGuiKeyRoutingIndex Index[ImGuiKey_NamedKey_COUNT]; // Index of first entry in Entries[] ImVector<ImGuiKeyRoutingData> Entries; ImVector<ImGuiKeyRoutingData> EntriesNext; // Double-buffer to avoid reallocation (could use a shared buffer) ImGuiKeyRoutingTable() { Clear(); } void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Index); n++) Index[n] = -1; Entries.clear(); EntriesNext.clear(); } }; // This extends ImGuiKeyData but only for named keys (legacy keys don't support the new features) // Stored in main context (1 per named key). In the future it might be merged into ImGuiKeyData. struct ImGuiKeyOwnerData { ImGuiID OwnerCurr; ImGuiID OwnerNext; bool LockThisFrame; // Reading this key requires explicit owner id (until end of frame). Set by ImGuiInputFlags_LockThisFrame. bool LockUntilRelease; // Reading this key requires explicit owner id (until key is released). Set by ImGuiInputFlags_LockUntilRelease. When this is true LockThisFrame is always true as well. ImGuiKeyOwnerData() { OwnerCurr = OwnerNext = ImGuiKeyOwner_NoOwner; LockThisFrame = LockUntilRelease = false; } }; // Extend ImGuiInputFlags_ // Flags for extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() // Don't mistake with ImGuiInputTextFlags! (which is for ImGui::InputText() function) enum ImGuiInputFlagsPrivate_ { // Flags for IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(), Shortcut() // - Repeat mode: Repeat rate selection ImGuiInputFlags_RepeatRateDefault = 1 << 1, // Repeat rate: Regular (default) ImGuiInputFlags_RepeatRateNavMove = 1 << 2, // Repeat rate: Fast ImGuiInputFlags_RepeatRateNavTweak = 1 << 3, // Repeat rate: Faster // - Repeat mode: Specify when repeating key pressed can be interrupted. // - In theory ImGuiInputFlags_RepeatUntilOtherKeyPress may be a desirable default, but it would break too many behavior so everything is opt-in. ImGuiInputFlags_RepeatUntilRelease = 1 << 4, // Stop repeating when released (default for all functions except Shortcut). This only exists to allow overriding Shortcut() default behavior. ImGuiInputFlags_RepeatUntilKeyModsChange = 1 << 5, // Stop repeating when released OR if keyboard mods are changed (default for Shortcut) ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone = 1 << 6, // Stop repeating when released OR if keyboard mods are leaving the None state. Allows going from Mod+Key to Key by releasing Mod. ImGuiInputFlags_RepeatUntilOtherKeyPress = 1 << 7, // Stop repeating when released OR if any other keyboard key is pressed during the repeat // Flags for SetKeyOwner(), SetItemKeyOwner() // - Locking key away from non-input aware code. Locking is useful to make input-owner-aware code steal keys from non-input-owner-aware code. If all code is input-owner-aware locking would never be necessary. ImGuiInputFlags_LockThisFrame = 1 << 20, // Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared at end of frame. ImGuiInputFlags_LockUntilRelease = 1 << 21, // Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared when the key is released or at end of each frame if key is released. // - Condition for SetItemKeyOwner() ImGuiInputFlags_CondHovered = 1 << 22, // Only set if item is hovered (default to both) ImGuiInputFlags_CondActive = 1 << 23, // Only set if item is active (default to both) ImGuiInputFlags_CondDefault_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, // [Internal] Mask of which function support which flags ImGuiInputFlags_RepeatRateMask_ = ImGuiInputFlags_RepeatRateDefault | ImGuiInputFlags_RepeatRateNavMove | ImGuiInputFlags_RepeatRateNavTweak, ImGuiInputFlags_RepeatUntilMask_ = ImGuiInputFlags_RepeatUntilRelease | ImGuiInputFlags_RepeatUntilKeyModsChange | ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone | ImGuiInputFlags_RepeatUntilOtherKeyPress, ImGuiInputFlags_RepeatMask_ = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_, ImGuiInputFlags_CondMask_ = ImGuiInputFlags_CondHovered | ImGuiInputFlags_CondActive, ImGuiInputFlags_RouteTypeMask_ = ImGuiInputFlags_RouteActive | ImGuiInputFlags_RouteFocused | ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteAlways, ImGuiInputFlags_RouteOptionsMask_ = ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused | ImGuiInputFlags_RouteFromRootWindow, ImGuiInputFlags_SupportedByIsKeyPressed = ImGuiInputFlags_RepeatMask_, ImGuiInputFlags_SupportedByIsMouseClicked = ImGuiInputFlags_Repeat, ImGuiInputFlags_SupportedByShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_, ImGuiInputFlags_SupportedBySetNextItemShortcut = ImGuiInputFlags_RepeatMask_ | ImGuiInputFlags_RouteTypeMask_ | ImGuiInputFlags_RouteOptionsMask_ | ImGuiInputFlags_Tooltip, ImGuiInputFlags_SupportedBySetKeyOwner = ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease, ImGuiInputFlags_SupportedBySetItemKeyOwner = ImGuiInputFlags_SupportedBySetKeyOwner | ImGuiInputFlags_CondMask_, }; //----------------------------------------------------------------------------- // [SECTION] Clipper support //----------------------------------------------------------------------------- // Note that Max is exclusive, so perhaps should be using a Begin/End convention. struct ImGuiListClipperRange { int Min; int Max; bool PosToIndexConvert; // Begin/End are absolute position (will be converted to indices later) ImS8 PosToIndexOffsetMin; // Add to Min after converting to indices ImS8 PosToIndexOffsetMax; // Add to Min after converting to indices static ImGuiListClipperRange FromIndices(int min, int max) { ImGuiListClipperRange r = { min, max, false, 0, 0 }; return r; } static ImGuiListClipperRange FromPositions(float y1, float y2, int off_min, int off_max) { ImGuiListClipperRange r = { (int)y1, (int)y2, true, (ImS8)off_min, (ImS8)off_max }; return r; } }; // Temporary clipper data, buffers shared/reused between instances struct ImGuiListClipperData { ImGuiListClipper* ListClipper; float LossynessOffset; int StepNo; int ItemsFrozen; ImVector<ImGuiListClipperRange> Ranges; ImGuiListClipperData() { memset(this, 0, sizeof(*this)); } void Reset(ImGuiListClipper* clipper) { ListClipper = clipper; StepNo = ItemsFrozen = 0; Ranges.resize(0); } }; //----------------------------------------------------------------------------- // [SECTION] Navigation support //----------------------------------------------------------------------------- enum ImGuiActivateFlags_ { ImGuiActivateFlags_None = 0, ImGuiActivateFlags_PreferInput = 1 << 0, // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. ImGuiActivateFlags_PreferTweak = 1 << 1, // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default for Space key and if keyboard is not used. ImGuiActivateFlags_TryToPreserveState = 1 << 2, // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request ImGuiActivateFlags_FromShortcut = 1 << 4, // Activation requested by an item shortcut via SetNextItemShortcut() function. }; // Early work-in-progress API for ScrollToItem() enum ImGuiScrollFlags_ { ImGuiScrollFlags_None = 0, ImGuiScrollFlags_KeepVisibleEdgeX = 1 << 0, // If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis] ImGuiScrollFlags_KeepVisibleEdgeY = 1 << 1, // If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible] ImGuiScrollFlags_KeepVisibleCenterX = 1 << 2, // If item is not visible: scroll to make the item centered on X axis [rarely used] ImGuiScrollFlags_KeepVisibleCenterY = 1 << 3, // If item is not visible: scroll to make the item centered on Y axis ImGuiScrollFlags_AlwaysCenterX = 1 << 4, // Always center the result item on X axis [rarely used] ImGuiScrollFlags_AlwaysCenterY = 1 << 5, // Always center the result item on Y axis [default for Y axis for appearing window) ImGuiScrollFlags_NoScrollParent = 1 << 6, // Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to). ImGuiScrollFlags_MaskX_ = ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleCenterX | ImGuiScrollFlags_AlwaysCenterX, ImGuiScrollFlags_MaskY_ = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY, }; enum ImGuiNavHighlightFlags_ { ImGuiNavHighlightFlags_None = 0, ImGuiNavHighlightFlags_Compact = 1 << 1, // Compact highlight, no padding ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, // Draw rectangular highlight if (g.NavId == id) _even_ when using the mouse. ImGuiNavHighlightFlags_NoRounding = 1 << 3, }; enum ImGuiNavMoveFlags_ { ImGuiNavMoveFlags_None = 0, ImGuiNavMoveFlags_LoopX = 1 << 0, // On failed request, restart from opposite side ImGuiNavMoveFlags_LoopY = 1 << 1, ImGuiNavMoveFlags_WrapX = 1 << 2, // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) ImGuiNavMoveFlags_WrapY = 1 << 3, // This is not super useful but provided for completeness ImGuiNavMoveFlags_WrapMask_ = ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_WrapY, ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5, // Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) ImGuiNavMoveFlags_ScrollToEdgeY = 1 << 6, // Force scrolling to min/max (used by Home/End) // FIXME-NAV: Aim to remove or reword, probably unnecessary ImGuiNavMoveFlags_Forwarded = 1 << 7, ImGuiNavMoveFlags_DebugNoResult = 1 << 8, // Dummy scoring for debug purpose, don't apply result ImGuiNavMoveFlags_FocusApi = 1 << 9, // Requests from focus API can land/focus/activate items even if they are marked with _NoTabStop (see NavProcessItemForTabbingRequest() for details) ImGuiNavMoveFlags_IsTabbing = 1 << 10, // == Focus + Activate if item is Inputable + DontChangeNavHighlight ImGuiNavMoveFlags_IsPageMove = 1 << 11, // Identify a PageDown/PageUp request. ImGuiNavMoveFlags_Activate = 1 << 12, // Activate/select target item. ImGuiNavMoveFlags_NoSelect = 1 << 13, // Don't trigger selection by not setting g.NavJustMovedTo ImGuiNavMoveFlags_NoSetNavHighlight = 1 << 14, // Do not alter the visible state of keyboard vs mouse nav highlight ImGuiNavMoveFlags_NoClearActiveId = 1 << 15, // (Experimental) Do not clear active id when applying move result }; enum ImGuiNavLayer { ImGuiNavLayer_Main = 0, // Main scrolling layer ImGuiNavLayer_Menu = 1, // Menu layer (access with Alt) ImGuiNavLayer_COUNT }; // Storage for navigation query/results struct ImGuiNavItemData { ImGuiWindow* Window; // Init,Move // Best candidate window (result->ItemWindow->RootWindowForNav == request->Window) ImGuiID ID; // Init,Move // Best candidate item ID ImGuiID FocusScopeId; // Init,Move // Best candidate focus scope ID ImRect RectRel; // Init,Move // Best candidate bounding box in window relative space ImGuiItemFlags InFlags; // ????,Move // Best candidate item flags float DistBox; // Move // Best candidate box distance to current NavId float DistCenter; // Move // Best candidate center distance to current NavId float DistAxial; // Move // Best candidate axial distance to current NavId ImGuiSelectionUserData SelectionUserData;//I+Mov // Best candidate SetNextItemSelectionUserData() value. Valid if (InFlags & ImGuiItemFlags_HasSelectionUserData) ImGuiNavItemData() { Clear(); } void Clear() { Window = NULL; ID = FocusScopeId = 0; InFlags = 0; SelectionUserData = -1; DistBox = DistCenter = DistAxial = FLT_MAX; } }; // Storage for PushFocusScope() struct ImGuiFocusScopeData { ImGuiID ID; ImGuiID WindowID; }; //----------------------------------------------------------------------------- // [SECTION] Typing-select support //----------------------------------------------------------------------------- // Flags for GetTypingSelectRequest() enum ImGuiTypingSelectFlags_ { ImGuiTypingSelectFlags_None = 0, ImGuiTypingSelectFlags_AllowBackspace = 1 << 0, // Backspace to delete character inputs. If using: ensure GetTypingSelectRequest() is not called more than once per frame (filter by e.g. focus state) ImGuiTypingSelectFlags_AllowSingleCharMode = 1 << 1, // Allow "single char" search mode which is activated when pressing the same character multiple times. }; // Returned by GetTypingSelectRequest(), designed to eventually be public. struct IMGUI_API ImGuiTypingSelectRequest { ImGuiTypingSelectFlags Flags; // Flags passed to GetTypingSelectRequest() int SearchBufferLen; const char* SearchBuffer; // Search buffer contents (use full string. unless SingleCharMode is set, in which case use SingleCharSize). bool SelectRequest; // Set when buffer was modified this frame, requesting a selection. bool SingleCharMode; // Notify when buffer contains same character repeated, to implement special mode. In this situation it preferred to not display any on-screen search indication. ImS8 SingleCharSize; // Length in bytes of first letter codepoint (1 for ascii, 2-4 for UTF-8). If (SearchBufferLen==RepeatCharSize) only 1 letter has been input. }; // Storage for GetTypingSelectRequest() struct IMGUI_API ImGuiTypingSelectState { ImGuiTypingSelectRequest Request; // User-facing data char SearchBuffer[64]; // Search buffer: no need to make dynamic as this search is very transient. ImGuiID FocusScope; int LastRequestFrame = 0; float LastRequestTime = 0.0f; bool SingleCharModeLock = false; // After a certain single char repeat count we lock into SingleCharMode. Two benefits: 1) buffer never fill, 2) we can provide an immediate SingleChar mode without timer elapsing. ImGuiTypingSelectState() { memset(this, 0, sizeof(*this)); } void Clear() { SearchBuffer[0] = 0; SingleCharModeLock = false; } // We preserve remaining data for easier debugging }; //----------------------------------------------------------------------------- // [SECTION] Columns support //----------------------------------------------------------------------------- // Flags for internal's BeginColumns(). This is an obsolete API. Prefer using BeginTable() nowadays! enum ImGuiOldColumnFlags_ { ImGuiOldColumnFlags_None = 0, ImGuiOldColumnFlags_NoBorder = 1 << 0, // Disable column dividers ImGuiOldColumnFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4, // Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None, //ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder, //ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize, //ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths, //ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow, //ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize, #endif }; struct ImGuiOldColumnData { float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) float OffsetNormBeforeResize; ImGuiOldColumnFlags Flags; // Not exposed ImRect ClipRect; ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); } }; struct ImGuiOldColumns { ImGuiID ID; ImGuiOldColumnFlags Flags; bool IsFirstFrame; bool IsBeingResized; int Current; int Count; float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x float LineMinY, LineMaxY; float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns() float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns() ImRect HostInitialClipRect; // Backup of ClipRect at the time of BeginColumns() ImRect HostBackupClipRect; // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground() ImRect HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns() ImVector<ImGuiOldColumnData> Columns; ImDrawListSplitter Splitter; ImGuiOldColumns() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- // [SECTION] Box-select support //----------------------------------------------------------------------------- struct ImGuiBoxSelectState { // Active box-selection data (persistent, 1 active at a time) ImGuiID ID; bool IsActive; bool IsStarting; bool IsStartedFromVoid; // Starting click was not from an item. bool IsStartedSetNavIdOnce; bool RequestClear; ImGuiKeyChord KeyMods : 16; // Latched key-mods for box-select logic. ImVec2 StartPosRel; // Start position in window-contents relative space (to support scrolling) ImVec2 EndPosRel; // End position in window-contents relative space ImVec2 ScrollAccum; // Scrolling accumulator (to behave at high-frame spaces) ImGuiWindow* Window; // Temporary/Transient data bool UnclipMode; // (Temp/Transient, here in hot area). Set/cleared by the BeginMultiSelect()/EndMultiSelect() owning active box-select. ImRect UnclipRect; // Rectangle where ItemAdd() clipping may be temporarily disabled. Need support by multi-select supporting widgets. ImRect BoxSelectRectPrev; // Selection rectangle in absolute coordinates (derived every frame from BoxSelectStartPosRel and MousePos) ImRect BoxSelectRectCurr; ImGuiBoxSelectState() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- // [SECTION] Multi-select support //----------------------------------------------------------------------------- // We always assume that -1 is an invalid value (which works for indices and pointers) #define ImGuiSelectionUserData_Invalid ((ImGuiSelectionUserData)-1) // Temporary storage for multi-select struct IMGUI_API ImGuiMultiSelectTempData { ImGuiMultiSelectIO IO; // MUST BE FIRST FIELD. Requests are set and returned by BeginMultiSelect()/EndMultiSelect() + written to by user during the loop. ImGuiMultiSelectState* Storage; ImGuiID FocusScopeId; // Copied from g.CurrentFocusScopeId (unless another selection scope was pushed manually) ImGuiMultiSelectFlags Flags; ImVec2 ScopeRectMin; ImVec2 BackupCursorMaxPos; ImGuiSelectionUserData LastSubmittedItem; // Copy of last submitted item data, used to merge output ranges. ImGuiID BoxSelectId; ImGuiKeyChord KeyMods; ImS8 LoopRequestSetAll; // -1: no operation, 0: clear all, 1: select all. bool IsEndIO; // Set when switching IO from BeginMultiSelect() to EndMultiSelect() state. bool IsFocused; // Set if currently focusing the selection scope (any item of the selection). May be used if you have custom shortcut associated to selection. bool IsKeyboardSetRange; // Set by BeginMultiSelect() when using Shift+Navigation. Because scrolling may be affected we can't afford a frame of lag with Shift+Navigation. bool NavIdPassedBy; bool RangeSrcPassedBy; // Set by the item that matches RangeSrcItem. bool RangeDstPassedBy; // Set by the item that matches NavJustMovedToId when IsSetRange is set. ImGuiMultiSelectTempData() { Clear(); } void Clear() { size_t io_sz = sizeof(IO); ClearIO(); memset((void*)(&IO + 1), 0, sizeof(*this) - io_sz); } // Zero-clear except IO as we preserve IO.Requests[] buffer allocation. void ClearIO() { IO.Requests.resize(0); IO.RangeSrcItem = IO.NavIdItem = ImGuiSelectionUserData_Invalid; IO.NavIdSelected = IO.RangeSrcReset = false; } }; // Persistent storage for multi-select (as long as selection is alive) struct IMGUI_API ImGuiMultiSelectState { ImGuiWindow* Window; ImGuiID ID; int LastFrameActive; // Last used frame-count, for GC. int LastSelectionSize; // Set by BeginMultiSelect() based on optional info provided by user. May be -1 if unknown. ImS8 RangeSelected; // -1 (don't have) or true/false ImS8 NavIdSelected; // -1 (don't have) or true/false ImGuiSelectionUserData RangeSrcItem; // ImGuiSelectionUserData NavIdItem; // SetNextItemSelectionUserData() value for NavId (if part of submitted items) ImGuiMultiSelectState() { Window = NULL; ID = 0; LastFrameActive = LastSelectionSize = 0; RangeSelected = NavIdSelected = -1; RangeSrcItem = NavIdItem = ImGuiSelectionUserData_Invalid; } }; //----------------------------------------------------------------------------- // [SECTION] Docking support //----------------------------------------------------------------------------- #ifdef IMGUI_HAS_DOCK // <this is filled in 'docking' branch> #endif // #ifdef IMGUI_HAS_DOCK //----------------------------------------------------------------------------- // [SECTION] Viewport support //----------------------------------------------------------------------------- // ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) // Every instance of ImGuiViewport is in fact a ImGuiViewportP. struct ImGuiViewportP : public ImGuiViewport { int BgFgDrawListsLastFrame[2]; // Last frame number the background (0) and foreground (1) draw lists were used ImDrawList* BgFgDrawLists[2]; // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. ImDrawData DrawDataP; ImDrawDataBuilder DrawDataBuilder; // Temporary data while building final ImDrawData // Per-viewport work area // - Insets are >= 0.0f values, distance from viewport corners to work area. // - BeginMainMenuBar() and DockspaceOverViewport() tend to use work area to avoid stepping over existing contents. // - Generally 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. ImVec2 WorkInsetMin; // Work Area inset locked for the frame. GetWorkRect() always fits within GetMainRect(). ImVec2 WorkInsetMax; // " ImVec2 BuildWorkInsetMin; // Work Area inset accumulator for current frame, to become next frame's WorkInset ImVec2 BuildWorkInsetMax; // " ImGuiViewportP() { BgFgDrawListsLastFrame[0] = BgFgDrawListsLastFrame[1] = -1; BgFgDrawLists[0] = BgFgDrawLists[1] = NULL; } ~ImGuiViewportP() { if (BgFgDrawLists[0]) IM_DELETE(BgFgDrawLists[0]); if (BgFgDrawLists[1]) IM_DELETE(BgFgDrawLists[1]); } // Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) ImVec2 CalcWorkRectPos(const ImVec2& inset_min) const { return ImVec2(Pos.x + inset_min.x, Pos.y + inset_min.y); } ImVec2 CalcWorkRectSize(const ImVec2& inset_min, const ImVec2& inset_max) const { return ImVec2(ImMax(0.0f, Size.x - inset_min.x - inset_max.x), ImMax(0.0f, Size.y - inset_min.y - inset_max.y)); } void UpdateWorkRect() { WorkPos = CalcWorkRectPos(WorkInsetMin); WorkSize = CalcWorkRectSize(WorkInsetMin, WorkInsetMax); } // Update public fields // Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) ImRect GetMainRect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } ImRect GetWorkRect() const { return ImRect(WorkPos.x, WorkPos.y, WorkPos.x + WorkSize.x, WorkPos.y + WorkSize.y); } ImRect GetBuildWorkRect() const { ImVec2 pos = CalcWorkRectPos(BuildWorkInsetMin); ImVec2 size = CalcWorkRectSize(BuildWorkInsetMin, BuildWorkInsetMax); return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); } }; //----------------------------------------------------------------------------- // [SECTION] Settings support //----------------------------------------------------------------------------- // Windows data saved in imgui.ini file // Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily. // (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure) struct ImGuiWindowSettings { ImGuiID ID; ImVec2ih Pos; ImVec2ih Size; bool Collapsed; bool IsChild; bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) bool WantDelete; // Set to invalidate/delete the settings entry ImGuiWindowSettings() { memset(this, 0, sizeof(*this)); } char* GetName() { return (char*)(this + 1); } }; struct ImGuiSettingsHandler { const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']' ImGuiID TypeHash; // == ImHashStr(TypeName) void (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Clear all settings data void (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called before reading (in registration order) void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]" void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry void (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler); // Read: Called after reading (in registration order) void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf' void* UserData; ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- // [SECTION] Localization support //----------------------------------------------------------------------------- // This is experimental and not officially supported, it'll probably fall short of features, if/when it does we may backtrack. enum ImGuiLocKey : int { ImGuiLocKey_VersionStr, ImGuiLocKey_TableSizeOne, ImGuiLocKey_TableSizeAllFit, ImGuiLocKey_TableSizeAllDefault, ImGuiLocKey_TableResetOrder, ImGuiLocKey_WindowingMainMenuBar, ImGuiLocKey_WindowingPopup, ImGuiLocKey_WindowingUntitled, ImGuiLocKey_CopyLink, ImGuiLocKey_COUNT }; struct ImGuiLocEntry { ImGuiLocKey Key; const char* Text; }; //----------------------------------------------------------------------------- // [SECTION] Metrics, Debug Tools //----------------------------------------------------------------------------- enum ImGuiDebugLogFlags_ { // Event types ImGuiDebugLogFlags_None = 0, ImGuiDebugLogFlags_EventActiveId = 1 << 0, ImGuiDebugLogFlags_EventFocus = 1 << 1, ImGuiDebugLogFlags_EventPopup = 1 << 2, ImGuiDebugLogFlags_EventNav = 1 << 3, ImGuiDebugLogFlags_EventClipper = 1 << 4, ImGuiDebugLogFlags_EventSelection = 1 << 5, ImGuiDebugLogFlags_EventIO = 1 << 6, ImGuiDebugLogFlags_EventInputRouting = 1 << 7, ImGuiDebugLogFlags_EventMask_ = ImGuiDebugLogFlags_EventActiveId | ImGuiDebugLogFlags_EventFocus | ImGuiDebugLogFlags_EventPopup | ImGuiDebugLogFlags_EventNav | ImGuiDebugLogFlags_EventClipper | ImGuiDebugLogFlags_EventSelection | ImGuiDebugLogFlags_EventIO | ImGuiDebugLogFlags_EventInputRouting, ImGuiDebugLogFlags_OutputToTTY = 1 << 20, // Also send output to TTY ImGuiDebugLogFlags_OutputToTestEngine = 1 << 21, // Also send output to Test Engine }; struct ImGuiDebugAllocEntry { int FrameCount; ImS16 AllocCount; ImS16 FreeCount; }; struct ImGuiDebugAllocInfo { int TotalAllocCount; // Number of call to MemAlloc(). int TotalFreeCount; ImS16 LastEntriesIdx; // Current index in buffer ImGuiDebugAllocEntry LastEntriesBuf[6]; // Track last 6 frames that had allocations ImGuiDebugAllocInfo() { memset(this, 0, sizeof(*this)); } }; struct ImGuiMetricsConfig { bool ShowDebugLog = false; bool ShowIDStackTool = false; bool ShowWindowsRects = false; bool ShowWindowsBeginOrder = false; bool ShowTablesRects = false; bool ShowDrawCmdMesh = true; bool ShowDrawCmdBoundingBoxes = true; bool ShowTextEncodingViewer = false; bool ShowAtlasTintedWithTextColor = false; int ShowWindowsRectsType = -1; int ShowTablesRectsType = -1; int HighlightMonitorIdx = -1; ImGuiID HighlightViewportID = 0; }; struct ImGuiStackLevelInfo { ImGuiID ID; ImS8 QueryFrameCount; // >= 1: Query in progress bool QuerySuccess; // Obtained result from DebugHookIdInfo() ImGuiDataType DataType : 8; char Desc[57]; // Arbitrarily sized buffer to hold a result (FIXME: could replace Results[] with a chunk stream?) FIXME: Now that we added CTRL+C this should be fixed. ImGuiStackLevelInfo() { memset(this, 0, sizeof(*this)); } }; // State for ID Stack tool queries struct ImGuiIDStackTool { int LastActiveFrame; int StackLevel; // -1: query stack and resize Results, >= 0: individual stack level ImGuiID QueryId; // ID to query details for ImVector<ImGuiStackLevelInfo> Results; bool CopyToClipboardOnCtrlC; float CopyToClipboardLastTime; ImGuiIDStackTool() { memset(this, 0, sizeof(*this)); CopyToClipboardLastTime = -FLT_MAX; } }; //----------------------------------------------------------------------------- // [SECTION] Generic context hooks //----------------------------------------------------------------------------- typedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook); enum ImGuiContextHookType { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown, ImGuiContextHookType_PendingRemoval_ }; struct ImGuiContextHook { ImGuiID HookId; // A unique ID assigned by AddContextHook() ImGuiContextHookType Type; ImGuiID Owner; ImGuiContextHookCallback Callback; void* UserData; ImGuiContextHook() { memset(this, 0, sizeof(*this)); } }; //----------------------------------------------------------------------------- // [SECTION] ImGuiContext (main Dear ImGui context) //----------------------------------------------------------------------------- struct ImGuiContext { bool Initialized; bool FontAtlasOwnedByContext; // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it. ImGuiIO IO; ImGuiPlatformIO PlatformIO; ImGuiStyle Style; ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. float FontScale; // == FontSize / Font->FontSize float CurrentDpiScale; // Current window/viewport DpiScale ImDrawListSharedData DrawListSharedData; double Time; int FrameCount; int FrameCountEnded; int FrameCountRendered; bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame() bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed bool WithinEndChild; // Set within EndChild() bool GcCompactAll; // Request full GC bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() void* TestEngine; // Test engine user data char ContextName[16]; // Storage for a context name (to facilitate debugging multi-context setups) // Inputs ImVector<ImGuiInputEvent> InputEventsQueue; // Input events which will be trickled/written into IO structure. ImVector<ImGuiInputEvent> InputEventsTrail; // Past input events processed in NewFrame(). This is to allow domain-specific application to access e.g mouse/pen trail. ImGuiMouseSource InputEventsNextMouseSource; ImU32 InputEventsNextEventId; // Windows state ImVector<ImGuiWindow*> Windows; // Windows, sorted in display order, back to front ImVector<ImGuiWindow*> WindowsFocusOrder; // Root windows, sorted in focus order, back to front. ImVector<ImGuiWindow*> WindowsTempSortBuffer; // Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child ImVector<ImGuiWindowStackData> CurrentWindowStack; ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow* int WindowsActiveCount; // Number of unique windows submitted by frame ImVec2 WindowsHoverPadding; // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, WINDOWS_HOVER_PADDING). ImGuiID DebugBreakInWindow; // Set to break in Begin() call. ImGuiWindow* CurrentWindow; // Window being drawn into ImGuiWindow* HoveredWindow; // Window the mouse is hovering. Will typically catch mouse inputs. ImGuiWindow* HoveredWindowUnderMovingWindow; // Hovered window ignoring MovingWindow. Only set if MovingWindow is set. ImGuiWindow* HoveredWindowBeforeClear; // Window the mouse is hovering. Filled even with _NoMouse. This is currently useful for multi-context compositors. ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. ImVec2 WheelingWindowRefMousePos; int WheelingWindowStartFrame; // This may be set one frame before WheelingWindow is != NULL int WheelingWindowScrolledFrame; float WheelingWindowReleaseTimer; ImVec2 WheelingWindowWheelRemainder; ImVec2 WheelingAxisAvg; // Item/widgets state and tracking information ImGuiID DebugHookIdInfo; // Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line] ImGuiID HoveredId; // Hovered widget, filled during the frame ImGuiID HoveredIdPreviousFrame; float HoveredIdTimer; // Measure contiguous hovering time float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active bool HoveredIdAllowOverlap; bool HoveredIdIsDisabled; // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. bool ItemUnclipByLog; // Disable ItemAdd() clipping, essentially a memory-locality friendly copy of LogEnabled ImGuiID ActiveId; // Active widget ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) float ActiveIdTimer; bool ActiveIdIsJustActivated; // Set at the time of activation for one frame bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) bool ActiveIdNoClearOnFocusLoss; // Disable losing active id if the active id window gets unfocused. bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state. bool ActiveIdHasBeenEditedThisFrame; bool ActiveIdFromShortcut; int ActiveIdMouseButton : 8; ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) ImGuiWindow* ActiveIdWindow; ImGuiInputSource ActiveIdSource; // Activating source: ImGuiInputSource_Mouse OR ImGuiInputSource_Keyboard OR ImGuiInputSource_Gamepad ImGuiID ActiveIdPreviousFrame; bool ActiveIdPreviousFrameIsAlive; bool ActiveIdPreviousFrameHasBeenEditedBefore; ImGuiWindow* ActiveIdPreviousFrameWindow; ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation. float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. // Key/Input Ownership + Shortcut Routing system // - The idea is that instead of "eating" a given key, we can link to an owner. // - Input query can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. // - Routing is requested ahead of time for a given chord (Key + Mods) and granted in NewFrame(). double LastKeyModsChangeTime; // Record the last time key mods changed (affect repeat delay when using shortcut logic) double LastKeyModsChangeFromNoneTime; // Record the last time key mods changed away from being 0 (affect repeat delay when using shortcut logic) double LastKeyboardKeyPressTime; // Record the last time a keyboard key (ignore mouse/gamepad ones) was pressed. ImBitArrayForNamedKeys KeysMayBeCharInput; // Lookup to tell if a key can emit char input, see IsKeyChordPotentiallyCharInput(). sizeof() = 20 bytes ImGuiKeyOwnerData KeysOwnerData[ImGuiKey_NamedKey_COUNT]; ImGuiKeyRoutingTable KeysRoutingTable; ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) bool ActiveIdUsingAllKeyboardKeys; // Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) ImGuiKeyChord DebugBreakInShortcutRouting; // Set to break in SetShortcutRouting()/Shortcut() calls. //ImU32 ActiveIdUsingNavInputMask; // [OBSOLETE] Since (IMGUI_VERSION_NUM >= 18804) : 'g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);' becomes --> 'SetKeyOwner(ImGuiKey_Escape, g.ActiveId) and/or SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId);' // Next window/item data ImGuiID CurrentFocusScopeId; // Value for currently appending items == g.FocusScopeStack.back(). Not to be mistaken with g.NavFocusScopeId. ImGuiItemFlags CurrentItemFlags; // Value for currently appending items == g.ItemFlagsStack.back() ImGuiID DebugLocateId; // Storage for DebugLocateItemOnHover() feature: this is read by ItemAdd() so we keep it in a hot/cached location ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions ImGuiLastItemData LastItemData; // Storage for last submitted item (setup by ItemAdd) ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions bool DebugShowGroupRects; // Shared stacks ImGuiCol DebugFlashStyleColorIdx; // (Keep close to ColorStack to share cache line) ImVector<ImGuiColorMod> ColorStack; // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() ImVector<ImGuiStyleMod> StyleVarStack; // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont() - inherited by Begin() ImVector<ImGuiFocusScopeData> FocusScopeStack; // Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() ImVector<ImGuiItemFlags> ItemFlagsStack; // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() ImVector<ImGuiGroupData> GroupStack; // Stack for BeginGroup()/EndGroup() - not inherited by Begin() ImVector<ImGuiPopupData> OpenPopupStack; // Which popups are open (persistent) ImVector<ImGuiPopupData> BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame) ImVector<ImGuiTreeNodeStackData>TreeNodeStack; // Stack for TreeNode() // Viewports ImVector<ImGuiViewportP*> Viewports; // Active viewports (Size==1 in 'master' branch). Each viewports hold their copy of ImDrawData. // Gamepad/keyboard Navigation ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusedWindow' ImGuiID NavId; // Focused item for navigation ImGuiID NavFocusScopeId; // Focused focus scope (e.g. selection code often wants to "clear other items" when landing on an item of the same scope) ImGuiNavLayer NavLayer; // Focused layer (main scrolling layer, or menu/title bar layer) ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItem() ImGuiID NavActivateDownId; // ~~ IsKeyDown(ImGuiKey_Space) || IsKeyDown(ImGuiKey_Enter) || IsKeyDown(ImGuiKey_NavGamepadActivate) ? NavId : 0 ImGuiID NavActivatePressedId; // ~~ IsKeyPressed(ImGuiKey_Space) || IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_NavGamepadActivate) ? NavId : 0 (no repeat) ImGuiActivateFlags NavActivateFlags; ImVector<ImGuiFocusScopeData> NavFocusRoute; // Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window->ParentWindowForFocusRoute chain. ImGuiID NavHighlightActivatedId; float NavHighlightActivatedTimer; ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame. ImGuiActivateFlags NavNextActivateFlags; ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource_Keyboard or ImGuiInputSource_Mouse ImGuiSelectionUserData NavLastValidSelectionUserData; // Last valid data passed to SetNextItemSelectionUser(), or -1. For current window. Not reset when focusing an item that doesn't have selection data. bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRectRel is valid bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default) bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover) bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again. // Navigation: Init & Move Requests bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() bool NavInitRequest; // Init request for appearing window to select first item bool NavInitRequestFromMove; ImGuiNavItemData NavInitResult; // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) bool NavMoveSubmitted; // Move request submitted, will process result on next NewFrame() bool NavMoveScoringItems; // Move request submitted, still scoring incoming items bool NavMoveForwardToNextFrame; ImGuiNavMoveFlags NavMoveFlags; ImGuiScrollFlags NavMoveScrollFlags; ImGuiKeyChord NavMoveKeyMods; ImGuiDir NavMoveDir; // Direction of the move request (left/right/up/down) ImGuiDir NavMoveDirForDebug; ImGuiDir NavMoveClipDir; // FIXME-NAV: Describe the purpose of this better. Might want to rename? ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring. ImRect NavScoringNoClipRect; // Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted int NavScoringDebugCount; // Metrics for debugging int NavTabbingDir; // Generally -1 or +1, 0 when tabbing without a nav id int NavTabbingCounter; // >0 when counting items for tabbing ImGuiNavItemData NavMoveResultLocal; // Best move request candidate within NavWindow ImGuiNavItemData NavMoveResultLocalVisible; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag) ImGuiNavItemData NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag) ImGuiNavItemData NavTabbingResultFirst; // First tabbing request candidate within NavWindow and flattened hierarchy // Navigation: record of last move request ImGuiID NavJustMovedFromFocusScopeId; // Just navigated from this focus scope id (result of a successfully MoveRequest). ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest). ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). ImGuiKeyChord NavJustMovedToKeyMods; bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. bool NavJustMovedToHasSelectionData; // Copy of move result's InFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) ImGuiKeyChord ConfigNavWindowingKeyNext; // = ImGuiMod_Ctrl | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiKey_Tab on OS X). For reconfiguration (see #4828) ImGuiKeyChord ConfigNavWindowingKeyPrev; // = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab on OS X) ImGuiWindow* NavWindowingTarget; // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. ImGuiWindow* NavWindowingListWindow; // Internal window actually listing the CTRL+Tab contents float NavWindowingTimer; float NavWindowingHighlightAlpha; bool NavWindowingToggleLayer; ImGuiKey NavWindowingToggleKey; ImVec2 NavWindowingAccumDeltaPos; ImVec2 NavWindowingAccumDeltaSize; // Render float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) // Drag and Drop bool DragDropActive; bool DragDropWithinSource; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. bool DragDropWithinTarget; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. ImGuiDragDropFlags DragDropSourceFlags; int DragDropSourceFrameCount; int DragDropMouseButton; ImGuiPayload DragDropPayload; ImRect DragDropTargetRect; // Store rectangle of current target candidate (we favor small targets when overlapping) ImRect DragDropTargetClipRect; // Store ClipRect at the time of item's drawing ImGuiID DragDropTargetId; ImGuiDragDropFlags DragDropAcceptFlags; float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface) 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 ImGuiID DragDropHoldJustPressedId; // Set when holding a payload just made ButtonBehavior() return a press. ImVector<unsigned char> DragDropPayloadBufHeap; // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size unsigned char DragDropPayloadBufLocal[16]; // Local buffer for small payloads // Clipper int ClipperTempDataStacked; ImVector<ImGuiListClipperData> ClipperTempData; // Tables ImGuiTable* CurrentTable; ImGuiID DebugBreakInTable; // Set to break in BeginTable() call. int TablesTempDataStacked; // Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) ImVector<ImGuiTableTempData> TablesTempData; // Temporary table data (buffers reused/shared across instances, support nesting) ImPool<ImGuiTable> Tables; // Persistent table data ImVector<float> TablesLastTimeActive; // Last used timestamp of each tables (SOA, for efficient GC) ImVector<ImDrawChannel> DrawChannelsTempMergeBuffer; // Tab bars ImGuiTabBar* CurrentTabBar; ImPool<ImGuiTabBar> TabBars; ImVector<ImGuiPtrOrIndex> CurrentTabBarStack; ImVector<ImGuiShrinkWidthItem> ShrinkWidthBuffer; // Multi-Select state ImGuiBoxSelectState BoxSelectState; ImGuiMultiSelectTempData* CurrentMultiSelect; int MultiSelectTempDataStacked; // Temporary multi-select data size (because we leave previous instances undestructed, we generally don't use MultiSelectTempData.Size) ImVector<ImGuiMultiSelectTempData> MultiSelectTempData; ImPool<ImGuiMultiSelectState> MultiSelectStorage; // Hover Delay system ImGuiID HoverItemDelayId; ImGuiID HoverItemDelayIdPreviousFrame; float HoverItemDelayTimer; // Currently used by IsItemHovered() float HoverItemDelayClearTimer; // Currently used by IsItemHovered(): grace time before g.TooltipHoverTimer gets cleared. ImGuiID HoverItemUnlockedStationaryId; // Mouse has once been stationary on this item. Only reset after departing the item. ImGuiID HoverWindowUnlockedStationaryId; // Mouse has once been stationary on this window. Only reset after departing the window. // Mouse state ImGuiMouseCursor MouseCursor; float MouseStationaryTimer; // Time the mouse has been stationary (with some loose heuristic) ImVec2 MouseLastValidPos; // Widget state ImGuiInputTextState InputTextState; ImGuiInputTextDeactivatedState InputTextDeactivatedState; ImFont InputTextPasswordFont; ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc. ImGuiDataTypeStorage DataTypeZeroValue; // 0 for all data types int BeginMenuDepth; int BeginComboDepth; ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets ImGuiID ColorEditCurrentID; // Set temporarily while inside of the parent-most ColorEdit4/ColorPicker4 (because they call each others). ImGuiID ColorEditSavedID; // ID we are saving/restoring HS for float ColorEditSavedHue; // Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips float ColorEditSavedSat; // Backup of last Saturation associated to LastColor, so we can restore Saturation in lossy RGB<>HSV round trips ImU32 ColorEditSavedColor; // RGB value with alpha set to 0. ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker. ImGuiComboPreviewData ComboPreviewData; ImRect WindowResizeBorderExpectedRect; // Expected border rect, switch to relative edit if moving bool WindowResizeRelativeMode; short ScrollbarSeekMode; // 0: relative, -1/+1: prev/next page. float ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? float SliderGrabClickOffset; float SliderCurrentAccum; // Accumulated slider delta when using navigation controls. bool SliderCurrentAccumDirty; // Has the accumulated slider delta changed since last time we tried to apply it? bool DragCurrentAccumDirty; float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio float DisabledAlphaBackup; // Backup for style.Alpha for BeginDisabled() short DisabledStackSize; short LockMarkEdited; short TooltipOverrideCount; ImVector<char> ClipboardHandlerData; // If no custom clipboard handler is defined ImVector<ImGuiID> MenusIdSubmittedThisFrame; // A list of menu IDs that were rendered at least once ImGuiTypingSelectState TypingSelectState; // State for GetTypingSelectRequest() // Platform support ImGuiPlatformImeData PlatformImeData; // Data updated by current frame ImGuiPlatformImeData PlatformImeDataPrev; // Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. // Settings bool SettingsLoaded; float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero ImGuiTextBuffer SettingsIniData; // In memory .ini settings ImVector<ImGuiSettingsHandler> SettingsHandlers; // List of .ini settings handlers ImChunkStream<ImGuiWindowSettings> SettingsWindows; // ImGuiWindow .ini settings entries ImChunkStream<ImGuiTableSettings> SettingsTables; // ImGuiTable .ini settings entries ImVector<ImGuiContextHook> Hooks; // Hooks for extensions (e.g. test engine) ImGuiID HookIdNext; // Next available HookId // Localization const char* LocalizationTable[ImGuiLocKey_COUNT]; // Capture/Logging bool LogEnabled; // Currently capturing ImGuiLogType LogType; // Capture target ImFileHandle LogFile; // If != NULL log to stdout/ file ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. const char* LogNextPrefix; const char* LogNextSuffix; float LogLinePosY; bool LogLineFirstItem; int LogDepthRef; int LogDepthToExpand; int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call. // Debug Tools // (some of the highly frequently used data are interleaved in other structures above: DebugBreakXXX fields, DebugHookIdInfo, DebugLocateId etc.) ImGuiDebugLogFlags DebugLogFlags; ImGuiTextBuffer DebugLogBuf; ImGuiTextIndex DebugLogIndex; ImGuiDebugLogFlags DebugLogAutoDisableFlags; ImU8 DebugLogAutoDisableFrames; ImU8 DebugLocateFrames; // For DebugLocateItemOnHover(). This is used together with DebugLocateId which is in a hot/cached spot above. bool DebugBreakInLocateId; // Debug break in ItemAdd() call for g.DebugLocateId. ImGuiKeyChord DebugBreakKeyChord; // = ImGuiKey_Pause ImS8 DebugBeginReturnValueCullDepth; // Cycle between 0..9 then wrap around. bool DebugItemPickerActive; // Item picker is active (started with DebugStartItemPicker()) ImU8 DebugItemPickerMouseButton; ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this ID float DebugFlashStyleColorTime; ImVec4 DebugFlashStyleColorBackup; ImGuiMetricsConfig DebugMetricsConfig; ImGuiIDStackTool DebugIDStackTool; ImGuiDebugAllocInfo DebugAllocInfo; // Misc float FramerateSecPerFrame[60]; // Calculate estimate of framerate for user over the last 60 frames.. int FramerateSecPerFrameIdx; int FramerateSecPerFrameCount; float FramerateSecPerFrameAccum; int WantCaptureMouseNextFrame; // Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. int WantCaptureKeyboardNextFrame; // " int WantTextInputNextFrame; ImVector<char> TempBuffer; // Temporary text buffer char TempKeychordName[64]; ImGuiContext(ImFontAtlas* shared_font_atlas) { IO.Ctx = this; InputTextState.Ctx = this; Initialized = false; FontAtlasOwnedByContext = shared_font_atlas ? false : true; Font = NULL; FontSize = FontBaseSize = FontScale = CurrentDpiScale = 0.0f; IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)(); Time = 0.0f; FrameCount = 0; FrameCountEnded = FrameCountRendered = -1; WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false; GcCompactAll = false; TestEngineHookItems = false; TestEngine = NULL; memset(ContextName, 0, sizeof(ContextName)); InputEventsNextMouseSource = ImGuiMouseSource_Mouse; InputEventsNextEventId = 1; WindowsActiveCount = 0; CurrentWindow = NULL; HoveredWindow = NULL; HoveredWindowUnderMovingWindow = NULL; HoveredWindowBeforeClear = NULL; MovingWindow = NULL; WheelingWindow = NULL; WheelingWindowStartFrame = WheelingWindowScrolledFrame = -1; WheelingWindowReleaseTimer = 0.0f; DebugHookIdInfo = 0; HoveredId = HoveredIdPreviousFrame = 0; HoveredIdAllowOverlap = false; HoveredIdIsDisabled = false; HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f; ItemUnclipByLog = false; ActiveId = 0; ActiveIdIsAlive = 0; ActiveIdTimer = 0.0f; ActiveIdIsJustActivated = false; ActiveIdAllowOverlap = false; ActiveIdNoClearOnFocusLoss = false; ActiveIdHasBeenPressedBefore = false; ActiveIdHasBeenEditedBefore = false; ActiveIdHasBeenEditedThisFrame = false; ActiveIdFromShortcut = false; ActiveIdClickOffset = ImVec2(-1, -1); ActiveIdWindow = NULL; ActiveIdSource = ImGuiInputSource_None; ActiveIdMouseButton = -1; ActiveIdPreviousFrame = 0; ActiveIdPreviousFrameIsAlive = false; ActiveIdPreviousFrameHasBeenEditedBefore = false; ActiveIdPreviousFrameWindow = NULL; LastActiveId = 0; LastActiveIdTimer = 0.0f; LastKeyboardKeyPressTime = LastKeyModsChangeTime = LastKeyModsChangeFromNoneTime = -1.0; ActiveIdUsingNavDirMask = 0x00; ActiveIdUsingAllKeyboardKeys = false; CurrentFocusScopeId = 0; CurrentItemFlags = ImGuiItemFlags_None; DebugShowGroupRects = false; NavWindow = NULL; NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = 0; NavLayer = ImGuiNavLayer_Main; NavNextActivateId = 0; NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None; NavHighlightActivatedId = 0; NavHighlightActivatedTimer = 0.0f; NavInputSource = ImGuiInputSource_Keyboard; NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid; NavIdIsAlive = false; NavMousePosDirty = false; NavDisableHighlight = true; NavDisableMouseHover = false; NavAnyRequest = false; NavInitRequest = false; NavInitRequestFromMove = false; NavMoveSubmitted = false; NavMoveScoringItems = false; NavMoveForwardToNextFrame = false; NavMoveFlags = ImGuiNavMoveFlags_None; NavMoveScrollFlags = ImGuiScrollFlags_None; NavMoveKeyMods = ImGuiMod_None; NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None; NavScoringDebugCount = 0; NavTabbingDir = 0; NavTabbingCounter = 0; NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0; NavJustMovedToKeyMods = ImGuiMod_None; NavJustMovedToIsTabbing = false; NavJustMovedToHasSelectionData = false; // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... // FIXME: Because this value is stored, it annoyingly interfere with toggling io.ConfigMacOSXBehaviors updating this.. ConfigNavWindowingKeyNext = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiKey_Tab); ConfigNavWindowingKeyPrev = IO.ConfigMacOSXBehaviors ? (ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey_Tab) : (ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Tab); NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL; NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f; NavWindowingToggleLayer = false; NavWindowingToggleKey = ImGuiKey_None; DimBgRatio = 0.0f; DragDropActive = DragDropWithinSource = DragDropWithinTarget = false; DragDropSourceFlags = ImGuiDragDropFlags_None; DragDropSourceFrameCount = -1; DragDropMouseButton = -1; DragDropTargetId = 0; DragDropAcceptFlags = ImGuiDragDropFlags_None; DragDropAcceptIdCurrRectSurface = 0.0f; DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0; DragDropAcceptFrameCount = -1; DragDropHoldJustPressedId = 0; memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal)); ClipperTempDataStacked = 0; CurrentTable = NULL; TablesTempDataStacked = 0; CurrentTabBar = NULL; CurrentMultiSelect = NULL; MultiSelectTempDataStacked = 0; HoverItemDelayId = HoverItemDelayIdPreviousFrame = HoverItemUnlockedStationaryId = HoverWindowUnlockedStationaryId = 0; HoverItemDelayTimer = HoverItemDelayClearTimer = 0.0f; MouseCursor = ImGuiMouseCursor_Arrow; MouseStationaryTimer = 0.0f; TempInputId = 0; memset(&DataTypeZeroValue, 0, sizeof(DataTypeZeroValue)); BeginMenuDepth = BeginComboDepth = 0; ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_; ColorEditCurrentID = ColorEditSavedID = 0; ColorEditSavedHue = ColorEditSavedSat = 0.0f; ColorEditSavedColor = 0; WindowResizeRelativeMode = false; ScrollbarSeekMode = 0; ScrollbarClickDeltaToGrabCenter = 0.0f; SliderGrabClickOffset = 0.0f; SliderCurrentAccum = 0.0f; SliderCurrentAccumDirty = false; DragCurrentAccumDirty = false; DragCurrentAccum = 0.0f; DragSpeedDefaultRatio = 1.0f / 100.0f; DisabledAlphaBackup = 0.0f; DisabledStackSize = 0; LockMarkEdited = 0; TooltipOverrideCount = 0; PlatformImeData.InputPos = ImVec2(0.0f, 0.0f); PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission SettingsLoaded = false; SettingsDirtyTimer = 0.0f; HookIdNext = 0; memset(LocalizationTable, 0, sizeof(LocalizationTable)); LogEnabled = false; LogType = ImGuiLogType_None; LogNextPrefix = LogNextSuffix = NULL; LogFile = NULL; LogLinePosY = FLT_MAX; LogLineFirstItem = false; LogDepthRef = 0; LogDepthToExpand = LogDepthToExpandDefault = 2; DebugLogFlags = ImGuiDebugLogFlags_OutputToTTY; DebugLocateId = 0; DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None; DebugLogAutoDisableFrames = 0; DebugLocateFrames = 0; DebugBeginReturnValueCullDepth = -1; DebugItemPickerActive = false; DebugItemPickerMouseButton = ImGuiMouseButton_Left; DebugItemPickerBreakId = 0; DebugFlashStyleColorTime = 0.0f; DebugFlashStyleColorIdx = ImGuiCol_COUNT; // Same as DebugBreakClearData(). Those fields are scattered in their respective subsystem to stay in hot-data locations DebugBreakInWindow = 0; DebugBreakInTable = 0; DebugBreakInLocateId = false; DebugBreakKeyChord = ImGuiKey_Pause; DebugBreakInShortcutRouting = ImGuiKey_None; memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0; FramerateSecPerFrameAccum = 0.0f; WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1; memset(TempKeychordName, 0, sizeof(TempKeychordName)); } }; //----------------------------------------------------------------------------- // [SECTION] ImGuiWindowTempData, ImGuiWindow //----------------------------------------------------------------------------- // Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. // (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) // (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin) struct IMGUI_API ImGuiWindowTempData { // Layout ImVec2 CursorPos; // Current emitting position, in absolute coordinates. ImVec2 CursorPosPrevLine; ImVec2 CursorStartPos; // Initial position after Begin(), generally ~ window position + WindowPadding. ImVec2 CursorMaxPos; // Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame. ImVec2 IdealMaxPos; // Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame. ImVec2 CurrLineSize; ImVec2 PrevLineSize; float CurrLineTextBaseOffset; // Baseline offset (0.0f by default on a new line, generally == style.FramePadding.y when a framed item has been added). float PrevLineTextBaseOffset; bool IsSameLine; bool IsSetPos; ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) ImVec1 ColumnsOffset; // 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. ImVec1 GroupOffset; ImVec2 CursorStartPosLossyness;// Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensate and fix the most common use case of large scroll area. // Keyboard/Gamepad navigation ImGuiNavLayer NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1) short NavLayersActiveMask; // Which layers have been written to (result from previous frame) short NavLayersActiveMaskNext;// Which layers have been written to (accumulator for current frame) bool NavIsScrollPushableX; // Set when current work location may be scrolled horizontally when moving left / right. This is generally always true UNLESS within a column. bool NavHideHighlightOneFrame; bool NavWindowHasScrollY; // Set per window when scrolling can be used (== ScrollMax.y > 0.0f) // Miscellaneous bool MenuBarAppending; // FIXME: Remove this ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs. ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement int TreeDepth; // Current tree depth. ImU32 TreeHasStackDataDepthMask; // Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. ImVector<ImGuiWindow*> ChildWindows; ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state) ImGuiOldColumns* CurrentColumns; // Current columns set int CurrentTableIdx; // Current table index (into g.Tables) ImGuiLayoutType LayoutType; ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin() ImU32 ModalDimBgColor; // Local parameters stacks // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. float ItemWidth; // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). float TextWrapPos; // Current text wrap pos. ImVector<float> ItemWidthStack; // Store item widths to restore (attention: .back() is not == ItemWidth) ImVector<float> TextWrapPosStack; // Store text wrap pos to restore (attention: .back() is not == TextWrapPos) }; // Storage for one window struct IMGUI_API ImGuiWindow { ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). char* Name; // Window name, owned by the window. ImGuiID ID; // == ImHashStr(Name) ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ ImGuiChildFlags ChildFlags; // Set when window is a child window. See enum ImGuiChildFlags_ ImGuiViewportP* Viewport; // Always set in Begin(). Inactive windows may have a NULL value here if their viewport was discarded. ImVec2 Pos; // Position (always rounded-up to nearest pixel) ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) ImVec2 SizeFull; // Size when non collapsed ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. ImVec2 ContentSizeIdeal; ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). ImVec2 WindowPadding; // Window padding at the time of Begin(). float WindowRounding; // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. float WindowBorderSize; // Window border size at the time of Begin(). float TitleBarHeight, MenuBarHeight; // Note that those used to be function before 2024/05/28. If you have old code calling TitleBarHeight() you can change it to TitleBarHeight. float DecoOuterSizeX1, DecoOuterSizeY1; // Left/Up offsets. Sum of non-scrolling outer decorations (X1 generally == 0.0f. Y1 generally = TitleBarHeight + MenuBarHeight). Locked during Begin(). float DecoOuterSizeX2, DecoOuterSizeY2; // Right/Down offsets (X2 generally == ScrollbarSize.x, Y2 == ScrollbarSizes.y). float DecoInnerSizeX1, DecoInnerSizeY1; // Applied AFTER/OVER InnerRect. Specialized for Tables as they use specialized form of clipping and frozen rows/columns are inside InnerRect (and not part of regular decoration sizes). int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)! ImGuiID MoveId; // == window->GetID("#MOVE") ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window) ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) ImVec2 Scroll; ImVec2 ScrollMax; ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered ImVec2 ScrollTargetEdgeSnapDist; // 0.0f = no snapping, >0.0f snapping threshold ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar. bool ScrollbarX, ScrollbarY; // Are scrollbars visible? bool Active; // Set to true on Begin(), unless Collapsed bool WasActive; bool WriteAccessed; // Set to true when any widget access the current window bool Collapsed; // Set when collapsing window to become only title-bar bool WantCollapseToggle; bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed) bool SkipRefresh; // [EXPERIMENTAL] Reuse previous frame drawn contents, Begin() returns false. bool Appearing; // Set during the frame where the window is appearing (or re-appearing) bool Hidden; // Do not display (== HiddenFrames*** > 0) bool IsFallbackWindow; // Set on the "Debug##Default" window. bool IsExplicitChild; // Set when passed _ChildWindow, left to false by BeginDocked() bool HasCloseButton; // Set when the window has a close button (p_open != NULL) signed char ResizeBorderHovered; // Current border being hovered for resize (-1: none, otherwise 0-3) signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3) short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) short BeginCountPreviousFrame; // Number of Begin() during the previous frame short BeginOrderWithinParent; // Begin() order within immediate parent window, if we are a child window. Otherwise 0. short BeginOrderWithinContext; // Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. short FocusOrder; // Order within WindowsFocusOrder[], altered when windows are focused. ImS8 AutoFitFramesX, AutoFitFramesY; bool AutoFitOnlyGrows; ImGuiDir AutoPosLastDirection; ImS8 HiddenFramesCanSkipItems; // Hide the window for N frames ImS8 HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size ImS8 HiddenFramesForRenderOnly; // Hide the window until frame N at Render() time only ImS8 DisableInputsFrames; // Disable window interactions for N frames ImGuiCond SetWindowPosAllowFlags : 8; // store acceptable condition flags for SetNextWindowPos() use. ImGuiCond SetWindowSizeAllowFlags : 8; // store acceptable condition flags for SetNextWindowSize() use. ImGuiCond SetWindowCollapsedAllowFlags : 8; // store acceptable condition flags for SetNextWindowCollapsed() use. ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right. ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. // The best way to understand what those rectangles are is to use the 'Metrics->Tools->Show Windows Rectangles' viewer. // The main 'OuterRect', omitted as a field, is window->Rect(). ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window. ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar) ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect. ImRect WorkRect; // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). ImRect ParentWorkRect; // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack? ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back(). ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. ImVec2ih HitTestHoleSize; // Define an optional rectangular hole where mouse will pass-through the window. ImVec2ih HitTestHoleOffset; int LastFrameActive; // Last frame number the window was Active. float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there) float ItemWidthDefault; ImGuiStorage StateStorage; ImVector<ImGuiOldColumns> ColumnsStorage; float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale() int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer) ImDrawList DrawListInst; ImGuiWindow* ParentWindow; // If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise NULL. ImGuiWindow* ParentWindowInBeginStack; ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. ImGuiWindow* RootWindowPopupTree; // Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active. ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag. ImGuiWindow* ParentWindowForFocusRoute; // Set to manual link a window to its logical parent so that Shortcut() chain are honoerd (e.g. Tool linked to Document) ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1) ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space ImVec2 NavPreferredScoringPosRel[ImGuiNavLayer_COUNT]; // Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. ImGuiID NavRootFocusScopeId; // Focus Scope ID at the time of Begin() int MemoryDrawListIdxCapacity; // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy int MemoryDrawListVtxCapacity; bool MemoryCompacted; // Set when window extraneous data have been garbage collected public: ImGuiWindow(ImGuiContext* context, const char* name); ~ImGuiWindow(); ImGuiID GetID(const char* str, const char* str_end = NULL); ImGuiID GetID(const void* ptr); ImGuiID GetID(int n); ImGuiID GetIDFromPos(const ImVec2& p_abs); ImGuiID GetIDFromRectangle(const ImRect& r_abs); // We don't use g.FontSize because the window may be != g.CurrentWindow. ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); } float CalcFontSize() const { ImGuiContext& g = *Ctx; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight)); } ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight; return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight); } }; //----------------------------------------------------------------------------- // [SECTION] Tab bar, Tab item support //----------------------------------------------------------------------------- // Extend ImGuiTabBarFlags_ enum ImGuiTabBarFlagsPrivate_ { ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] ImGuiTabBarFlags_IsFocused = 1 << 21, ImGuiTabBarFlags_SaveSettings = 1 << 22, // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs }; // Extend ImGuiTabItemFlags_ enum ImGuiTabItemFlagsPrivate_ { ImGuiTabItemFlags_SectionMask_ = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing, ImGuiTabItemFlags_NoCloseButton = 1 << 20, // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) ImGuiTabItemFlags_Button = 1 << 21, // Used by TabItemButton, change the tab item behavior to mimic a button }; // Storage for one active tab item (sizeof() 40 bytes) struct ImGuiTabItem { ImGuiID ID; ImGuiTabItemFlags Flags; int LastFrameVisible; int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance float Offset; // Position relative to beginning of tab float Width; // Width currently displayed float ContentWidth; // Width of label, stored during BeginTabItem() call float RequestedWidth; // Width optionally requested by caller, -1.0f is unused ImS32 NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable ImS16 IndexDuringLayout; // Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. bool WantClose; // Marked as closed by SetTabItemClosed() ImGuiTabItem() { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } }; // Storage for a tab bar (sizeof() 152 bytes) struct IMGUI_API ImGuiTabBar { ImVector<ImGuiTabItem> Tabs; ImGuiTabBarFlags Flags; ImGuiID ID; // Zero for tab-bars used by docking ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview) int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; float CurrTabsContentsHeight; float PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar float WidthAllTabs; // Actual width of all tabs (locked during layout) float WidthAllTabsIdeal; // Ideal width if all tabs were visible and not clipped float ScrollingAnim; float ScrollingTarget; float ScrollingTargetDistToVisibility; float ScrollingSpeed; float ScrollingRectMinX; float ScrollingRectMaxX; float SeparatorMinX; float SeparatorMaxX; ImGuiID ReorderRequestTabId; ImS16 ReorderRequestOffset; ImS8 BeginCount; bool WantLayout; bool VisibleTabWasSubmitted; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame ImS16 TabsActiveCount; // Number of tabs submitted this frame. ImS16 LastTabItemIdx; // Index of last BeginTabItem() tab for use by EndTabItem() float ItemSpacingY; ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar() ImVec2 BackupCursorPos; ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer. ImGuiTabBar(); }; //----------------------------------------------------------------------------- // [SECTION] Table support //----------------------------------------------------------------------------- #define IM_COL32_DISABLE IM_COL32(0,0,0,1) // Special sentinel code which cannot be used as a regular color. #define IMGUI_TABLE_MAX_COLUMNS 512 // May be further lifted // Our current column maximum is 64 but we may raise that in the future. typedef ImS16 ImGuiTableColumnIdx; typedef ImU16 ImGuiTableDrawChannelIdx; // [Internal] sizeof() ~ 112 // We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. // We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping. // This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped". struct ImGuiTableColumn { ImGuiTableColumnFlags Flags; // Flags after some patching (not directly same as provided by user). See ImGuiTableColumnFlags_ float WidthGiven; // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be > WidthRequest to honor minimum width, may be < WidthRequest to honor shrinking columns down in tight space. float MinX; // Absolute positions float MaxX; float WidthRequest; // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from StretchWeight in TableUpdateLayout() float WidthAuto; // Automatic width float WidthMax; // Maximum width (FIXME: overwritten by each instance) float StretchWeight; // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially. float InitStretchWeightOrWidth; // Value passed to TableSetupColumn(). For Width it is a content width (_without padding_). ImRect ClipRect; // Clipping rectangle for the column ImGuiID UserID; // Optional, value passed to TableSetupColumn() float WorkMinX; // Contents region min ~(MinX + CellPaddingX + CellSpacingX1) == cursor start position when entering column float WorkMaxX; // Contents region max ~(MaxX - CellPaddingX - CellSpacingX2) float ItemWidth; // Current item width for the column, preserved across rows float ContentMaxXFrozen; // Contents maximum position for frozen rows (apart from headers), from which we can infer content width. float ContentMaxXUnfrozen; float ContentMaxXHeadersUsed; // Contents maximum position for headers rows (regardless of freezing). TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls float ContentMaxXHeadersIdeal; ImS16 NameOffset; // Offset into parent ColumnsNames[] ImGuiTableColumnIdx DisplayOrder; // Index within Table's IndexToDisplayOrder[] (column may be reordered by users) ImGuiTableColumnIdx IndexWithinEnabledSet; // Index within enabled/visible set (<= IndexToDisplayOrder) ImGuiTableColumnIdx PrevEnabledColumn; // Index of prev enabled/visible column within Columns[], -1 if first enabled/visible column ImGuiTableColumnIdx NextEnabledColumn; // Index of next enabled/visible column within Columns[], -1 if last enabled/visible column ImGuiTableColumnIdx SortOrder; // Index of this column within sort specs, -1 if not sorting on this column, 0 for single-sort, may be >0 on multi-sort ImGuiTableDrawChannelIdx DrawChannelCurrent; // Index within DrawSplitter.Channels[] ImGuiTableDrawChannelIdx DrawChannelFrozen; // Draw channels for frozen rows (often headers) ImGuiTableDrawChannelIdx DrawChannelUnfrozen; // Draw channels for unfrozen rows bool IsEnabled; // IsUserEnabled && (Flags & ImGuiTableColumnFlags_Disabled) == 0 bool IsUserEnabled; // Is the column not marked Hidden by the user? (unrelated to being off view, e.g. clipped by scrolling). bool IsUserEnabledNextFrame; bool IsVisibleX; // Is actually in view (e.g. overlapping the host window clipping rectangle, not scrolled). bool IsVisibleY; bool IsRequestOutput; // Return value for TableSetColumnIndex() / TableNextColumn(): whether we request user to output contents or not. bool IsSkipItems; // Do we want item submissions to this column to be completely ignored (no layout will happen). bool IsPreserveWidthAuto; ImS8 NavLayerCurrent; // ImGuiNavLayer in 1 byte ImU8 AutoFitQueue; // Queue of 8 values for the next 8 frames to request auto-fit ImU8 CannotSkipItemsQueue; // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem ImU8 SortDirection : 2; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending ImU8 SortDirectionsAvailCount : 2; // Number of available sort directions (0 to 3) ImU8 SortDirectionsAvailMask : 4; // Mask of available sort directions (1-bit each) ImU8 SortDirectionsAvailList; // Ordered list of available sort directions (2-bits each, total 8-bits) ImGuiTableColumn() { memset(this, 0, sizeof(*this)); StretchWeight = WidthRequest = -1.0f; NameOffset = -1; DisplayOrder = IndexWithinEnabledSet = -1; PrevEnabledColumn = NextEnabledColumn = -1; SortOrder = -1; SortDirection = ImGuiSortDirection_None; DrawChannelCurrent = DrawChannelFrozen = DrawChannelUnfrozen = (ImU8)-1; } }; // Transient cell data stored per row. // sizeof() ~ 6 bytes struct ImGuiTableCellData { ImU32 BgColor; // Actual color ImGuiTableColumnIdx Column; // Column number }; // Parameters for TableAngledHeadersRowEx() // This may end up being refactored for more general purpose. // sizeof() ~ 12 bytes struct ImGuiTableHeaderData { ImGuiTableColumnIdx Index; // Column index ImU32 TextColor; ImU32 BgColor0; ImU32 BgColor1; }; // Per-instance data that needs preserving across frames (seemingly most others do not need to be preserved aside from debug needs. Does that means they could be moved to ImGuiTableTempData?) // sizeof() ~ 24 bytes struct ImGuiTableInstanceData { ImGuiID TableInstanceID; float LastOuterHeight; // Outer height from last frame float LastTopHeadersRowHeight; // Height of first consecutive header rows from last frame (FIXME: this is used assuming consecutive headers are in same frozen set) float LastFrozenHeight; // Height of frozen section from last frame int HoveredRowLast; // Index of row which was hovered last frame. int HoveredRowNext; // Index of row hovered this frame, set after encountering it. ImGuiTableInstanceData() { TableInstanceID = 0; LastOuterHeight = LastTopHeadersRowHeight = LastFrozenHeight = 0.0f; HoveredRowLast = HoveredRowNext = -1; } }; // sizeof() ~ 592 bytes + heap allocs described in TableBeginInitMemory() struct IMGUI_API ImGuiTable { ImGuiID ID; ImGuiTableFlags Flags; void* RawData; // Single allocation to hold Columns[], DisplayOrderToIndex[] and RowCellData[] ImGuiTableTempData* TempData; // Transient data while table is active. Point within g.CurrentTableStack[] ImSpan<ImGuiTableColumn> Columns; // Point within RawData[] ImSpan<ImGuiTableColumnIdx> DisplayOrderToIndex; // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1) ImSpan<ImGuiTableCellData> RowCellData; // Point within RawData[]. Store cells background requests for current row. ImBitArrayPtr EnabledMaskByDisplayOrder; // Column DisplayOrder -> IsEnabled map ImBitArrayPtr EnabledMaskByIndex; // Column Index -> IsEnabled map (== not hidden by user/api) in a format adequate for iterating column without touching cold data ImBitArrayPtr VisibleMaskByIndex; // Column Index -> IsVisibleX|IsVisibleY map (== not hidden by user/api && not hidden by scrolling/cliprect) ImGuiTableFlags SettingsLoadedFlags; // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order) int SettingsOffset; // Offset in g.SettingsTables int LastFrameActive; int ColumnsCount; // Number of columns declared in BeginTable() int CurrentRow; int CurrentColumn; ImS16 InstanceCurrent; // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple table with same ID look are multiple tables, they are just synched. ImS16 InstanceInteracted; // Mark which instance (generally 0) of the same ID is being interacted with float RowPosY1; float RowPosY2; float RowMinHeight; // Height submitted to TableNextRow() float RowCellPaddingY; // Top and bottom padding. Reloaded during row change. float RowTextBaseline; float RowIndentOffsetX; ImGuiTableRowFlags RowFlags : 16; // Current row flags, see ImGuiTableRowFlags_ ImGuiTableRowFlags LastRowFlags : 16; int RowBgColorCounter; // Counter for alternating background colors (can be fast-forwarded by e.g clipper), not same as CurrentRow because header rows typically don't increase this. ImU32 RowBgColor[2]; // Background color override for current row. ImU32 BorderColorStrong; ImU32 BorderColorLight; float BorderX1; float BorderX2; float HostIndentX; float MinColumnWidth; float OuterPaddingX; float CellPaddingX; // Padding from each borders. Locked in BeginTable()/Layout. float CellSpacingX1; // Spacing between non-bordered cells. Locked in BeginTable()/Layout. float CellSpacingX2; float InnerWidth; // User value passed to BeginTable(), see comments at the top of BeginTable() for details. float ColumnsGivenWidth; // Sum of current column width float ColumnsAutoFitWidth; // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window float ColumnsStretchSumWeights; // Sum of weight of all enabled stretching columns float ResizedColumnNextWidth; float ResizeLockMinContentsX2; // Lock minimum contents width while resizing down in order to not create feedback loops. But we allow growing the table. float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. float AngledHeadersHeight; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() float AngledHeadersSlope; // Set by TableAngledHeadersRow(), used in TableUpdateLayout() ImRect OuterRect; // Note: for non-scrolling table, OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable(). ImRect InnerRect; // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is ImRect WorkRect; ImRect InnerClipRect; ImRect BgClipRect; // We use this to cpu-clip cell background color fill, evolve during the frame as we cross frozen rows boundaries ImRect Bg0ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG0/1 channel. This tends to be == OuterWindow->ClipRect at BeginTable() because output in BG0/BG1 is cpu-clipped ImRect Bg2ClipRectForDrawCmd; // Actual ImDrawCmd clip rect for BG2 channel. This tends to be a correct, tight-fit, because output to BG2 are done by widgets relying on regular ClipRect. ImRect HostClipRect; // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window. ImRect HostBackupInnerClipRect; // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground() ImGuiWindow* OuterWindow; // Parent window for the table ImGuiWindow* InnerWindow; // Window holding the table data (== OuterWindow or a child window) ImGuiTextBuffer ColumnsNames; // Contiguous buffer holding columns names ImDrawListSplitter* DrawSplitter; // Shortcut to TempData->DrawSplitter while in table. Isolate draw commands per columns to avoid switching clip rect constantly ImGuiTableInstanceData InstanceDataFirst; ImVector<ImGuiTableInstanceData> InstanceDataExtra; // FIXME-OPT: Using a small-vector pattern would be good. ImGuiTableColumnSortSpecs SortSpecsSingle; ImVector<ImGuiTableColumnSortSpecs> SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() ImGuiTableColumnIdx SortSpecsCount; ImGuiTableColumnIdx ColumnsEnabledCount; // Number of enabled columns (<= ColumnsCount) ImGuiTableColumnIdx ColumnsEnabledFixedCount; // Number of enabled columns using fixed width (<= ColumnsCount) ImGuiTableColumnIdx DeclColumnsCount; // Count calls to TableSetupColumn() ImGuiTableColumnIdx AngledHeadersCount; // Count columns with angled headers ImGuiTableColumnIdx HoveredColumnBody; // Index of column whose visible region is being hovered. Important: == ColumnsCount when hovering empty region after the right-most column! ImGuiTableColumnIdx HoveredColumnBorder; // Index of column whose right-border is being hovered (for resizing). ImGuiTableColumnIdx HighlightColumnHeader; // Index of column which should be highlighted. ImGuiTableColumnIdx AutoFitSingleColumn; // Index of single column requesting auto-fit. ImGuiTableColumnIdx ResizedColumn; // Index of column being resized. Reset when InstanceCurrent==0. ImGuiTableColumnIdx LastResizedColumn; // Index of column being resized from previous frame. ImGuiTableColumnIdx HeldHeaderColumn; // Index of column header being held. ImGuiTableColumnIdx ReorderColumn; // Index of column being reordered. (not cleared) ImGuiTableColumnIdx ReorderColumnDir; // -1 or +1 ImGuiTableColumnIdx LeftMostEnabledColumn; // Index of left-most non-hidden column. ImGuiTableColumnIdx RightMostEnabledColumn; // Index of right-most non-hidden column. ImGuiTableColumnIdx LeftMostStretchedColumn; // Index of left-most stretched column. ImGuiTableColumnIdx RightMostStretchedColumn; // Index of right-most stretched column. ImGuiTableColumnIdx ContextPopupColumn; // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot ImGuiTableColumnIdx FreezeRowsRequest; // Requested frozen rows count ImGuiTableColumnIdx FreezeRowsCount; // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset) ImGuiTableColumnIdx FreezeColumnsRequest; // Requested frozen columns count ImGuiTableColumnIdx FreezeColumnsCount; // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset) ImGuiTableColumnIdx RowCellDataCurrent; // Index of current RowCellData[] entry in current row ImGuiTableDrawChannelIdx DummyDrawChannel; // Redirect non-visible columns here. ImGuiTableDrawChannelIdx Bg2DrawChannelCurrent; // For Selectable() and other widgets drawing across columns after the freezing line. Index within DrawSplitter.Channels[] ImGuiTableDrawChannelIdx Bg2DrawChannelUnfrozen; bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). bool IsInitializing; bool IsSortSpecsDirty; bool IsUsingHeaders; // Set when the first row had the ImGuiTableRowFlags_Headers flag. bool IsContextPopupOpen; // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted). bool DisableDefaultContextMenu; // Disable default context menu contents. You may submit your own using TableBeginContextMenuPopup()/EndPopup() bool IsSettingsRequestLoad; bool IsSettingsDirty; // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data. bool IsDefaultDisplayOrder; // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1) bool IsResetAllRequest; bool IsResetDisplayOrderRequest; bool IsUnfrozenRows; // Set when we got past the frozen row. bool IsDefaultSizingPolicy; // Set if user didn't explicitly set a sizing policy in BeginTable() bool IsActiveIdAliveBeforeTable; bool IsActiveIdInTable; bool HasScrollbarYCurr; // Whether ANY instance of this table had a vertical scrollbar during the current frame. bool HasScrollbarYPrev; // Whether ANY instance of this table had a vertical scrollbar during the previous. bool MemoryCompacted; bool HostSkipItems; // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis ImGuiTable() { memset(this, 0, sizeof(*this)); LastFrameActive = -1; } ~ImGuiTable() { IM_FREE(RawData); } }; // Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table). // - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure. // - We also leave out of this structure data that tend to be particularly useful for debugging/metrics. // FIXME-TABLE: more transient data could be stored in a stacked ImGuiTableTempData: e.g. SortSpecs. // sizeof() ~ 136 bytes. struct IMGUI_API ImGuiTableTempData { int TableIndex; // Index in g.Tables.Buf[] pool float LastTimeActive; // Last timestamp this structure was used float AngledHeadersExtraWidth; // Used in EndTable() ImVector<ImGuiTableHeaderData> AngledHeadersRequests; // Used in TableAngledHeadersRow() ImVec2 UserOuterSize; // outer_size.x passed to BeginTable() ImDrawListSplitter DrawSplitter; ImRect HostBackupWorkRect; // Backup of InnerWindow->WorkRect at the end of BeginTable() ImRect HostBackupParentWorkRect; // Backup of InnerWindow->ParentWorkRect at the end of BeginTable() ImVec2 HostBackupPrevLineSize; // Backup of InnerWindow->DC.PrevLineSize at the end of BeginTable() ImVec2 HostBackupCurrLineSize; // Backup of InnerWindow->DC.CurrLineSize at the end of BeginTable() ImVec2 HostBackupCursorMaxPos; // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable() ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable() float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable() int HostBackupItemWidthStackSize;//Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable() ImGuiTableTempData() { memset(this, 0, sizeof(*this)); LastTimeActive = -1.0f; } }; // sizeof() ~ 12 struct ImGuiTableColumnSettings { float WidthOrWeight; ImGuiID UserID; ImGuiTableColumnIdx Index; ImGuiTableColumnIdx DisplayOrder; ImGuiTableColumnIdx SortOrder; ImU8 SortDirection : 2; ImU8 IsEnabled : 1; // "Visible" in ini file ImU8 IsStretch : 1; ImGuiTableColumnSettings() { WidthOrWeight = 0.0f; UserID = 0; Index = -1; DisplayOrder = SortOrder = -1; SortDirection = ImGuiSortDirection_None; IsEnabled = 1; IsStretch = 0; } }; // This is designed to be stored in a single ImChunkStream (1 header followed by N ImGuiTableColumnSettings, etc.) struct ImGuiTableSettings { ImGuiID ID; // Set to 0 to invalidate/delete the setting ImGuiTableFlags SaveFlags; // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..) float RefScale; // Reference scale to be able to rescale columns on font/dpi changes. ImGuiTableColumnIdx ColumnsCount; ImGuiTableColumnIdx ColumnsCountMax; // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher bool WantApply; // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) ImGuiTableSettings() { memset(this, 0, sizeof(*this)); } ImGuiTableColumnSettings* GetColumnSettings() { return (ImGuiTableColumnSettings*)(this + 1); } }; //----------------------------------------------------------------------------- // [SECTION] ImGui internal API // No guarantee of forward compatibility here! //----------------------------------------------------------------------------- namespace ImGui { // Windows // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) // If this ever crashes because g.CurrentWindow is NULL, it means that either: // - ImGui::NewFrame() has never been called, which is illegal. // - You are calling ImGui functions after ImGui::EndFrame()/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->WriteAccessed = true; return g.CurrentWindow; } IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); IMGUI_API ImGuiWindow* FindWindowByName(const char* name); IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window); IMGUI_API void UpdateWindowSkipRefresh(ImGuiWindow* window); IMGUI_API ImVec2 CalcWindowNextAutoFitSize(ImGuiWindow* window); IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy); IMGUI_API bool IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent); IMGUI_API bool IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below); IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window); IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0); IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0); IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0); IMGUI_API void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size); IMGUI_API void SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window); inline void SetWindowParentWindowForFocusRoute(ImGuiWindow* window, ImGuiWindow* parent_window) { window->ParentWindowForFocusRoute = parent_window; } inline ImRect WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); } inline ImRect WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); } inline ImVec2 WindowPosAbsToRel(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x - off.x, p.y - off.y); } inline ImVec2 WindowPosRelToAbs(ImGuiWindow* window, const ImVec2& p) { ImVec2 off = window->DC.CursorStartPos; return ImVec2(p.x + off.x, p.y + off.y); } // Windows: Display Order and Focus Order IMGUI_API void FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags = 0); IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags); IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window); IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window); IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window); IMGUI_API void BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* above_window); IMGUI_API int FindWindowDisplayIndex(ImGuiWindow* window); IMGUI_API ImGuiWindow* FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* window); // Windows: Idle, Refresh Policies [EXPERIMENTAL] IMGUI_API void SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags); // Fonts, drawing IMGUI_API void SetCurrentFont(ImFont* font); inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. IMGUI_API ImDrawList* GetBackgroundDrawList(ImGuiViewport* viewport); // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents. IMGUI_API ImDrawList* GetForegroundDrawList(ImGuiViewport* viewport); // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. IMGUI_API void AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector<ImDrawList*>* out_list, ImDrawList* draw_list); // Init IMGUI_API void Initialize(); IMGUI_API void Shutdown(); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext(). // NewFrame IMGUI_API void UpdateInputEvents(bool trickle_fast_inputs); IMGUI_API void UpdateHoveredWindowAndCaptureFlags(); IMGUI_API void FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window); IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window); IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); // Generic context hooks IMGUI_API ImGuiID AddContextHook(ImGuiContext* context, const ImGuiContextHook* hook); IMGUI_API void RemoveContextHook(ImGuiContext* context, ImGuiID hook_to_remove); IMGUI_API void CallContextHooks(ImGuiContext* context, ImGuiContextHookType type); // Viewports IMGUI_API void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport); // Settings IMGUI_API void MarkIniSettingsDirty(); IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window); IMGUI_API void ClearIniSettings(); IMGUI_API void AddSettingsHandler(const ImGuiSettingsHandler* handler); IMGUI_API void RemoveSettingsHandler(const char* type_name); IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name); // Settings - Windows IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name); IMGUI_API ImGuiWindowSettings* FindWindowSettingsByID(ImGuiID id); IMGUI_API ImGuiWindowSettings* FindWindowSettingsByWindow(ImGuiWindow* window); IMGUI_API void ClearWindowSettings(const char* name); // Localization IMGUI_API void LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count); inline const char* LocalizeGetMsg(ImGuiLocKey key) { ImGuiContext& g = *GImGui; const char* msg = g.LocalizationTable[key]; return msg ? msg : "*Missing Text*"; } // Scrolling IMGUI_API void SetScrollX(ImGuiWindow* window, float scroll_x); IMGUI_API void SetScrollY(ImGuiWindow* window, float scroll_y); IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio); IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio); // Early work-in-progress API (ScrollToItem() will become public) IMGUI_API void ScrollToItem(ImGuiScrollFlags flags = 0); IMGUI_API void ScrollToRect(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0); IMGUI_API ImVec2 ScrollToRectEx(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0); //#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline void ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& rect) { ScrollToRect(window, rect, ImGuiScrollFlags_KeepVisibleEdgeY); } //#endif // Basic Accessors inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; } inline ImGuiItemFlags GetItemFlags() { ImGuiContext& g = *GImGui; return g.LastItemData.InFlags; } inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window); IMGUI_API void ClearActiveID(); IMGUI_API ImGuiID GetHoveredID(); IMGUI_API void SetHoveredID(ImGuiID id); IMGUI_API void KeepAliveID(ImGuiID id); IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function. IMGUI_API void PushOverrideID(ImGuiID id); // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes) IMGUI_API ImGuiID GetIDWithSeed(const char* str_id_begin, const char* str_id_end, ImGuiID seed); IMGUI_API ImGuiID GetIDWithSeed(int n, ImGuiID seed); // Basic Helpers for widget code IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f); inline void ItemSize(const ImRect& bb, float text_baseline_y = -1.0f) { ItemSize(bb.GetSize(), text_baseline_y); } // FIXME: This is a misleading API since we expect CursorPos to be bb.Min. IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL, ImGuiItemFlags extra_flags = 0); IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags); IMGUI_API bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags = 0); IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id); IMGUI_API void SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect); IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h); IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); IMGUI_API void PushMultiItemsWidths(int components, float width_full); IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess); // Parameter stacks (shared) IMGUI_API const ImGuiDataVarInfo* GetStyleVarInfo(ImGuiStyleVar idx); IMGUI_API void BeginDisabledOverrideReenable(); IMGUI_API void EndDisabledOverrideReenable(); // Logging/Capture IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name. IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL); IMGUI_API void LogSetNextTextDecoration(const char* prefix, const char* suffix); // Childs IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags); // Popups, Modals IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags); IMGUI_API void OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None); IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup); IMGUI_API void ClosePopupsExceptModals(); IMGUI_API bool IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags); IMGUI_API ImRect GetPopupAllowedExtentRect(ImGuiWindow* window); IMGUI_API ImGuiWindow* GetTopMostPopupModal(); IMGUI_API ImGuiWindow* GetTopMostAndVisiblePopupModal(); IMGUI_API ImGuiWindow* FindBlockingModal(ImGuiWindow* window); IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window); IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy); // Tooltips IMGUI_API bool BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags); IMGUI_API bool BeginTooltipHidden(); // Menus IMGUI_API bool BeginViewportSideBar(const char* name, ImGuiViewport* viewport, ImGuiDir dir, float size, ImGuiWindowFlags window_flags); IMGUI_API bool BeginMenuEx(const char* label, const char* icon, bool enabled = true); IMGUI_API bool MenuItemEx(const char* label, const char* icon, const char* shortcut = NULL, bool selected = false, bool enabled = true); // Combos IMGUI_API bool BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags); IMGUI_API bool BeginComboPreview(); IMGUI_API void EndComboPreview(); // Gamepad/Keyboard Navigation IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit); IMGUI_API void NavInitRequestApplyResult(); IMGUI_API bool NavMoveRequestButNoResultYet(); IMGUI_API void NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags); IMGUI_API void NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result); IMGUI_API void NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data); IMGUI_API void NavMoveRequestCancel(); IMGUI_API void NavMoveRequestApplyResult(); IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags); IMGUI_API void NavHighlightActivated(ImGuiID id); IMGUI_API void NavClearPreferredPosForAxis(ImGuiAxis axis); IMGUI_API void NavRestoreHighlightAfterMove(); IMGUI_API void NavUpdateCurrentWindowIsScrollPushableX(); IMGUI_API void SetNavWindow(ImGuiWindow* window); IMGUI_API void SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel); IMGUI_API void SetNavFocusScope(ImGuiID focus_scope_id); // Focus/Activation // This should be part of a larger set of API: FocusItem(offset = -1), FocusItemByID(id), ActivateItem(offset = -1), ActivateItemByID(id) etc. which are // much harder to design and implement than expected. I have a couple of private branches on this matter but it's not simple. For now implementing the easy ones. IMGUI_API void FocusItem(); // Focus last item (no selection/activation). IMGUI_API void ActivateItemByID(ImGuiID id); // Activate an item by ID (button, checkbox, tree node etc.). Activation is queued and processed on the next frame when the item is encountered again. // Inputs // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. inline bool IsNamedKey(ImGuiKey key) { return key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END; } inline bool IsNamedKeyOrMod(ImGuiKey key) { return (key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END) || key == ImGuiMod_Ctrl || key == ImGuiMod_Shift || key == ImGuiMod_Alt || key == ImGuiMod_Super; } inline bool IsLegacyKey(ImGuiKey key) { return key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_LegacyNativeKey_END; } inline bool IsKeyboardKey(ImGuiKey key) { return key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END; } inline bool IsGamepadKey(ImGuiKey key) { return key >= ImGuiKey_Gamepad_BEGIN && key < ImGuiKey_Gamepad_END; } inline bool IsMouseKey(ImGuiKey key) { return key >= ImGuiKey_Mouse_BEGIN && key < ImGuiKey_Mouse_END; } inline bool IsAliasKey(ImGuiKey key) { return key >= ImGuiKey_Aliases_BEGIN && key < ImGuiKey_Aliases_END; } inline bool IsLRModKey(ImGuiKey key) { return key >= ImGuiKey_LeftCtrl && key <= ImGuiKey_RightSuper; } ImGuiKeyChord FixupKeyChord(ImGuiKeyChord key_chord); inline ImGuiKey ConvertSingleModFlagToKey(ImGuiKey key) { if (key == ImGuiMod_Ctrl) return ImGuiKey_ReservedForModCtrl; if (key == ImGuiMod_Shift) return ImGuiKey_ReservedForModShift; if (key == ImGuiMod_Alt) return ImGuiKey_ReservedForModAlt; if (key == ImGuiMod_Super) return ImGuiKey_ReservedForModSuper; return key; } IMGUI_API ImGuiKeyData* GetKeyData(ImGuiContext* ctx, ImGuiKey key); inline ImGuiKeyData* GetKeyData(ImGuiKey key) { ImGuiContext& g = *GImGui; return GetKeyData(&g, key); } IMGUI_API const char* GetKeyChordName(ImGuiKeyChord key_chord); inline ImGuiKey MouseButtonToKey(ImGuiMouseButton button) { IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT); return (ImGuiKey)(ImGuiKey_MouseLeft + button); } IMGUI_API bool IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold = -1.0f); IMGUI_API ImVec2 GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down); IMGUI_API float GetNavTweakPressedAmount(ImGuiAxis axis); IMGUI_API int CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate); IMGUI_API void GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate); IMGUI_API void TeleportMousePos(const ImVec2& pos); IMGUI_API void SetActiveIdUsingAllKeyboardKeys(); inline bool IsActiveIdUsingNavDir(ImGuiDir dir) { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavDirMask & (1 << dir)) != 0; } // [EXPERIMENTAL] Low-Level: Key/Input Ownership // - The idea is that instead of "eating" a given input, we can link to an owner id. // - Ownership is most often claimed as a result of reacting to a press/down event (but occasionally may be claimed ahead). // - Input queries can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. // - Legacy input queries (without specifying an owner or _Any or _None) are equivalent to using ImGuiKeyOwner_Any (== 0). // - Input ownership is automatically released on the frame after a key is released. Therefore: // - for ownership registration happening as a result of a down/press event, the SetKeyOwner() call may be done once (common case). // - for ownership registration happening ahead of a down/press event, the SetKeyOwner() call needs to be made every frame (happens if e.g. claiming ownership on hover). // - SetItemKeyOwner() is a shortcut for common simple case. A custom widget will probably want to call SetKeyOwner() multiple times directly based on its interaction state. // - This is marked experimental because not all widgets are fully honoring the Set/Test idioms. We will need to move forward step by step. // Please open a GitHub Issue to submit your usage scenario or if there's a use case you need solved. IMGUI_API ImGuiID GetKeyOwner(ImGuiKey key); IMGUI_API void SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0); IMGUI_API void SetKeyOwnersForKeyChord(ImGuiKeyChord key, ImGuiID owner_id, ImGuiInputFlags flags = 0); IMGUI_API void SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags); // Set key owner to last item if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. IMGUI_API bool TestKeyOwner(ImGuiKey key, ImGuiID owner_id); // Test that key is either not owned, either owned by 'owner_id' inline ImGuiKeyOwnerData* GetKeyOwnerData(ImGuiContext* ctx, ImGuiKey key) { if (key & ImGuiMod_Mask_) key = ConvertSingleModFlagToKey(key); IM_ASSERT(IsNamedKey(key)); return &ctx->KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN]; } // [EXPERIMENTAL] High-Level: Input Access functions w/ support for Key/Input Ownership // - Important: legacy IsKeyPressed(ImGuiKey, bool repeat=true) _DEFAULTS_ to repeat, new IsKeyPressed() requires _EXPLICIT_ ImGuiInputFlags_Repeat flag. // - Expected to be later promoted to public API, the prototypes are designed to replace existing ones (since owner_id can default to Any == 0) // - Specifying a value for 'ImGuiID owner' will test that EITHER the key is NOT owned (UNLESS locked), EITHER the key is owned by 'owner'. // Legacy functions use ImGuiKeyOwner_Any meaning that they typically ignore ownership, unless a call to SetKeyOwner() explicitly used ImGuiInputFlags_LockThisFrame or ImGuiInputFlags_LockUntilRelease. // - Binding generators may want to ignore those for now, or suffix them with Ex() until we decide if this gets moved into public API. IMGUI_API bool IsKeyDown(ImGuiKey key, ImGuiID owner_id); IMGUI_API bool IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0); // Important: when transitioning from old to new IsKeyPressed(): old API has "bool repeat = true", so would default to repeat. New API requiress explicit ImGuiInputFlags_Repeat. IMGUI_API bool IsKeyReleased(ImGuiKey key, ImGuiID owner_id); IMGUI_API bool IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id = 0); IMGUI_API bool IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id); IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0); IMGUI_API bool IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id); IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id); // Shortcut Testing & Routing // - Set Shortcut() and SetNextItemShortcut() in imgui.h // - When a policy (except for ImGuiInputFlags_RouteAlways *) is set, Shortcut() will register itself with SetShortcutRouting(), // allowing the system to decide where to route the input among other route-aware calls. // (* using ImGuiInputFlags_RouteAlways is roughly equivalent to calling IsKeyChordPressed(key) and bypassing route registration and check) // - When using one of the routing option: // - The default route is ImGuiInputFlags_RouteFocused (accept inputs if window is in focus stack. Deep-most focused window takes inputs. ActiveId takes inputs over deep-most focused window.) // - Routes are requested given a chord (key + modifiers) and a routing policy. // - Routes are resolved during NewFrame(): if keyboard modifiers are matching current ones: SetKeyOwner() is called + route is granted for the frame. // - Each route may be granted to a single owner. When multiple requests are made we have policies to select the winning route (e.g. deep most window). // - Multiple read sites may use the same owner id can all access the granted route. // - When owner_id is 0 we use the current Focus Scope ID as a owner ID in order to identify our location. // - You can chain two unrelated windows in the focus stack using SetWindowParentWindowForFocusRoute() // e.g. if you have a tool window associated to a document, and you want document shortcuts to run when the tool is focused. IMGUI_API bool Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id); IMGUI_API bool SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id); // owner_id needs to be explicit and cannot be 0 IMGUI_API bool TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id); IMGUI_API ImGuiKeyRoutingData* GetShortcutRoutingData(ImGuiKeyChord key_chord); // [EXPERIMENTAL] Focus Scope // This is generally used to identify a unique input location (for e.g. a selection set) // There is one per window (automatically set in Begin), but: // - Selection patterns generally need to react (e.g. clear a selection) when landing on one item of the set. // So in order to identify a set multiple lists in same window may each need a focus scope. // If you imagine an hypothetical BeginSelectionGroup()/EndSelectionGroup() api, it would likely call PushFocusScope()/EndFocusScope() // - Shortcut routing also use focus scope as a default location identifier if an owner is not provided. // We don't use the ID Stack for this as it is common to want them separate. IMGUI_API void PushFocusScope(ImGuiID id); IMGUI_API void PopFocusScope(); inline ImGuiID GetCurrentFocusScope() { ImGuiContext& g = *GImGui; return g.CurrentFocusScopeId; } // Focus scope we are outputting into, set by PushFocusScope() // Drag and Drop IMGUI_API bool IsDragDropActive(); IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id); IMGUI_API void ClearDragDrop(); IMGUI_API bool IsDragDropPayloadBeingAccepted(); IMGUI_API void RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect); // Typing-Select API IMGUI_API ImGuiTypingSelectRequest* GetTypingSelectRequest(ImGuiTypingSelectFlags flags = ImGuiTypingSelectFlags_None); IMGUI_API int TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); IMGUI_API int TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx); IMGUI_API int TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data); // Box-Select API IMGUI_API bool BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags); IMGUI_API void EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags); // Multi-Select API IMGUI_API void MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags); IMGUI_API void MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed); IMGUI_API void MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected); IMGUI_API void MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item); inline ImGuiBoxSelectState* GetBoxSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.BoxSelectState.ID == id && g.BoxSelectState.IsActive) ? &g.BoxSelectState : NULL; } inline ImGuiMultiSelectState* GetMultiSelectState(ImGuiID id) { ImGuiContext& g = *GImGui; return g.MultiSelectStorage.GetByKey(id); } // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API) IMGUI_API void SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect); IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns(). IMGUI_API void EndColumns(); // close columns IMGUI_API void PushColumnClipRect(int column_index); IMGUI_API void PushColumnsBackground(); IMGUI_API void PopColumnsBackground(); IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count); IMGUI_API ImGuiOldColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id); IMGUI_API float GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm); IMGUI_API float GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset); // Tables: Candidates for public API IMGUI_API void TableOpenContextMenu(int column_n = -1); IMGUI_API void TableSetColumnWidth(int column_n, float width); IMGUI_API void TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs); IMGUI_API int TableGetHoveredRow(); // Retrieve *PREVIOUS FRAME* hovered row. This difference with TableGetHoveredColumn() is the reason why this is not public yet. IMGUI_API float TableGetHeaderRowHeight(); IMGUI_API float TableGetHeaderAngledMaxLabelWidth(); IMGUI_API void TablePushBackgroundChannel(); IMGUI_API void TablePopBackgroundChannel(); IMGUI_API void TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count); // Tables: Internals inline ImGuiTable* GetCurrentTable() { ImGuiContext& g = *GImGui; return g.CurrentTable; } IMGUI_API ImGuiTable* TableFindByID(ImGuiID id); IMGUI_API bool BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f); IMGUI_API void TableBeginInitMemory(ImGuiTable* table, int columns_count); IMGUI_API void TableBeginApplyRequests(ImGuiTable* table); IMGUI_API void TableSetupDrawChannels(ImGuiTable* table); IMGUI_API void TableUpdateLayout(ImGuiTable* table); IMGUI_API void TableUpdateBorders(ImGuiTable* table); IMGUI_API void TableUpdateColumnsWeightFromWidth(ImGuiTable* table); IMGUI_API void TableDrawBorders(ImGuiTable* table); IMGUI_API void TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags_for_section_to_display); IMGUI_API bool TableBeginContextMenuPopup(ImGuiTable* table); IMGUI_API void TableMergeDrawChannels(ImGuiTable* table); inline ImGuiTableInstanceData* TableGetInstanceData(ImGuiTable* table, int instance_no) { if (instance_no == 0) return &table->InstanceDataFirst; return &table->InstanceDataExtra[instance_no - 1]; } inline ImGuiID TableGetInstanceID(ImGuiTable* table, int instance_no) { return TableGetInstanceData(table, instance_no)->TableInstanceID; } IMGUI_API void TableSortSpecsSanitize(ImGuiTable* table); IMGUI_API void TableSortSpecsBuild(ImGuiTable* table); IMGUI_API ImGuiSortDirection TableGetColumnNextSortDirection(ImGuiTableColumn* column); IMGUI_API void TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column); IMGUI_API float TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column); IMGUI_API void TableBeginRow(ImGuiTable* table); IMGUI_API void TableEndRow(ImGuiTable* table); IMGUI_API void TableBeginCell(ImGuiTable* table, int column_n); IMGUI_API void TableEndCell(ImGuiTable* table); IMGUI_API ImRect TableGetCellBgRect(const ImGuiTable* table, int column_n); IMGUI_API const char* TableGetColumnName(const ImGuiTable* table, int column_n); IMGUI_API ImGuiID TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no = 0); IMGUI_API float TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n); IMGUI_API void TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n); IMGUI_API void TableSetColumnWidthAutoAll(ImGuiTable* table); IMGUI_API void TableRemove(ImGuiTable* table); IMGUI_API void TableGcCompactTransientBuffers(ImGuiTable* table); IMGUI_API void TableGcCompactTransientBuffers(ImGuiTableTempData* table); IMGUI_API void TableGcCompactSettings(); // Tables: Settings IMGUI_API void TableLoadSettings(ImGuiTable* table); IMGUI_API void TableSaveSettings(ImGuiTable* table); IMGUI_API void TableResetSettings(ImGuiTable* table); IMGUI_API ImGuiTableSettings* TableGetBoundSettings(ImGuiTable* table); IMGUI_API void TableSettingsAddSettingsHandler(); IMGUI_API ImGuiTableSettings* TableSettingsCreate(ImGuiID id, int columns_count); IMGUI_API ImGuiTableSettings* TableSettingsFindByID(ImGuiID id); // Tab Bars inline ImGuiTabBar* GetCurrentTabBar() { ImGuiContext& g = *GImGui; return g.CurrentTabBar; } IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags); IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id); IMGUI_API ImGuiTabItem* TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order); IMGUI_API ImGuiTabItem* TabBarGetCurrentTab(ImGuiTabBar* tab_bar); inline int TabBarGetTabOrder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { return tab_bar->Tabs.index_from_ptr(tab); } IMGUI_API const char* TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id); IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); IMGUI_API void TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); IMGUI_API void TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset); IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImVec2 mouse_pos); IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar); IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window); IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker); IMGUI_API ImVec2 TabItemCalcSize(ImGuiWindow* window); IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col); IMGUI_API void TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped); // Render helpers // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT. // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally) IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL); IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known); IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool borders = true, float rounding = 0.0f); IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f); IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0); IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_None); // Navigation highlight IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. IMGUI_API void RenderMouseCursor(ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow); // Render helpers (those functions don't access any ImGui state!) IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding); IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); // Widgets IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0); IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0); IMGUI_API bool ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags = 0); IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags, float thickness = 1.0f); IMGUI_API void SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_width); IMGUI_API bool CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value); IMGUI_API bool CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value); // Widgets: Window Decorations IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos); IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos); IMGUI_API void Scrollbar(ImGuiAxis axis); IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags flags); IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis); IMGUI_API ImGuiID GetWindowResizeCornerID(ImGuiWindow* window, int n); // 0..3: corners IMGUI_API ImGuiID GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir); // Widgets low-level behaviors IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags); IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f, ImU32 bg_col = 0); // Widgets: Tree Nodes IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); IMGUI_API void TreePushOverrideID(ImGuiID id); IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); IMGUI_API void TreeNodeSetOpen(ImGuiID storage_id, bool open); IMGUI_API bool TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags); // Return open state. Consume previous SetNextItemOpen() data, if any. May return true when logging. // Template functions are instantiated in imgui_widgets.cpp for a finite number of types. // To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036). // e.g. " extern template IMGUI_API float RoundScalarWithFormatT<float, float>(const char* format, ImGuiDataType data_type, float v); " template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API T ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size); template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags); template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb); template<typename T> IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v); template<typename T> IMGUI_API bool CheckboxFlagsT(const char* label, T* flags, T flags_value); // Data type helpers IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type); IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format); IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg_1, const void* arg_2); IMGUI_API bool DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty = NULL); IMGUI_API int DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2); IMGUI_API bool DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API void InputTextDeactivateHook(ImGuiID id); IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags); IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL); inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); } inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (id != 0 && g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active IMGUI_API void SetNextItemRefVal(ImGuiDataType data_type, void* p_data); // Color IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags); IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags); // Plot IMGUI_API int PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, const ImVec2& size_arg); // Shade functions (write over already created vertices) IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1); IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp); IMGUI_API void ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& pivot_in, float cos_a, float sin_a, const ImVec2& pivot_out); // Garbage collection IMGUI_API void GcCompactTransientMiscBuffers(); IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window); IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); // Debug Tools IMGUI_API void DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size); // size >= 0 : alloc, size = -1 : free IMGUI_API void ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL); IMGUI_API void ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL); IMGUI_API void ErrorCheckUsingSetCursorPosToExtendParentBoundaries(); IMGUI_API void DebugDrawCursorPos(ImU32 col = IM_COL32(255, 0, 0, 255)); IMGUI_API void DebugDrawLineExtents(ImU32 col = IM_COL32(255, 0, 0, 255)); IMGUI_API void DebugDrawItemRect(ImU32 col = IM_COL32(255, 0, 0, 255)); IMGUI_API void DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end); IMGUI_API void DebugLocateItem(ImGuiID target_id); // Call sparingly: only 1 at the same time! IMGUI_API void DebugLocateItemOnHover(ImGuiID target_id); // Only call on reaction to a mouse Hover: because only 1 at the same time! IMGUI_API void DebugLocateItemResolveWithLastItem(); IMGUI_API void DebugBreakClearData(); IMGUI_API bool DebugBreakButton(const char* label, const char* description_of_location); IMGUI_API void DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location); IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); IMGUI_API void DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end); IMGUI_API void DebugNodeColumns(ImGuiOldColumns* columns); IMGUI_API void DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label); IMGUI_API void DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb); IMGUI_API void DebugNodeFont(ImFont* font); IMGUI_API void DebugNodeFontGlyph(ImFont* font, const ImFontGlyph* glyph); IMGUI_API void DebugNodeStorage(ImGuiStorage* storage, const char* label); IMGUI_API void DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label); IMGUI_API void DebugNodeTable(ImGuiTable* table); IMGUI_API void DebugNodeTableSettings(ImGuiTableSettings* settings); IMGUI_API void DebugNodeInputTextState(ImGuiInputTextState* state); IMGUI_API void DebugNodeTypingSelectState(ImGuiTypingSelectState* state); IMGUI_API void DebugNodeMultiSelectState(ImGuiMultiSelectState* state); IMGUI_API void DebugNodeWindow(ImGuiWindow* window, const char* label); IMGUI_API void DebugNodeWindowSettings(ImGuiWindowSettings* settings); IMGUI_API void DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label); IMGUI_API void DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack); IMGUI_API void DebugNodeViewport(ImGuiViewportP* viewport); IMGUI_API void DebugRenderKeyboardPreview(ImDrawList* draw_list); IMGUI_API void DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb); // Obsolete functions #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS inline void SetItemUsingMouseWheel() { SetItemKeyOwner(ImGuiKey_MouseWheelY); } // Changed in 1.89 inline bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0) { return TreeNodeUpdateNextOpen(id, flags); } // Renamed in 1.89 //inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); } // Removed in 1.87: Mapping from named key is always identity! // Refactored focus/nav/tabbing system in 1.82 and 1.84. If you have old/custom copy-and-pasted widgets which used FocusableItemRegister(): // (Old) IMGUI_VERSION_NUM < 18209: using 'ItemAdd(....)' and 'bool tab_focused = FocusableItemRegister(...)' // (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)' and 'bool tab_focused = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Focused) != 0' // (New) IMGUI_VERSION_NUM >= 18413: using 'ItemAdd(..., ImGuiItemFlags_Inputable)' and 'bool tab_focused = (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))' //inline bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id) // -> pass ImGuiItemAddFlags_Inputable flag to ItemAdd() //inline void FocusableItemUnregister(ImGuiWindow* window) // -> unnecessary: TempInputText() uses ImGuiInputTextFlags_MergedItem #endif } // namespace ImGui //----------------------------------------------------------------------------- // [SECTION] ImFontAtlas internal API //----------------------------------------------------------------------------- // This structure is likely to evolve as we add support for incremental atlas updates struct ImFontBuilderIO { bool (*FontBuilder_Build)(ImFontAtlas* atlas); }; // Helper for font builder #ifdef IMGUI_ENABLE_STB_TRUETYPE IMGUI_API const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype(); #endif IMGUI_API void ImFontAtlasUpdateConfigDataPointers(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent); IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque); IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value); IMGUI_API void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value); IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor); IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride); //----------------------------------------------------------------------------- // [SECTION] Test Engine specific hooks (imgui_test_engine) //----------------------------------------------------------------------------- #ifdef IMGUI_ENABLE_TEST_ENGINE extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, ImGuiID id, const ImRect& bb, const ImGuiLastItemData* item_data); // item_data may be NULL extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags); extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...); extern const char* ImGuiTestEngine_FindItemDebugLabel(ImGuiContext* ctx, ImGuiID id); // In IMGUI_VERSION_NUM >= 18934: changed IMGUI_TEST_ENGINE_ITEM_ADD(bb,id) to IMGUI_TEST_ENGINE_ITEM_ADD(id,bb,item_data); #define IMGUI_TEST_ENGINE_ITEM_ADD(_ID,_BB,_ITEM_DATA) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _ID, _BB, _ITEM_DATA) // Register item bounding box #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional) #define IMGUI_TEST_ENGINE_LOG(_FMT,...) if (g.TestEngineHookItems) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log #else #define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) ((void)0) #define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) ((void)g) #endif //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif #ifdef _MSC_VER #pragma warning (pop) #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig
repos/cimgui.zig/cimgui/cimgui.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui, v1.91.1 // (headers) // Help: // - See links below. // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // - Read top of imgui.cpp for more details, links and comments. // - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. // Resources: // - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md) // - Homepage ................... https://github.com/ocornut/imgui // - Releases & changelog ....... https://github.com/ocornut/imgui/releases // - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!) // - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) // - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) // - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) // - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines) // - Glossary https://github.com/ocornut/imgui/wiki/Glossary // - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools // - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui // - Issues & support ........... https://github.com/ocornut/imgui/issues // - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) // For first-time users having issues compiling/linking/running/loading fonts: // please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above. // Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there. // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') #define IMGUI_VERSION "1.91.1" #define IMGUI_VERSION_NUM 19110 #define IMGUI_HAS_TABLE /* Index of this file: // [SECTION] Header mess // [SECTION] Forward declarations and basic types // [SECTION] Dear ImGui end-user API functions // [SECTION] Flags & Enumerations // [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) // [SECTION] Helpers: Debug log, Memory allocations macros, ImVector<> // [SECTION] ImGuiStyle // [SECTION] ImGuiIO // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) // [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformImeData) // [SECTION] Obsolete functions and types */ #pragma once #ifdef __cplusplus extern "C" { #endif // Configuration file with compile-time options // (edit imconfig.h or '#define IMGUI_USER_CONFIG "myfilename.h" from your build system) #ifdef IMGUI_USER_CONFIG #include IMGUI_USER_CONFIG #endif // #ifdef IMGUI_USER_CONFIG #include "imconfig.h" //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE // [SECTION] Header mess //----------------------------------------------------------------------------- // Includes #include <stdint.h> #include <stdbool.h> #include <stdarg.h> #include <stddef.h> // Define attributes of all API symbols declarations (e.g. for DLL under Windows) // CIMGUI_API is used for core imgui functions, CIMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h) // Using dear imgui via a shared library is not recommended: we don't guarantee backward nor forward ABI compatibility + this is a call-heavy library and function call overhead adds up. #ifndef CIMGUI_API #define CIMGUI_API #endif // #ifndef CIMGUI_API #ifndef CIMGUI_IMPL_API #define CIMGUI_IMPL_API CIMGUI_API #endif // #ifndef CIMGUI_IMPL_API // Helper Macros #ifndef IM_ASSERT #include <assert.h> #define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h #endif // #ifndef IM_ASSERT #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR)))) // Size of a static C-style array. Don't use on pointers! #define IM_UNUSED(_VAR) ((void)(_VAR)) // Used to silence "unused variable warnings". Often useful as asserts may be stripped out from final builds. // Check that version and structures layouts are matching between compiled imgui code and caller. Read comments above DebugCheckVersionAndDataLayout() for details. #define CIMGUI_CHECKVERSION() ImGui_DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx)) // Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions. // (MSVC provides an equivalent mechanism via SAL Annotations but it would require the macros in a different // location. e.g. #include <sal.h> + void myprintf(_Printf_format_string_ const char* format, ...)) #if !defined(IMGUI_USE_STB_SPRINTF)&& defined(__MINGW32__)&&!defined(__clang__) #define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1))) #define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0))) #else #if !defined(IMGUI_USE_STB_SPRINTF)&&(defined(__clang__)|| defined(__GNUC__)) #define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) #define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) #else #define IM_FMTARGS(FMT) #define IM_FMTLIST(FMT) #endif // #if !defined(IMGUI_USE_STB_SPRINTF)&&(defined(__clang__)|| defined(__GNUC__)) #endif // #if !defined(IMGUI_USE_STB_SPRINTF)&& defined(__MINGW32__)&&!defined(__clang__) // Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions) #if defined(_MSC_VER)&&!defined(__clang__)&&!defined(__INTEL_COMPILER)&&!defined(IMGUI_DEBUG_PARANOID) #define IM_MSVC_RUNTIME_CHECKS_OFF __pragma(runtime_checks("",off)) __pragma(check_stack(off)) __pragma(strict_gs_check(push,off)) #define IM_MSVC_RUNTIME_CHECKS_RESTORE __pragma(runtime_checks("",restore)) __pragma(check_stack()) __pragma(strict_gs_check(pop)) #else #define IM_MSVC_RUNTIME_CHECKS_OFF #define IM_MSVC_RUNTIME_CHECKS_RESTORE #endif // #if defined(_MSC_VER)&&!defined(__clang__)&&!defined(__INTEL_COMPILER)&&!defined(IMGUI_DEBUG_PARANOID) // Warnings #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6). #endif // #ifdef _MSC_VER #if defined(__clang__) #pragma clang diagnostic push #if __has_warning("-Wunknown-warning-option") #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' #endif // #if __has_warning("-Wunknown-warning-option") #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access #else #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif // #if defined(__GNUC__) #endif // #if defined(__clang__) //----------------------------------------------------------------------------- // [SECTION] Forward declarations and basic types //----------------------------------------------------------------------------- // Auto-generated forward declarations for C header typedef struct ImVec2_t ImVec2; typedef struct ImVec4_t ImVec4; typedef struct ImVector_ImWchar_t ImVector_ImWchar; typedef struct ImVector_ImGuiTextFilter_ImGuiTextRange_t ImVector_ImGuiTextFilter_ImGuiTextRange; typedef struct ImVector_char_t ImVector_char; typedef struct ImVector_ImGuiStoragePair_t ImVector_ImGuiStoragePair; typedef struct ImVector_ImGuiSelectionRequest_t ImVector_ImGuiSelectionRequest; typedef struct ImVector_ImDrawCmd_t ImVector_ImDrawCmd; typedef struct ImVector_ImDrawIdx_t ImVector_ImDrawIdx; typedef struct ImVector_ImDrawChannel_t ImVector_ImDrawChannel; typedef struct ImVector_ImDrawVert_t ImVector_ImDrawVert; typedef struct ImVector_ImVec2_t ImVector_ImVec2; typedef struct ImVector_ImVec4_t ImVector_ImVec4; typedef struct ImVector_ImTextureID_t ImVector_ImTextureID; typedef struct ImVector_ImDrawListPtr_t ImVector_ImDrawListPtr; typedef struct ImVector_ImU32_t ImVector_ImU32; typedef struct ImVector_ImFontPtr_t ImVector_ImFontPtr; typedef struct ImVector_ImFontAtlasCustomRect_t ImVector_ImFontAtlasCustomRect; typedef struct ImVector_ImFontConfig_t ImVector_ImFontConfig; typedef struct ImVector_float_t ImVector_float; typedef struct ImVector_ImFontGlyph_t ImVector_ImFontGlyph; typedef struct ImGuiTextFilter_ImGuiTextRange_t ImGuiTextFilter_ImGuiTextRange; typedef struct ImDrawCmdHeader_t ImDrawCmdHeader; typedef struct ImFontAtlasCustomRect_t ImFontAtlasCustomRect; // Scalar data types typedef unsigned int ImGuiID; // A unique ID used by widgets (typically the result of hashing a stack of string) typedef signed char ImS8; // 8-bit signed integer typedef unsigned char ImU8; // 8-bit unsigned integer typedef signed short ImS16; // 16-bit signed integer typedef unsigned short ImU16; // 16-bit unsigned integer typedef signed int ImS32; // 32-bit signed integer == int typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) typedef signed long long ImS64; // 64-bit signed integer typedef unsigned long long ImU64; // 64-bit unsigned integer // Forward declarations typedef struct ImDrawChannel_t ImDrawChannel; // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit() typedef struct ImDrawCmd_t ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback) typedef struct ImDrawData_t ImDrawData; // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix. typedef struct ImDrawList_t ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) typedef struct ImDrawListSharedData_t ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) typedef struct ImDrawListSplitter_t ImDrawListSplitter; // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back. typedef struct ImDrawVert_t ImDrawVert; // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) typedef struct ImFont_t ImFont; // Runtime data for a single font within a parent ImFontAtlas typedef struct ImFontAtlas_t ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader typedef struct ImFontBuilderIO_t ImFontBuilderIO; // Opaque interface to a font builder (stb_truetype or FreeType). typedef struct ImFontConfig_t ImFontConfig; // Configuration data when adding a font or merging fonts typedef struct ImFontGlyph_t ImFontGlyph; // A single font glyph (code point + coordinates within in ImFontAtlas + offset) typedef struct ImFontGlyphRangesBuilder_t ImFontGlyphRangesBuilder; // Helper to build glyph ranges from text/string data typedef struct ImColor_t ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using) typedef struct ImGuiContext_t ImGuiContext; // Dear ImGui context (opaque structure, unless including imgui_internal.h) typedef struct ImGuiIO_t ImGuiIO; // Main configuration and I/O between your application and ImGui (also see: ImGuiPlatformIO) typedef struct ImGuiInputTextCallbackData_t ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) typedef struct ImGuiKeyData_t ImGuiKeyData; // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions. typedef struct ImGuiListClipper_t ImGuiListClipper; // Helper to manually clip large list of items typedef struct ImGuiMultiSelectIO_t ImGuiMultiSelectIO; // Structure to interact with a BeginMultiSelect()/EndMultiSelect() block typedef struct ImGuiPayload_t ImGuiPayload; // User data payload for drag and drop operations typedef struct ImGuiPlatformIO_t ImGuiPlatformIO; // Interface between platform/renderer backends and ImGui (e.g. Clipboard, IME hooks). Extends ImGuiIO. In docking branch, this gets extended to support multi-viewports. typedef struct ImGuiPlatformImeData_t ImGuiPlatformImeData; // Platform IME data for io.PlatformSetImeDataFn() function. typedef struct ImGuiSelectionBasicStorage_t ImGuiSelectionBasicStorage; // Optional helper to store multi-selection state + apply multi-selection requests. typedef struct ImGuiSelectionExternalStorage_t ImGuiSelectionExternalStorage; //Optional helper to apply multi-selection requests to existing randomly accessible storage. typedef struct ImGuiSelectionRequest_t ImGuiSelectionRequest; // A selection request (stored in ImGuiMultiSelectIO) typedef struct ImGuiSizeCallbackData_t ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) typedef struct ImGuiStorage_t ImGuiStorage; // Helper for key->value storage (container sorted by key) typedef struct ImGuiStoragePair_t ImGuiStoragePair; // Helper for key->value storage (pair) typedef struct ImGuiStyle_t ImGuiStyle; // Runtime data for styling/colors typedef struct ImGuiTableSortSpecs_t ImGuiTableSortSpecs; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) typedef struct ImGuiTableColumnSortSpecs_t ImGuiTableColumnSortSpecs; // Sorting specification for one column of a table typedef struct ImGuiTextBuffer_t ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) typedef struct ImGuiTextFilter_t ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbbb][,ccccc]") typedef struct ImGuiViewport_t ImGuiViewport; // A Platform Window (always only one in 'master' branch), in the future may represent Platform Monitor // Enumerations // - We don't use strongly typed enums much because they add constraints (can't extend in private code, can't store typed in bit fields, extra casting on iteration) // - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! // - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. // - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. typedef int ImGuiDir; // -> enum ImGuiDir // Enum: A cardinal direction (Left, Right, Up, Down) typedef int ImGuiKey; // -> enum ImGuiKey // Enum: A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value) typedef int ImGuiMouseSource; // -> enum ImGuiMouseSource // Enum; A mouse input source identifier (Mouse, TouchScreen, Pen) typedef ImU8 ImGuiSortDirection; // -> enum ImGuiSortDirection // Enum: A sorting direction (ascending or descending) typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type typedef int ImGuiMouseButton; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle) typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor shape typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() // Flags (declared as int to allow using as flags without overhead, and to not pollute the top of this file) // - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! // - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. // - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton() typedef int ImGuiChildFlags; // -> enum ImGuiChildFlags_ // Flags: for BeginChild() typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc. typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload() typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. typedef int ImGuiInputFlags; // -> enum ImGuiInputFlags_ // Flags: for Shortcut(), SetNextItemShortcut() typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag(), shared by all items typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiMultiSelectFlags; // -> enum ImGuiMultiSelectFlags_// Flags: for BeginMultiSelect() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTableFlags; // -> enum ImGuiTableFlags_ // Flags: For BeginTable() typedef int ImGuiTableColumnFlags; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn() typedef int ImGuiTableRowFlags; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader() typedef int ImGuiViewportFlags; // -> enum ImGuiViewportFlags_ // Flags: for ImGuiViewport typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild() // ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type] // - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file. // - This can be whatever to you want it to be! read the FAQ about ImTextureID for details. #ifndef ImTextureID typedef void* ImTextureID; // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that) #endif // #ifndef ImTextureID // ImDrawIdx: vertex index. [Compile-time configurable type] // - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). // - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; // Default: 16-bit (for maximum compatibility with renderer backends) #endif // #ifndef ImDrawIdx // Character types // (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display) typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings. typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings. #ifdef IMGUI_USE_WCHAR32 typedef ImWchar32 ImWchar; #else typedef ImWchar16 ImWchar; #endif// ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16] // Multi-Selection item index or identifier when using BeginMultiSelect() // - Used by SetNextItemSelectionUserData() + and inside ImGuiMultiSelectIO structure. // - Most users are likely to use this store an item INDEX but this may be used to store a POINTER/ID as well. Read comments near ImGuiMultiSelectIO for details. typedef ImS64 ImGuiSelectionUserData; // Callback and functions types typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText() typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints() typedef void* (*ImGuiMemAllocFunc)(size_t sz, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() typedef void (*ImGuiMemFreeFunc)(void* ptr, void* user_data); // Function signature for ImGui::SetAllocatorFunctions() // ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] // - This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type. // - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. IM_MSVC_RUNTIME_CHECKS_OFF typedef struct ImVec2_t { float x, y; } ImVec2; // ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] typedef struct ImVec4_t { float x, y, z, w; } ImVec4; IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- // [SECTION] Dear ImGui end-user API functions // (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!) //----------------------------------------------------------------------------- // Context creation and access // - Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts. // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for details. CIMGUI_API ImGuiContext* ImGui_CreateContext(ImFontAtlas* shared_font_atlas /* = NULL */); CIMGUI_API void ImGui_DestroyContext(ImGuiContext* ctx /* = NULL */); // NULL = destroy current context CIMGUI_API ImGuiContext* ImGui_GetCurrentContext(void); CIMGUI_API void ImGui_SetCurrentContext(ImGuiContext* ctx); // Main CIMGUI_API ImGuiIO* ImGui_GetIO(void); // access the ImGuiIO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) CIMGUI_API ImGuiPlatformIO* ImGui_GetPlatformIO(void); // access the ImGuiPlatformIO structure (mostly hooks/functions to connect to platform/renderer and OS Clipboard, IME etc.) CIMGUI_API ImGuiStyle* ImGui_GetStyle(void); // access the Style structure (colors, sizes). Always use PushStyleColor(), PushStyleVar() to modify style mid-frame! CIMGUI_API void ImGui_NewFrame(void); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame(). CIMGUI_API void ImGui_EndFrame(void); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all! CIMGUI_API void ImGui_Render(void); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData(). CIMGUI_API ImDrawData* ImGui_GetDrawData(void); // valid after Render() and until the next call to NewFrame(). this is what you have to render. // Demo, Debug, Information CIMGUI_API void ImGui_ShowDemoWindow(bool* p_open /* = NULL */); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! CIMGUI_API void ImGui_ShowMetricsWindow(bool* p_open /* = NULL */); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc. CIMGUI_API void ImGui_ShowDebugLogWindow(bool* p_open /* = NULL */); // create Debug Log window. display a simplified log of important dear imgui events. CIMGUI_API void ImGui_ShowIDStackToolWindow(void); // Implied p_open = NULL CIMGUI_API void ImGui_ShowIDStackToolWindowEx(bool* p_open /* = NULL */); // create Stack Tool window. hover items with mouse to query information about the source of their unique ID. CIMGUI_API void ImGui_ShowAboutWindow(bool* p_open /* = NULL */); // create About window. display Dear ImGui version, credits and build/system information. CIMGUI_API void ImGui_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) CIMGUI_API bool ImGui_ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. CIMGUI_API void ImGui_ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. CIMGUI_API void ImGui_ShowUserGuide(void); // add basic help/info block (not a window): how to manipulate ImGui as an end-user (mouse/keyboard controls). CIMGUI_API const char* ImGui_GetVersion(void); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp) // Styles CIMGUI_API void ImGui_StyleColorsDark(ImGuiStyle* dst /* = NULL */); // new, recommended style (default) CIMGUI_API void ImGui_StyleColorsLight(ImGuiStyle* dst /* = NULL */); // best used with borders and a custom, thicker font CIMGUI_API void ImGui_StyleColorsClassic(ImGuiStyle* dst /* = NULL */); // classic imgui style // Windows // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, // which clicking will set the boolean to false when clicked. // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times. // Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin(). // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! // [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] // - Note that the bottom of window stack always contains a window called "Debug". CIMGUI_API bool ImGui_Begin(const char* name, bool* p_open /* = NULL */, ImGuiWindowFlags flags /* = 0 */); CIMGUI_API void ImGui_End(void); // Child Windows // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. // - Before 1.90 (November 2023), the "ImGuiChildFlags child_flags = 0" parameter was "bool border = false". // This API is backward compatible with old code, as we guarantee that ImGuiChildFlags_Borders == true. // Consider updating your old code: // BeginChild("Name", size, false) -> Begin("Name", size, 0); or Begin("Name", size, ImGuiChildFlags_None); // BeginChild("Name", size, true) -> Begin("Name", size, ImGuiChildFlags_Borders); // - Manual sizing (each axis can use a different setting e.g. ImVec2(0.0f, 400.0f)): // == 0.0f: use remaining parent window size for this axis. // > 0.0f: use specified size for this axis. // < 0.0f: right/bottom-align to specified distance from available content boundaries. // - Specifying ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY makes the sizing automatic based on child contents. // Combining both ImGuiChildFlags_AutoResizeX _and_ ImGuiChildFlags_AutoResizeY defeats purpose of a scrolling region and is NOT recommended. // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting // anything to the window. Always call a matching EndChild() for each BeginChild() call, regardless of its return value. // [Important: due to legacy reason, Begin/End and BeginChild/EndChild are inconsistent with all other functions // such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding // BeginXXX function returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.] CIMGUI_API bool ImGui_BeginChild(const char* str_id, ImVec2 size /* = ImVec2(0, 0) */, ImGuiChildFlags child_flags /* = 0 */, ImGuiWindowFlags window_flags /* = 0 */); CIMGUI_API bool ImGui_BeginChildID(ImGuiID id, ImVec2 size /* = ImVec2(0, 0) */, ImGuiChildFlags child_flags /* = 0 */, ImGuiWindowFlags window_flags /* = 0 */); CIMGUI_API void ImGui_EndChild(void); // Windows Utilities // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into. CIMGUI_API bool ImGui_IsWindowAppearing(void); CIMGUI_API bool ImGui_IsWindowCollapsed(void); CIMGUI_API bool ImGui_IsWindowFocused(ImGuiFocusedFlags flags /* = 0 */); // is current window focused? or its root/child, depending on flags. see flags for options. CIMGUI_API bool ImGui_IsWindowHovered(ImGuiHoveredFlags flags /* = 0 */); // is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options. IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. CIMGUI_API ImDrawList* ImGui_GetWindowDrawList(void); // get draw list associated to the current window, to append your own drawing primitives CIMGUI_API ImVec2 ImGui_GetWindowPos(void); // get current window position in screen space (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) CIMGUI_API ImVec2 ImGui_GetWindowSize(void); // get current window size (IT IS UNLIKELY YOU EVER NEED TO USE THIS. Consider always using GetCursorScreenPos() and GetContentRegionAvail() instead) CIMGUI_API float ImGui_GetWindowWidth(void); // get current window width (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().x. CIMGUI_API float ImGui_GetWindowHeight(void); // get current window height (IT IS UNLIKELY YOU EVER NEED TO USE THIS). Shortcut for GetWindowSize().y. // Window manipulation // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin). CIMGUI_API void ImGui_SetNextWindowPos(ImVec2 pos, ImGuiCond cond /* = 0 */); // Implied pivot = ImVec2(0, 0) CIMGUI_API void ImGui_SetNextWindowPosEx(ImVec2 pos, ImGuiCond cond /* = 0 */, ImVec2 pivot /* = ImVec2(0, 0) */); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. CIMGUI_API void ImGui_SetNextWindowSize(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() CIMGUI_API void ImGui_SetNextWindowSizeConstraints(ImVec2 size_min, ImVec2 size_max, ImGuiSizeCallback custom_callback /* = NULL */, void* custom_callback_data /* = NULL */); // set next window size limits. use 0.0f or FLT_MAX if you don't want limits. Use -1 for both min and max of same axis to preserve current size (which itself is a constraint). Use callback to apply non-trivial programmatic constraints. CIMGUI_API void ImGui_SetNextWindowContentSize(ImVec2 size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin() CIMGUI_API void ImGui_SetNextWindowCollapsed(bool collapsed, ImGuiCond cond /* = 0 */); // set next window collapsed state. call before Begin() CIMGUI_API void ImGui_SetNextWindowFocus(void); // set next window to be focused / top-most. call before Begin() CIMGUI_API void ImGui_SetNextWindowScroll(ImVec2 scroll); // set next window scrolling value (use < 0.0f to not affect a given axis). CIMGUI_API void ImGui_SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. CIMGUI_API void ImGui_SetWindowPos(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. CIMGUI_API void ImGui_SetWindowSize(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. CIMGUI_API void ImGui_SetWindowCollapsed(bool collapsed, ImGuiCond cond /* = 0 */); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). CIMGUI_API void ImGui_SetWindowFocus(void); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus(). CIMGUI_API void ImGui_SetWindowFontScale(float scale); // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes(). CIMGUI_API void ImGui_SetWindowPosStr(const char* name, ImVec2 pos, ImGuiCond cond /* = 0 */); // set named window position. CIMGUI_API void ImGui_SetWindowSizeStr(const char* name, ImVec2 size, ImGuiCond cond /* = 0 */); // set named window size. set axis to 0.0f to force an auto-fit on this axis. CIMGUI_API void ImGui_SetWindowCollapsedStr(const char* name, bool collapsed, ImGuiCond cond /* = 0 */); // set named window collapsed state CIMGUI_API void ImGui_SetWindowFocusStr(const char* name); // set named window to be focused / top-most. use NULL to remove focus. // Windows Scrolling // - Any change of Scroll will be applied at the beginning of next frame in the first call to Begin(). // - You may instead use SetNextWindowScroll() prior to calling Begin() to avoid this delay, as an alternative to using SetScrollX()/SetScrollY(). CIMGUI_API float ImGui_GetScrollX(void); // get scrolling amount [0 .. GetScrollMaxX()] CIMGUI_API float ImGui_GetScrollY(void); // get scrolling amount [0 .. GetScrollMaxY()] CIMGUI_API void ImGui_SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()] CIMGUI_API void ImGui_SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()] CIMGUI_API float ImGui_GetScrollMaxX(void); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x CIMGUI_API float ImGui_GetScrollMaxY(void); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y CIMGUI_API void ImGui_SetScrollHereX(float center_x_ratio /* = 0.5f */); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. CIMGUI_API void ImGui_SetScrollHereY(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. CIMGUI_API void ImGui_SetScrollFromPosX(float local_x, float center_x_ratio /* = 0.5f */); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. CIMGUI_API void ImGui_SetScrollFromPosY(float local_y, float center_y_ratio /* = 0.5f */); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position. // Parameters stacks (shared) CIMGUI_API void ImGui_PushFont(ImFont* font); // use NULL as a shortcut to push default font CIMGUI_API void ImGui_PopFont(void); CIMGUI_API void ImGui_PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame(). CIMGUI_API void ImGui_PushStyleColorImVec4(ImGuiCol idx, ImVec4 col); CIMGUI_API void ImGui_PopStyleColor(void); // Implied count = 1 CIMGUI_API void ImGui_PopStyleColorEx(int count /* = 1 */); CIMGUI_API void ImGui_PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame()! CIMGUI_API void ImGui_PushStyleVarImVec2(ImGuiStyleVar idx, ImVec2 val); // modify a style ImVec2 variable. " CIMGUI_API void ImGui_PushStyleVarX(ImGuiStyleVar idx, float val_x); // modify X component of a style ImVec2 variable. " CIMGUI_API void ImGui_PushStyleVarY(ImGuiStyleVar idx, float val_y); // modify Y component of a style ImVec2 variable. " CIMGUI_API void ImGui_PopStyleVar(void); // Implied count = 1 CIMGUI_API void ImGui_PopStyleVarEx(int count /* = 1 */); CIMGUI_API void ImGui_PushItemFlag(ImGuiItemFlags option, bool enabled); // modify specified shared item flag, e.g. PushItemFlag(ImGuiItemFlags_NoTabStop, true) CIMGUI_API void ImGui_PopItemFlag(void); // Parameters stacks (current window) CIMGUI_API void ImGui_PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). CIMGUI_API void ImGui_PopItemWidth(void); CIMGUI_API void ImGui_SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side) CIMGUI_API float ImGui_CalcItemWidth(void); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions. CIMGUI_API void ImGui_PushTextWrapPos(float wrap_local_pos_x /* = 0.0f */); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space CIMGUI_API void ImGui_PopTextWrapPos(void); // Style read access // - Use the ShowStyleEditor() function to interactively see/edit the colors. CIMGUI_API ImFont* ImGui_GetFont(void); // get current font CIMGUI_API float ImGui_GetFontSize(void); // get current font size (= height in pixels) of current font with current scale applied CIMGUI_API ImVec2 ImGui_GetFontTexUvWhitePixel(void); // get UV coordinate for a white pixel, useful to draw custom shapes via the ImDrawList API CIMGUI_API ImU32 ImGui_GetColorU32(ImGuiCol idx); // Implied alpha_mul = 1.0f CIMGUI_API ImU32 ImGui_GetColorU32Ex(ImGuiCol idx, float alpha_mul /* = 1.0f */); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList CIMGUI_API ImU32 ImGui_GetColorU32ImVec4(ImVec4 col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList CIMGUI_API ImU32 ImGui_GetColorU32ImU32(ImU32 col); // Implied alpha_mul = 1.0f CIMGUI_API ImU32 ImGui_GetColorU32ImU32Ex(ImU32 col, float alpha_mul /* = 1.0f */); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList CIMGUI_API const ImVec4* ImGui_GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. // Layout cursor positioning // - By "cursor" we mean the current output position. // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget. // - YOU CAN DO 99% OF WHAT YOU NEED WITH ONLY GetCursorScreenPos() and GetContentRegionAvail(). // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API: // - Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions. -> this is the preferred way forward. // - Window-local coordinates: SameLine(offset), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), PushTextWrapPos() // - Window-local coordinates: GetContentRegionMax(), GetWindowContentRegionMin(), GetWindowContentRegionMax() --> all obsoleted. YOU DON'T NEED THEM. // - GetCursorScreenPos() = GetCursorPos() + GetWindowPos(). GetWindowPos() is almost only ever useful to convert from window-local to absolute coordinates. Try not to use it. CIMGUI_API ImVec2 ImGui_GetCursorScreenPos(void); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND (prefer using this rather than GetCursorPos(), also more useful to work with ImDrawList API). CIMGUI_API void ImGui_SetCursorScreenPos(ImVec2 pos); // cursor position, absolute coordinates. THIS IS YOUR BEST FRIEND. CIMGUI_API ImVec2 ImGui_GetContentRegionAvail(void); // available space from current position. THIS IS YOUR BEST FRIEND. CIMGUI_API ImVec2 ImGui_GetCursorPos(void); // [window-local] cursor position in window-local coordinates. This is not your best friend. CIMGUI_API float ImGui_GetCursorPosX(void); // [window-local] " CIMGUI_API float ImGui_GetCursorPosY(void); // [window-local] " CIMGUI_API void ImGui_SetCursorPos(ImVec2 local_pos); // [window-local] " CIMGUI_API void ImGui_SetCursorPosX(float local_x); // [window-local] " CIMGUI_API void ImGui_SetCursorPosY(float local_y); // [window-local] " CIMGUI_API ImVec2 ImGui_GetCursorStartPos(void); // [window-local] initial cursor position, in window-local coordinates. Call GetCursorScreenPos() after Begin() to get the absolute coordinates version. // Other layout functions CIMGUI_API void ImGui_Separator(void); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. CIMGUI_API void ImGui_SameLine(void); // Implied offset_from_start_x = 0.0f, spacing = -1.0f CIMGUI_API void ImGui_SameLineEx(float offset_from_start_x /* = 0.0f */, float spacing /* = -1.0f */); // call between widgets or groups to layout them horizontally. X position given in window coordinates. CIMGUI_API void ImGui_NewLine(void); // undo a SameLine() or force a new line when in a horizontal-layout context. CIMGUI_API void ImGui_Spacing(void); // add vertical spacing. CIMGUI_API void ImGui_Dummy(ImVec2 size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. CIMGUI_API void ImGui_Indent(void); // Implied indent_w = 0.0f CIMGUI_API void ImGui_IndentEx(float indent_w /* = 0.0f */); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0 CIMGUI_API void ImGui_Unindent(void); // Implied indent_w = 0.0f CIMGUI_API void ImGui_UnindentEx(float indent_w /* = 0.0f */); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0 CIMGUI_API void ImGui_BeginGroup(void); // lock horizontal starting position CIMGUI_API void ImGui_EndGroup(void); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) CIMGUI_API void ImGui_AlignTextToFramePadding(void); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) CIMGUI_API float ImGui_GetTextLineHeight(void); // ~ FontSize CIMGUI_API float ImGui_GetTextLineHeightWithSpacing(void); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) CIMGUI_API float ImGui_GetFrameHeight(void); // ~ FontSize + style.FramePadding.y * 2 CIMGUI_API float ImGui_GetFrameHeightWithSpacing(void); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) // ID stack/scopes // Read the FAQ (docs/FAQ.md or http://dearimgui.com/faq) for more details about how ID are handled in dear imgui. // - Those questions are answered and impacted by understanding of the ID stack system: // - "Q: Why is my widget not reacting when I click on it?" // - "Q: How can I have widgets with an empty label?" // - "Q: How can I have multiple widgets with the same label?" // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely // want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID, // whereas "str_id" denote a string that is only used as an ID and not normally displayed. CIMGUI_API void ImGui_PushID(const char* str_id); // push string into the ID stack (will hash string). CIMGUI_API void ImGui_PushIDStr(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). CIMGUI_API void ImGui_PushIDPtr(const void* ptr_id); // push pointer into the ID stack (will hash pointer). CIMGUI_API void ImGui_PushIDInt(int int_id); // push integer into the ID stack (will hash integer). CIMGUI_API void ImGui_PopID(void); // pop from the ID stack. CIMGUI_API ImGuiID ImGui_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 CIMGUI_API ImGuiID ImGui_GetIDStr(const char* str_id_begin, const char* str_id_end); CIMGUI_API ImGuiID ImGui_GetIDPtr(const void* ptr_id); CIMGUI_API ImGuiID ImGui_GetIDInt(int int_id); // Widgets: Text CIMGUI_API void ImGui_TextUnformatted(const char* text); // Implied text_end = NULL CIMGUI_API void ImGui_TextUnformattedEx(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. CIMGUI_API void ImGui_Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text CIMGUI_API void ImGui_TextV(const char* fmt, va_list args) IM_FMTLIST(1); CIMGUI_API void ImGui_TextColored(ImVec4 col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); CIMGUI_API void ImGui_TextColoredV(ImVec4 col, const char* fmt, va_list args) IM_FMTLIST(2); CIMGUI_API void ImGui_TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); CIMGUI_API void ImGui_TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); CIMGUI_API void ImGui_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(). CIMGUI_API void ImGui_TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); CIMGUI_API void ImGui_LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets CIMGUI_API void ImGui_LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); CIMGUI_API void ImGui_BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() CIMGUI_API void ImGui_BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); CIMGUI_API void ImGui_SeparatorText(const char* label); // currently: formatted text with an horizontal line // Widgets: Main // - Most widgets return true when the value has been changed or when pressed/selected // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state. CIMGUI_API bool ImGui_Button(const char* label); // Implied size = ImVec2(0, 0) CIMGUI_API bool ImGui_ButtonEx(const char* label, ImVec2 size /* = ImVec2(0, 0) */); // button CIMGUI_API bool ImGui_SmallButton(const char* label); // button with (FramePadding.y == 0) to easily embed within text CIMGUI_API bool ImGui_InvisibleButton(const char* str_id, ImVec2 size, ImGuiButtonFlags flags /* = 0 */); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) CIMGUI_API bool ImGui_ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape CIMGUI_API bool ImGui_Checkbox(const char* label, bool* v); CIMGUI_API bool ImGui_CheckboxFlagsIntPtr(const char* label, int* flags, int flags_value); CIMGUI_API bool ImGui_CheckboxFlagsUintPtr(const char* label, unsigned int* flags, unsigned int flags_value); CIMGUI_API bool ImGui_RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } CIMGUI_API bool ImGui_RadioButtonIntPtr(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer CIMGUI_API void ImGui_ProgressBar(float fraction, ImVec2 size_arg /* = ImVec2(-FLT_MIN, 0) */, const char* overlay /* = NULL */); CIMGUI_API void ImGui_Bullet(void); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses CIMGUI_API bool ImGui_TextLink(const char* label); // hyperlink text button, return true when clicked CIMGUI_API void ImGui_TextLinkOpenURL(const char* label); // Implied url = NULL CIMGUI_API void ImGui_TextLinkOpenURLEx(const char* label, const char* url /* = NULL */); // hyperlink text button, automatically open file/url when clicked // Widgets: Images // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above. // - Note that Image() may add +2.0f to provided size if a border is visible, ImageButton() adds style.FramePadding*2.0f to provided size. CIMGUI_API void ImGui_Image(ImTextureID user_texture_id, ImVec2 image_size); // Implied uv0 = ImVec2(0, 0), uv1 = ImVec2(1, 1), tint_col = ImVec4(1, 1, 1, 1), border_col = ImVec4(0, 0, 0, 0) CIMGUI_API void ImGui_ImageEx(ImTextureID user_texture_id, ImVec2 image_size, ImVec2 uv0 /* = ImVec2(0, 0) */, ImVec2 uv1 /* = ImVec2(1, 1) */, ImVec4 tint_col /* = ImVec4(1, 1, 1, 1) */, ImVec4 border_col /* = ImVec4(0, 0, 0, 0) */); CIMGUI_API bool ImGui_ImageButton(const char* str_id, ImTextureID user_texture_id, ImVec2 image_size); // Implied uv0 = ImVec2(0, 0), uv1 = ImVec2(1, 1), bg_col = ImVec4(0, 0, 0, 0), tint_col = ImVec4(1, 1, 1, 1) CIMGUI_API bool ImGui_ImageButtonEx(const char* str_id, ImTextureID user_texture_id, ImVec2 image_size, ImVec2 uv0 /* = ImVec2(0, 0) */, ImVec2 uv1 /* = ImVec2(1, 1) */, ImVec4 bg_col /* = ImVec4(0, 0, 0, 0) */, ImVec4 tint_col /* = ImVec4(1, 1, 1, 1) */); // Widgets: Combo Box (Dropdown) // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created. CIMGUI_API bool ImGui_BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags /* = 0 */); CIMGUI_API void ImGui_EndCombo(void); // only call EndCombo() if BeginCombo() returns true! CIMGUI_API bool ImGui_ComboChar(const char* label, int* current_item, const char*const items[], int items_count); // Implied popup_max_height_in_items = -1 CIMGUI_API bool ImGui_ComboCharEx(const char* label, int* current_item, const char*const items[], int items_count, int popup_max_height_in_items /* = -1 */); CIMGUI_API bool ImGui_Combo(const char* label, int* current_item, const char* items_separated_by_zeros); // Implied popup_max_height_in_items = -1 CIMGUI_API bool ImGui_ComboEx(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" CIMGUI_API bool ImGui_ComboCallback(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count); // Implied popup_max_height_in_items = -1 CIMGUI_API bool ImGui_ComboCallbackEx(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items /* = -1 */); // Widgets: Drag Sliders // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every function, note that a 'float v[X]' function argument is the same as 'float* v', // the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used. // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum. // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. // - Legacy: Pre-1.78 there are DragXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 CIMGUI_API bool ImGui_DragFloat(const char* label, float* v); // Implied v_speed = 1.0f, v_min = 0.0f, v_max = 0.0f, format = "%.3f", flags = 0 CIMGUI_API bool ImGui_DragFloatEx(const char* label, float* v, float v_speed /* = 1.0f */, float v_min /* = 0.0f */, float v_max /* = 0.0f */, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); // If v_min >= v_max we have no bound CIMGUI_API bool ImGui_DragFloat2(const char* label, float v[2]); // Implied v_speed = 1.0f, v_min = 0.0f, v_max = 0.0f, format = "%.3f", flags = 0 CIMGUI_API bool ImGui_DragFloat2Ex(const char* label, float v[2], float v_speed /* = 1.0f */, float v_min /* = 0.0f */, float v_max /* = 0.0f */, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragFloat3(const char* label, float v[3]); // Implied v_speed = 1.0f, v_min = 0.0f, v_max = 0.0f, format = "%.3f", flags = 0 CIMGUI_API bool ImGui_DragFloat3Ex(const char* label, float v[3], float v_speed /* = 1.0f */, float v_min /* = 0.0f */, float v_max /* = 0.0f */, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragFloat4(const char* label, float v[4]); // Implied v_speed = 1.0f, v_min = 0.0f, v_max = 0.0f, format = "%.3f", flags = 0 CIMGUI_API bool ImGui_DragFloat4Ex(const char* label, float v[4], float v_speed /* = 1.0f */, float v_min /* = 0.0f */, float v_max /* = 0.0f */, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragFloatRange2(const char* label, float* v_current_min, float* v_current_max); // Implied v_speed = 1.0f, v_min = 0.0f, v_max = 0.0f, format = "%.3f", format_max = NULL, flags = 0 CIMGUI_API bool ImGui_DragFloatRange2Ex(const char* label, float* v_current_min, float* v_current_max, float v_speed /* = 1.0f */, float v_min /* = 0.0f */, float v_max /* = 0.0f */, const char* format /* = "%.3f" */, const char* format_max /* = NULL */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragInt(const char* label, int* v); // Implied v_speed = 1.0f, v_min = 0, v_max = 0, format = "%d", flags = 0 CIMGUI_API bool ImGui_DragIntEx(const char* label, int* v, float v_speed /* = 1.0f */, int v_min /* = 0 */, int v_max /* = 0 */, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); // If v_min >= v_max we have no bound CIMGUI_API bool ImGui_DragInt2(const char* label, int v[2]); // Implied v_speed = 1.0f, v_min = 0, v_max = 0, format = "%d", flags = 0 CIMGUI_API bool ImGui_DragInt2Ex(const char* label, int v[2], float v_speed /* = 1.0f */, int v_min /* = 0 */, int v_max /* = 0 */, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragInt3(const char* label, int v[3]); // Implied v_speed = 1.0f, v_min = 0, v_max = 0, format = "%d", flags = 0 CIMGUI_API bool ImGui_DragInt3Ex(const char* label, int v[3], float v_speed /* = 1.0f */, int v_min /* = 0 */, int v_max /* = 0 */, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragInt4(const char* label, int v[4]); // Implied v_speed = 1.0f, v_min = 0, v_max = 0, format = "%d", flags = 0 CIMGUI_API bool ImGui_DragInt4Ex(const char* label, int v[4], float v_speed /* = 1.0f */, int v_min /* = 0 */, int v_max /* = 0 */, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragIntRange2(const char* label, int* v_current_min, int* v_current_max); // Implied v_speed = 1.0f, v_min = 0, v_max = 0, format = "%d", format_max = NULL, flags = 0 CIMGUI_API bool ImGui_DragIntRange2Ex(const char* label, int* v_current_min, int* v_current_max, float v_speed /* = 1.0f */, int v_min /* = 0 */, int v_max /* = 0 */, const char* format /* = "%d" */, const char* format_max /* = NULL */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragScalar(const char* label, ImGuiDataType data_type, void* p_data); // Implied v_speed = 1.0f, p_min = NULL, p_max = NULL, format = NULL, flags = 0 CIMGUI_API bool ImGui_DragScalarEx(const char* label, ImGuiDataType data_type, void* p_data, float v_speed /* = 1.0f */, const void* p_min /* = NULL */, const void* p_max /* = NULL */, const char* format /* = NULL */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components); // Implied v_speed = 1.0f, p_min = NULL, p_max = NULL, format = NULL, flags = 0 CIMGUI_API bool ImGui_DragScalarNEx(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed /* = 1.0f */, const void* p_min /* = NULL */, const void* p_max /* = NULL */, const char* format /* = NULL */, ImGuiSliderFlags flags /* = 0 */); // Widgets: Regular Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. // - Format string may also be set to NULL or use the default format ("%f" or "%d"). // - Legacy: Pre-1.78 there are SliderXXX() function signatures that take a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument. // If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361 CIMGUI_API bool ImGui_SliderFloat(const char* label, float* v, float v_min, float v_max); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_SliderFloatEx(const char* label, float* v, float v_min, float v_max, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. CIMGUI_API bool ImGui_SliderFloat2(const char* label, float v[2], float v_min, float v_max); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_SliderFloat2Ex(const char* label, float v[2], float v_min, float v_max, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderFloat3(const char* label, float v[3], float v_min, float v_max); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_SliderFloat3Ex(const char* label, float v[3], float v_min, float v_max, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderFloat4(const char* label, float v[4], float v_min, float v_max); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_SliderFloat4Ex(const char* label, float v[4], float v_min, float v_max, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderAngle(const char* label, float* v_rad); // Implied v_degrees_min = -360.0f, v_degrees_max = +360.0f, format = "%.0f deg", flags = 0 CIMGUI_API bool ImGui_SliderAngleEx(const char* label, float* v_rad, float v_degrees_min /* = -360.0f */, float v_degrees_max /* = +360.0f */, const char* format /* = "%.0f deg" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderInt(const char* label, int* v, int v_min, int v_max); // Implied format = "%d", flags = 0 CIMGUI_API bool ImGui_SliderIntEx(const char* label, int* v, int v_min, int v_max, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderInt2(const char* label, int v[2], int v_min, int v_max); // Implied format = "%d", flags = 0 CIMGUI_API bool ImGui_SliderInt2Ex(const char* label, int v[2], int v_min, int v_max, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderInt3(const char* label, int v[3], int v_min, int v_max); // Implied format = "%d", flags = 0 CIMGUI_API bool ImGui_SliderInt3Ex(const char* label, int v[3], int v_min, int v_max, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderInt4(const char* label, int v[4], int v_min, int v_max); // Implied format = "%d", flags = 0 CIMGUI_API bool ImGui_SliderInt4Ex(const char* label, int v[4], int v_min, int v_max, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); // Implied format = NULL, flags = 0 CIMGUI_API bool ImGui_SliderScalarEx(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format /* = NULL */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max); // Implied format = NULL, flags = 0 CIMGUI_API bool ImGui_SliderScalarNEx(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format /* = NULL */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_VSliderFloat(const char* label, ImVec2 size, float* v, float v_min, float v_max); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_VSliderFloatEx(const char* label, ImVec2 size, float* v, float v_min, float v_max, const char* format /* = "%.3f" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_VSliderInt(const char* label, ImVec2 size, int* v, int v_min, int v_max); // Implied format = "%d", flags = 0 CIMGUI_API bool ImGui_VSliderIntEx(const char* label, ImVec2 size, int* v, int v_min, int v_max, const char* format /* = "%d" */, ImGuiSliderFlags flags /* = 0 */); CIMGUI_API bool ImGui_VSliderScalar(const char* label, ImVec2 size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max); // Implied format = NULL, flags = 0 CIMGUI_API bool ImGui_VSliderScalarEx(const char* label, ImVec2 size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format /* = NULL */, ImGuiSliderFlags flags /* = 0 */); // Widgets: Input with Keyboard // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp. // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. CIMGUI_API bool ImGui_InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags /* = 0 */); // Implied callback = NULL, user_data = NULL CIMGUI_API bool ImGui_InputTextEx(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags /* = 0 */, ImGuiInputTextCallback callback /* = NULL */, void* user_data /* = NULL */); CIMGUI_API bool ImGui_InputTextMultiline(const char* label, char* buf, size_t buf_size); // Implied size = ImVec2(0, 0), flags = 0, callback = NULL, user_data = NULL CIMGUI_API bool ImGui_InputTextMultilineEx(const char* label, char* buf, size_t buf_size, ImVec2 size /* = ImVec2(0, 0) */, ImGuiInputTextFlags flags /* = 0 */, ImGuiInputTextCallback callback /* = NULL */, void* user_data /* = NULL */); CIMGUI_API bool ImGui_InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags /* = 0 */); // Implied callback = NULL, user_data = NULL CIMGUI_API bool ImGui_InputTextWithHintEx(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags /* = 0 */, ImGuiInputTextCallback callback /* = NULL */, void* user_data /* = NULL */); CIMGUI_API bool ImGui_InputFloat(const char* label, float* v); // Implied step = 0.0f, step_fast = 0.0f, format = "%.3f", flags = 0 CIMGUI_API bool ImGui_InputFloatEx(const char* label, float* v, float step /* = 0.0f */, float step_fast /* = 0.0f */, const char* format /* = "%.3f" */, ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputFloat2(const char* label, float v[2]); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_InputFloat2Ex(const char* label, float v[2], const char* format /* = "%.3f" */, ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputFloat3(const char* label, float v[3]); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_InputFloat3Ex(const char* label, float v[3], const char* format /* = "%.3f" */, ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputFloat4(const char* label, float v[4]); // Implied format = "%.3f", flags = 0 CIMGUI_API bool ImGui_InputFloat4Ex(const char* label, float v[4], const char* format /* = "%.3f" */, ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputInt(const char* label, int* v); // Implied step = 1, step_fast = 100, flags = 0 CIMGUI_API bool ImGui_InputIntEx(const char* label, int* v, int step /* = 1 */, int step_fast /* = 100 */, ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputDouble(const char* label, double* v); // Implied step = 0.0, step_fast = 0.0, format = "%.6f", flags = 0 CIMGUI_API bool ImGui_InputDoubleEx(const char* label, double* v, double step /* = 0.0 */, double step_fast /* = 0.0 */, const char* format /* = "%.6f" */, ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputScalar(const char* label, ImGuiDataType data_type, void* p_data); // Implied p_step = NULL, p_step_fast = NULL, format = NULL, flags = 0 CIMGUI_API bool ImGui_InputScalarEx(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step /* = NULL */, const void* p_step_fast /* = NULL */, const char* format /* = NULL */, ImGuiInputTextFlags flags /* = 0 */); CIMGUI_API bool ImGui_InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components); // Implied p_step = NULL, p_step_fast = NULL, format = NULL, flags = 0 CIMGUI_API bool ImGui_InputScalarNEx(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step /* = NULL */, const void* p_step_fast /* = NULL */, const char* format /* = NULL */, ImGuiInputTextFlags flags /* = 0 */); // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.) // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x CIMGUI_API bool ImGui_ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags /* = 0 */); CIMGUI_API bool ImGui_ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags /* = 0 */); CIMGUI_API bool ImGui_ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags /* = 0 */); CIMGUI_API bool ImGui_ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags /* = 0 */, const float* ref_col /* = NULL */); CIMGUI_API bool ImGui_ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags /* = 0 */); // Implied size = ImVec2(0, 0) CIMGUI_API bool ImGui_ColorButtonEx(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags /* = 0 */, ImVec2 size /* = ImVec2(0, 0) */); // display a color square/button, hover for details, return true when pressed. CIMGUI_API void ImGui_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 // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. CIMGUI_API bool ImGui_TreeNode(const char* label); CIMGUI_API bool ImGui_TreeNodeStr(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. 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(). CIMGUI_API bool ImGui_TreeNodePtr(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " CIMGUI_API bool ImGui_TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); CIMGUI_API bool ImGui_TreeNodeVPtr(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); CIMGUI_API bool ImGui_TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags /* = 0 */); CIMGUI_API bool ImGui_TreeNodeExStr(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); CIMGUI_API bool ImGui_TreeNodeExPtr(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); CIMGUI_API bool ImGui_TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); CIMGUI_API bool ImGui_TreeNodeExVPtr(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); CIMGUI_API void ImGui_TreePush(const char* str_id); // ~ Indent()+PushID(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. CIMGUI_API void ImGui_TreePushPtr(const void* ptr_id); // " CIMGUI_API void ImGui_TreePop(void); // ~ Unindent()+PopID() CIMGUI_API float ImGui_GetTreeNodeToLabelSpacing(void); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode CIMGUI_API bool ImGui_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(). CIMGUI_API bool ImGui_CollapsingHeaderBoolPtr(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags /* = 0 */); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. CIMGUI_API void ImGui_SetNextItemOpen(bool is_open, ImGuiCond cond /* = 0 */); // set next TreeNode/CollapsingHeader open state. CIMGUI_API void ImGui_SetNextItemStorageID(ImGuiID storage_id); // set id to use for open/close storage (default to same as item id). // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous. CIMGUI_API bool ImGui_Selectable(const char* label); // Implied selected = false, flags = 0, size = ImVec2(0, 0) CIMGUI_API bool ImGui_SelectableEx(const char* label, bool selected /* = false */, ImGuiSelectableFlags flags /* = 0 */, 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 CIMGUI_API bool ImGui_SelectableBoolPtr(const char* label, bool* p_selected, ImGuiSelectableFlags flags /* = 0 */); // Implied size = ImVec2(0, 0) CIMGUI_API bool ImGui_SelectableBoolPtrEx(const char* label, bool* p_selected, ImGuiSelectableFlags flags /* = 0 */, ImVec2 size /* = ImVec2(0, 0) */); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. // Multi-selection system for Selectable(), Checkbox(), TreeNode() functions [BETA] // - This enables standard multi-selection/range-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc.) in a way that also allow a clipper to be used. // - ImGuiSelectionUserData is often used to store your item index within the current view (but may store something else). // - Read comments near ImGuiMultiSelectIO for instructions/details and see 'Demo->Widgets->Selection State & Multi-Select' for demo. // - TreeNode() is technically supported but... using this correctly is more complicated. You need some sort of linear/random access to your tree, // which is suited to advanced trees setups already implementing filters and clipper. We will work simplifying the current demo. // - 'selection_size' and 'items_count' parameters are optional and used by a few features. If they are costly for you to compute, you may avoid them. CIMGUI_API ImGuiMultiSelectIO* ImGui_BeginMultiSelect(ImGuiMultiSelectFlags flags); // Implied selection_size = -1, items_count = -1 CIMGUI_API ImGuiMultiSelectIO* ImGui_BeginMultiSelectEx(ImGuiMultiSelectFlags flags, int selection_size /* = -1 */, int items_count /* = -1 */); CIMGUI_API ImGuiMultiSelectIO* ImGui_EndMultiSelect(void); CIMGUI_API void ImGui_SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data); CIMGUI_API bool ImGui_IsItemToggledSelection(void); // Was the last item selection state toggled? Useful if you need the per-item information _before_ reaching EndMultiSelect(). We only returns toggle _event_ in order to handle clipping correctly. // Widgets: List Boxes // - This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label. // - You can submit contents and manage your selection state however you want it, by creating e.g. Selectable() or any other items. // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created. // - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth // - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items CIMGUI_API bool ImGui_BeginListBox(const char* label, ImVec2 size /* = ImVec2(0, 0) */); // open a framed scrolling region CIMGUI_API void ImGui_EndListBox(void); // only call EndListBox() if BeginListBox() returned true! CIMGUI_API bool ImGui_ListBox(const char* label, int* current_item, const char*const items[], int items_count, int height_in_items /* = -1 */); CIMGUI_API bool ImGui_ListBoxCallback(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count); // Implied height_in_items = -1 CIMGUI_API bool ImGui_ListBoxCallbackEx(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items /* = -1 */); // Widgets: Data Plotting // - Consider using ImPlot (https://github.com/epezent/implot) which is much better! CIMGUI_API void ImGui_PlotLines(const char* label, const float* values, int values_count); // Implied values_offset = 0, overlay_text = NULL, scale_min = FLT_MAX, scale_max = FLT_MAX, graph_size = ImVec2(0, 0), stride = sizeof(float) CIMGUI_API void ImGui_PlotLinesEx(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) */); CIMGUI_API void ImGui_PlotLinesCallback(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count); // Implied values_offset = 0, overlay_text = NULL, scale_min = FLT_MAX, scale_max = FLT_MAX, graph_size = ImVec2(0, 0) CIMGUI_API void ImGui_PlotLinesCallbackEx(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) */); CIMGUI_API void ImGui_PlotHistogram(const char* label, const float* values, int values_count); // Implied values_offset = 0, overlay_text = NULL, scale_min = FLT_MAX, scale_max = FLT_MAX, graph_size = ImVec2(0, 0), stride = sizeof(float) CIMGUI_API void ImGui_PlotHistogramEx(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) */); CIMGUI_API void ImGui_PlotHistogramCallback(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count); // Implied values_offset = 0, overlay_text = NULL, scale_min = FLT_MAX, scale_max = FLT_MAX, graph_size = ImVec2(0, 0) CIMGUI_API void ImGui_PlotHistogramCallbackEx(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) */); // Widgets: Menus // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar. // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it. // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it. // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment. CIMGUI_API bool ImGui_BeginMenuBar(void); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). CIMGUI_API void ImGui_EndMenuBar(void); // only call EndMenuBar() if BeginMenuBar() returns true! CIMGUI_API bool ImGui_BeginMainMenuBar(void); // create and append to a full screen menu-bar. CIMGUI_API void ImGui_EndMainMenuBar(void); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! CIMGUI_API bool ImGui_BeginMenu(const char* label); // Implied enabled = true CIMGUI_API bool ImGui_BeginMenuEx(const char* label, bool enabled /* = true */); // create a sub-menu entry. only call EndMenu() if this returns true! CIMGUI_API void ImGui_EndMenu(void); // only call EndMenu() if BeginMenu() returns true! CIMGUI_API bool ImGui_MenuItem(const char* label); // Implied shortcut = NULL, selected = false, enabled = true CIMGUI_API bool ImGui_MenuItemEx(const char* label, const char* shortcut /* = NULL */, bool selected /* = false */, bool enabled /* = true */); // return true when activated. CIMGUI_API bool ImGui_MenuItemBoolPtr(const char* label, const char* shortcut, bool* p_selected, bool enabled /* = true */); // return true when activated + toggle (*p_selected) if p_selected != NULL // Tooltips // - Tooltips are windows following the mouse. They do not take focus away. // - A tooltip window can contain items of any types. // - SetTooltip() is more or less a shortcut for the 'if (BeginTooltip()) { Text(...); EndTooltip(); }' idiom (with a subtlety that it discard any previously submitted tooltip) CIMGUI_API bool ImGui_BeginTooltip(void); // begin/append a tooltip window. CIMGUI_API void ImGui_EndTooltip(void); // only call EndTooltip() if BeginTooltip()/BeginItemTooltip() returns true! CIMGUI_API void ImGui_SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip. Often used after a ImGui::IsItemHovered() check. Override any previous call to SetTooltip(). CIMGUI_API void ImGui_SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); // Tooltips: helpers for showing a tooltip when hovering an item // - BeginItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_ForTooltip) && BeginTooltip())' idiom. // - SetItemTooltip() is a shortcut for the 'if (IsItemHovered(ImGuiHoveredFlags_ForTooltip)) { SetTooltip(...); }' idiom. // - Where 'ImGuiHoveredFlags_ForTooltip' itself is a shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on active input type. For mouse it defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. CIMGUI_API bool ImGui_BeginItemTooltip(void); // begin/append a tooltip window if preceding item was hovered. CIMGUI_API void ImGui_SetItemTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip if preceding item was hovered. override any previous call to SetTooltip(). CIMGUI_API void ImGui_SetItemTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); // Popups, Modals // - They block normal mouse hovering detection (and therefore most mouse interactions) behind them. // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. // - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls. // - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time. // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. // This is sometimes leading to confusing mistakes. May rework this in the future. // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards if returned true. ImGuiWindowFlags are forwarded to the window. // - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar. CIMGUI_API bool ImGui_BeginPopup(const char* str_id, ImGuiWindowFlags flags /* = 0 */); // return true if the popup is open, and you can start outputting to it. CIMGUI_API bool ImGui_BeginPopupModal(const char* name, bool* p_open /* = NULL */, ImGuiWindowFlags flags /* = 0 */); // return true if the modal is open, and you can start outputting to it. CIMGUI_API void ImGui_EndPopup(void); // only call EndPopup() if BeginPopupXXX() returns true! // Popups: open/close functions // - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options. // - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE. // - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually. // - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options). // - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup(). // - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened. // - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter CIMGUI_API void ImGui_OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags /* = 0 */); // call to mark popup as open (don't call every frame!). CIMGUI_API void ImGui_OpenPopupID(ImGuiID id, ImGuiPopupFlags popup_flags /* = 0 */); // id overload to facilitate calling from nested stacks CIMGUI_API void ImGui_OpenPopupOnItemClick(const char* str_id /* = NULL */, ImGuiPopupFlags popup_flags /* = 1 */); // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors) CIMGUI_API void ImGui_CloseCurrentPopup(void); // manually close the popup we have begin-ed into. // Popups: open+begin combined functions helpers // - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking. // - They are convenient to easily create context menus, hence the name. // - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future. // - IMPORTANT: Notice that we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight. CIMGUI_API bool ImGui_BeginPopupContextItem(void); // Implied str_id = NULL, popup_flags = 1 CIMGUI_API bool ImGui_BeginPopupContextItemEx(const char* str_id /* = NULL */, ImGuiPopupFlags popup_flags /* = 1 */); // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. 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! CIMGUI_API bool ImGui_BeginPopupContextWindow(void); // Implied str_id = NULL, popup_flags = 1 CIMGUI_API bool ImGui_BeginPopupContextWindowEx(const char* str_id /* = NULL */, ImGuiPopupFlags popup_flags /* = 1 */); // open+begin popup when clicked on current window. CIMGUI_API bool ImGui_BeginPopupContextVoid(void); // Implied str_id = NULL, popup_flags = 1 CIMGUI_API bool ImGui_BeginPopupContextVoidEx(const char* str_id /* = NULL */, ImGuiPopupFlags popup_flags /* = 1 */); // open+begin popup when clicked in void (where there are no windows). // Popups: query functions // - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack. // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack. // - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open. CIMGUI_API bool ImGui_IsPopupOpen(const char* str_id, ImGuiPopupFlags flags /* = 0 */); // return true if the popup is open. // Tables // - Full-featured replacement for old Columns API. // - See Demo->Tables for demo code. See top of imgui_tables.cpp for general commentary. // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags. // The typical call flow is: // - 1. Call BeginTable(), early out if returning false. // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults. // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows. // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data. // - 5. Populate contents: // - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column. // - If you are using tables as a sort of grid, where every column is holding the same type of contents, // you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex(). // TableNextColumn() will automatically wrap-around into the next row if needed. // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! // - Summary of possible call flow: // - TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK // - TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK // - TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! // - TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! // - 5. Call EndTable() CIMGUI_API bool ImGui_BeginTable(const char* str_id, int columns, ImGuiTableFlags flags /* = 0 */); // Implied outer_size = ImVec2(0.0f, 0.0f), inner_width = 0.0f CIMGUI_API bool ImGui_BeginTableEx(const char* str_id, int columns, ImGuiTableFlags flags /* = 0 */, ImVec2 outer_size /* = ImVec2(0.0f, 0.0f) */, float inner_width /* = 0.0f */); CIMGUI_API void ImGui_EndTable(void); // only call EndTable() if BeginTable() returns true! CIMGUI_API void ImGui_TableNextRow(void); // Implied row_flags = 0, min_row_height = 0.0f CIMGUI_API void ImGui_TableNextRowEx(ImGuiTableRowFlags row_flags /* = 0 */, float min_row_height /* = 0.0f */); // append into the first cell of a new row. CIMGUI_API bool ImGui_TableNextColumn(void); // append into the next column (or first column of next row if currently in last column). Return true when column is visible. CIMGUI_API bool ImGui_TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible. // Tables: Headers & Columns declaration // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc. // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column. // Headers are required to perform: reordering, sorting, and opening the context menu. // The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody. // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in // some advanced use cases (e.g. adding custom widgets in header row). // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled. CIMGUI_API void ImGui_TableSetupColumn(const char* label, ImGuiTableColumnFlags flags /* = 0 */); // Implied init_width_or_weight = 0.0f, user_id = 0 CIMGUI_API void ImGui_TableSetupColumnEx(const char* label, ImGuiTableColumnFlags flags /* = 0 */, float init_width_or_weight /* = 0.0f */, ImGuiID user_id /* = 0 */); CIMGUI_API void ImGui_TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled. CIMGUI_API void ImGui_TableHeader(const char* label); // submit one header cell manually (rarely used) CIMGUI_API void ImGui_TableHeadersRow(void); // submit a row with headers cells based on data provided to TableSetupColumn() + submit context menu CIMGUI_API void ImGui_TableAngledHeadersRow(void); // submit a row with angled headers for every column with the ImGuiTableColumnFlags_AngledHeader flag. MUST BE FIRST ROW. // Tables: Sorting & Miscellaneous functions // - Sorting: call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting. // When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have // changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, // else you may wastefully sort your data every frame! // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index. CIMGUI_API ImGuiTableSortSpecs* ImGui_TableGetSortSpecs(void); // get latest sort specs for the table (NULL if not sorting). Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable(). CIMGUI_API int ImGui_TableGetColumnCount(void); // return number of columns (value passed to BeginTable) CIMGUI_API int ImGui_TableGetColumnIndex(void); // return current column index. CIMGUI_API int ImGui_TableGetRowIndex(void); // return current row index. CIMGUI_API const char* ImGui_TableGetColumnName(int column_n /* = -1 */); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column. CIMGUI_API ImGuiTableColumnFlags ImGui_TableGetColumnFlags(int column_n /* = -1 */); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column. CIMGUI_API void ImGui_TableSetColumnEnabled(int column_n, bool v); // change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody) CIMGUI_API int ImGui_TableGetHoveredColumn(void); // return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered. Can also use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. CIMGUI_API void ImGui_TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n /* = -1 */); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details. // Legacy Columns API (prefer using Tables!) // - You can also use SameLine(pos_x) to mimic simplified columns. CIMGUI_API void ImGui_Columns(void); // Implied count = 1, id = NULL, borders = true CIMGUI_API void ImGui_ColumnsEx(int count /* = 1 */, const char* id /* = NULL */, bool borders /* = true */); CIMGUI_API void ImGui_NextColumn(void); // next column, defaults to current row or next row if the current row is finished CIMGUI_API int ImGui_GetColumnIndex(void); // get current column index CIMGUI_API float ImGui_GetColumnWidth(int column_index /* = -1 */); // get column width (in pixels). pass -1 to use current column CIMGUI_API void ImGui_SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column CIMGUI_API float ImGui_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 CIMGUI_API void ImGui_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 CIMGUI_API int ImGui_GetColumnsCount(void); // Tab Bars, Tabs // - Note: Tabs are automatically created by the docking system (when in 'docking' branch). Use this to create tab bars/tabs yourself. CIMGUI_API bool ImGui_BeginTabBar(const char* str_id, ImGuiTabBarFlags flags /* = 0 */); // create and append into a TabBar CIMGUI_API void ImGui_EndTabBar(void); // only call EndTabBar() if BeginTabBar() returns true! CIMGUI_API bool ImGui_BeginTabItem(const char* label, bool* p_open /* = NULL */, ImGuiTabItemFlags flags /* = 0 */); // create a Tab. Returns true if the Tab is selected. CIMGUI_API void ImGui_EndTabItem(void); // only call EndTabItem() if BeginTabItem() returns true! CIMGUI_API bool ImGui_TabItemButton(const char* label, ImGuiTabItemFlags flags /* = 0 */); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar. CIMGUI_API void ImGui_SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. // Logging/Capture // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. CIMGUI_API void ImGui_LogToTTY(int auto_open_depth /* = -1 */); // start logging to tty (stdout) CIMGUI_API void ImGui_LogToFile(int auto_open_depth /* = -1 */, const char* filename /* = NULL */); // start logging to file CIMGUI_API void ImGui_LogToClipboard(int auto_open_depth /* = -1 */); // start logging to OS clipboard CIMGUI_API void ImGui_LogFinish(void); // stop logging (close file, etc.) CIMGUI_API void ImGui_LogButtons(void); // helper to display buttons for logging to tty/file/clipboard CIMGUI_API void ImGui_LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) CIMGUI_API void ImGui_LogTextV(const char* fmt, va_list args) IM_FMTLIST(1); // Drag and Drop // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource(). // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget(). // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725) // - An item can be both drag source and drop target. CIMGUI_API bool ImGui_BeginDragDropSource(ImGuiDragDropFlags flags /* = 0 */); // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource() CIMGUI_API bool ImGui_SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond /* = 0 */); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted. CIMGUI_API void ImGui_EndDragDropSource(void); // only call EndDragDropSource() if BeginDragDropSource() returns true! CIMGUI_API bool ImGui_BeginDragDropTarget(void); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() CIMGUI_API const ImGuiPayload* ImGui_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. CIMGUI_API void ImGui_EndDragDropTarget(void); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! CIMGUI_API const ImGuiPayload* ImGui_GetDragDropPayload(void); // peek directly into the current payload from anywhere. returns NULL when drag and drop is finished or inactive. use ImGuiPayload::IsDataType() to test for the payload type. // Disabling [BETA API] // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) // - Tooltips windows by exception are opted out of disabling. // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it. CIMGUI_API void ImGui_BeginDisabled(bool disabled /* = true */); CIMGUI_API void ImGui_EndDisabled(void); // Clipping // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only. CIMGUI_API void ImGui_PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect); CIMGUI_API void ImGui_PopClipRect(void); // Focus, Activation // - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item" CIMGUI_API void ImGui_SetItemDefaultFocus(void); // make last item the default focused item of a window. CIMGUI_API void ImGui_SetKeyboardFocusHere(void); // Implied offset = 0 CIMGUI_API void ImGui_SetKeyboardFocusHereEx(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. // Overlapping mode CIMGUI_API void ImGui_SetNextItemAllowOverlap(void); // allow next item to be overlapped by a subsequent item. Useful with invisible buttons, selectable, treenode covering an area where subsequent items may need to be added. Note that both Selectable() and TreeNode() have dedicated flags doing this. // Item/Widgets Utilities and Query Functions // - Most of the functions are referring to the previous Item that has been submitted. // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions. CIMGUI_API bool ImGui_IsItemHovered(ImGuiHoveredFlags flags /* = 0 */); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. CIMGUI_API bool ImGui_IsItemActive(void); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) CIMGUI_API bool ImGui_IsItemFocused(void); // is the last item focused for keyboard/gamepad navigation? CIMGUI_API bool ImGui_IsItemClicked(void); // Implied mouse_button = 0 CIMGUI_API bool ImGui_IsItemClickedEx(ImGuiMouseButton mouse_button /* = 0 */); // is the last item hovered and mouse clicked on? (**) == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this is NOT equivalent to the behavior of e.g. Button(). Read comments in function definition. CIMGUI_API bool ImGui_IsItemVisible(void); // is the last item visible? (items may be out of sight because of clipping/scrolling) CIMGUI_API bool ImGui_IsItemEdited(void); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. CIMGUI_API bool ImGui_IsItemActivated(void); // was the last item just made active (item was previously inactive). CIMGUI_API bool ImGui_IsItemDeactivated(void); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that require continuous editing. CIMGUI_API bool ImGui_IsItemDeactivatedAfterEdit(void); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that require continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). CIMGUI_API bool ImGui_IsItemToggledOpen(void); // was the last item open state toggled? set by TreeNode(). CIMGUI_API bool ImGui_IsAnyItemHovered(void); // is any item hovered? CIMGUI_API bool ImGui_IsAnyItemActive(void); // is any item active? CIMGUI_API bool ImGui_IsAnyItemFocused(void); // is any item focused? CIMGUI_API ImGuiID ImGui_GetItemID(void); // get ID of last item (~~ often same ImGui::GetID(label) beforehand) CIMGUI_API ImVec2 ImGui_GetItemRectMin(void); // get upper-left bounding rectangle of the last item (screen space) CIMGUI_API ImVec2 ImGui_GetItemRectMax(void); // get lower-right bounding rectangle of the last item (screen space) CIMGUI_API ImVec2 ImGui_GetItemRectSize(void); // get size of last item // Viewports // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. CIMGUI_API ImGuiViewport* ImGui_GetMainViewport(void); // return primary/default viewport. This can never be NULL. // Background/Foreground Draw Lists CIMGUI_API ImDrawList* ImGui_GetBackgroundDrawList(void); // this draw list will be the first rendered one. Useful to quickly draw shapes/text behind dear imgui contents. CIMGUI_API ImDrawList* ImGui_GetForegroundDrawList(void); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents. // Miscellaneous Utilities CIMGUI_API bool ImGui_IsRectVisibleBySize(ImVec2 size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. CIMGUI_API bool ImGui_IsRectVisible(ImVec2 rect_min, ImVec2 rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. CIMGUI_API double ImGui_GetTime(void); // get global imgui time. incremented by io.DeltaTime every frame. CIMGUI_API int ImGui_GetFrameCount(void); // get global imgui frame count. incremented by 1 every frame. CIMGUI_API ImDrawListSharedData* ImGui_GetDrawListSharedData(void); // you may use this when creating your own ImDrawList instances. CIMGUI_API const char* ImGui_GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.). CIMGUI_API void ImGui_SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) CIMGUI_API ImGuiStorage* ImGui_GetStateStorage(void); // Text Utilities CIMGUI_API ImVec2 ImGui_CalcTextSize(const char* text); // Implied text_end = NULL, hide_text_after_double_hash = false, wrap_width = -1.0f CIMGUI_API ImVec2 ImGui_CalcTextSizeEx(const char* text, const char* text_end /* = NULL */, bool hide_text_after_double_hash /* = false */, float wrap_width /* = -1.0f */); // Color Utilities CIMGUI_API ImVec4 ImGui_ColorConvertU32ToFloat4(ImU32 in); CIMGUI_API ImU32 ImGui_ColorConvertFloat4ToU32(ImVec4 in); CIMGUI_API void ImGui_ColorConvertRGBtoHSV(float r, float g, float b, float* out_h, float* out_s, float* out_v); CIMGUI_API void ImGui_ColorConvertHSVtoRGB(float h, float s, float v, float* out_r, float* out_g, float* out_b); // Inputs Utilities: Keyboard/Mouse/Gamepad // - the ImGuiKey enum contains all possible keyboard, mouse and gamepad inputs (e.g. ImGuiKey_A, ImGuiKey_MouseLeft, ImGuiKey_GamepadDpadUp...). // - before v1.87, we used ImGuiKey to carry native/user indices as defined by each backends. About use of those legacy ImGuiKey values: // - without IMGUI_DISABLE_OBSOLETE_KEYIO (legacy support): you can still use your legacy native/user indices (< 512) according to how your backend/engine stored them in io.KeysDown[], but need to cast them to ImGuiKey. // - with IMGUI_DISABLE_OBSOLETE_KEYIO (this is the way forward): any use of ImGuiKey will assert with key < 512. GetKeyIndex() is pass-through and therefore deprecated (gone if IMGUI_DISABLE_OBSOLETE_KEYIO is defined). CIMGUI_API bool ImGui_IsKeyDown(ImGuiKey key); // is key being held. CIMGUI_API bool ImGui_IsKeyPressed(ImGuiKey key); // Implied repeat = true CIMGUI_API bool ImGui_IsKeyPressedEx(ImGuiKey key, bool repeat /* = true */); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate CIMGUI_API bool ImGui_IsKeyReleased(ImGuiKey key); // was key released (went from Down to !Down)? CIMGUI_API bool ImGui_IsKeyChordPressed(ImGuiKeyChord key_chord); // was key chord (mods + key) pressed, e.g. you can pass 'ImGuiMod_Ctrl | ImGuiKey_S' as a key-chord. This doesn't do any routing or focus check, please consider using Shortcut() function instead. CIMGUI_API int ImGui_GetKeyPressedAmount(ImGuiKey key, 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 CIMGUI_API const char* ImGui_GetKeyName(ImGuiKey key); // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared. CIMGUI_API void ImGui_SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard); // Override io.WantCaptureKeyboard flag next frame (said flag is left for your application to handle, typically when true it instructs your app to ignore inputs). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard"; after the next NewFrame() call. // Inputs Utilities: Shortcut Testing & Routing [BETA] // - ImGuiKeyChord = a ImGuiKey + optional ImGuiMod_Alt/ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Super. // ImGuiKey_C // Accepted by functions taking ImGuiKey or ImGuiKeyChord arguments) // ImGuiMod_Ctrl | ImGuiKey_C // Accepted by functions taking ImGuiKeyChord arguments) // only ImGuiMod_XXX values are legal to combine with an ImGuiKey. You CANNOT combine two ImGuiKey values. // - The general idea is that several callers may register interest in a shortcut, and only one owner gets it. // Parent -> call Shortcut(Ctrl+S) // When Parent is focused, Parent gets the shortcut. // Child1 -> call Shortcut(Ctrl+S) // When Child1 is focused, Child1 gets the shortcut (Child1 overrides Parent shortcuts) // Child2 -> no call // When Child2 is focused, Parent gets the shortcut. // The whole system is order independent, so if Child1 makes its calls before Parent, results will be identical. // This is an important property as it facilitate working with foreign code or larger codebase. // - To understand the difference: // - IsKeyChordPressed() compares mods and call IsKeyPressed() -> function has no side-effect. // - Shortcut() submits a route, routes are resolved, if it currently can be routed it calls IsKeyChordPressed() -> function has (desirable) side-effects as it can prevents another call from getting the route. // - Visualize registered routes in 'Metrics/Debugger->Inputs'. CIMGUI_API bool ImGui_Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags /* = 0 */); CIMGUI_API void ImGui_SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags /* = 0 */); // Inputs Utilities: Key/Input Ownership [BETA] // - One common use case would be to allow your items to disable standard inputs behaviors such // as Tab or Alt key handling, Mouse Wheel scrolling, etc. // e.g. Button(...); SetItemKeyOwner(ImGuiKey_MouseWheelY); to make hovering/activating a button disable wheel for scrolling. // - Reminder ImGuiKey enum include access to mouse buttons and gamepad, so key ownership can apply to them. // - Many related features are still in imgui_internal.h. For instance, most IsKeyXXX()/IsMouseXXX() functions have an owner-id-aware version. CIMGUI_API void ImGui_SetItemKeyOwner(ImGuiKey key); // Set key owner to last item ID if it is hovered or active. Equivalent to 'if (IsItemHovered() || IsItemActive()) { SetKeyOwner(key, GetItemID());'. // Inputs Utilities: Mouse specific // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right. // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle. // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold') CIMGUI_API bool ImGui_IsMouseDown(ImGuiMouseButton button); // is mouse button held? CIMGUI_API bool ImGui_IsMouseClicked(ImGuiMouseButton button); // Implied repeat = false CIMGUI_API bool ImGui_IsMouseClickedEx(ImGuiMouseButton button, bool repeat /* = false */); // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1. CIMGUI_API bool ImGui_IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down) CIMGUI_API bool ImGui_IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true) CIMGUI_API int ImGui_GetMouseClickedCount(ImGuiMouseButton button); // return the number of successive mouse-clicks at the time where a click happen (otherwise 0). CIMGUI_API bool ImGui_IsMouseHoveringRect(ImVec2 r_min, ImVec2 r_max); // Implied clip = true CIMGUI_API bool ImGui_IsMouseHoveringRectEx(ImVec2 r_min, ImVec2 r_max, bool clip /* = true */); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. CIMGUI_API bool ImGui_IsMousePosValid(const ImVec2* mouse_pos /* = NULL */); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available CIMGUI_API bool ImGui_IsAnyMouseDown(void); // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. CIMGUI_API ImVec2 ImGui_GetMousePos(void); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls CIMGUI_API ImVec2 ImGui_GetMousePosOnOpeningCurrentPopup(void); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves) CIMGUI_API bool ImGui_IsMouseDragging(ImGuiMouseButton button, float lock_threshold /* = -1.0f */); // is mouse dragging? (uses io.MouseDraggingThreshold if lock_threshold < 0.0f) CIMGUI_API ImVec2 ImGui_GetMouseDragDelta(ImGuiMouseButton button /* = 0 */, float lock_threshold /* = -1.0f */); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (uses io.MouseDraggingThreshold if lock_threshold < 0.0f) CIMGUI_API void ImGui_ResetMouseDragDelta(void); // Implied button = 0 CIMGUI_API void ImGui_ResetMouseDragDeltaEx(ImGuiMouseButton button /* = 0 */); // CIMGUI_API ImGuiMouseCursor ImGui_GetMouseCursor(void); // get desired mouse cursor shape. Important: reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you CIMGUI_API void ImGui_SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired mouse cursor shape CIMGUI_API void ImGui_SetNextFrameWantCaptureMouse(bool want_capture_mouse); // Override io.WantCaptureMouse flag next frame (said flag is left for your application to handle, typical when true it instucts your app to ignore inputs). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse;" after the next NewFrame() call. // Clipboard Utilities // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard. CIMGUI_API const char* ImGui_GetClipboardText(void); CIMGUI_API void ImGui_SetClipboardText(const char* text); // Settings/.Ini Utilities // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. // - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables). CIMGUI_API void ImGui_LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). CIMGUI_API void ImGui_LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size /* = 0 */); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. CIMGUI_API void ImGui_SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext). CIMGUI_API const char* ImGui_SaveIniSettingsToMemory(size_t* out_ini_size /* = NULL */); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. // Debug Utilities // - Your main debugging friend is the ShowMetricsWindow() function, which is also accessible from Demo->Tools->Metrics Debugger CIMGUI_API void ImGui_DebugTextEncoding(const char* text); CIMGUI_API void ImGui_DebugFlashStyleColor(ImGuiCol idx); CIMGUI_API void ImGui_DebugStartItemPicker(void); CIMGUI_API bool ImGui_DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. #ifndef IMGUI_DISABLE_DEBUG_TOOLS CIMGUI_API void ImGui_DebugLog(const char* fmt, ...) IM_FMTARGS(1); // Call via IMGUI_DEBUG_LOG() for maximum stripping in caller code! CIMGUI_API void ImGui_DebugLogV(const char* fmt, va_list args) IM_FMTLIST(1); #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS // Memory Allocators // - Those functions are not reliant on the current context. // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. CIMGUI_API void ImGui_SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data /* = NULL */); CIMGUI_API void ImGui_GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data); CIMGUI_API void* ImGui_MemAlloc(size_t size); CIMGUI_API void ImGui_MemFree(void* ptr); //----------------------------------------------------------------------------- // [SECTION] Flags & Enumerations //----------------------------------------------------------------------------- // Flags for ImGui::Begin() // (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) typedef enum { ImGuiWindowFlags_None = 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 programmatically) 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. Also referred to as Window Menu Button (e.g. within a docking node). ImGuiWindowFlags_AlwaysAutoResize = 1<<6, // Resize every window to its content every frame ImGuiWindowFlags_NoBackground = 1<<7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). ImGuiWindowFlags_NoSavedSettings = 1<<8, // Never load/save settings in .ini file ImGuiWindowFlags_NoMouseInputs = 1<<9, // Disable catching mouse, 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 ImGuiWindowFlags_NoBringToFrontOnFocus = 1<<13, // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) 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_NoNavInputs = 1<<16, // No gamepad/keyboard navigation within the window ImGuiWindowFlags_NoNavFocus = 1<<17, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) ImGuiWindowFlags_UnsavedDocument = 1<<18, // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, // [Internal] 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() // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiWindowFlags_AlwaysUseWindowPadding = 1<<30, // Obsoleted in 1.90.0: Use ImGuiChildFlags_AlwaysUseWindowPadding in BeginChild() call. ImGuiWindowFlags_NavFlattened = 1<<31, // Obsoleted in 1.90.9: Use ImGuiChildFlags_NavFlattened in BeginChild() call. #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS } ImGuiWindowFlags_; // Flags for ImGui::BeginChild() // (Legacy: bit 0 must always correspond to ImGuiChildFlags_Borders to be backward compatible with old API using 'bool border = false'. // About using AutoResizeX/AutoResizeY flags: // - May be combined with SetNextWindowSizeConstraints() to set a min/max size for each axis (see "Demo->Child->Auto-resize with Constraints"). // - Size measurement for a given axis is only performed when the child window is within visible boundaries, or is just appearing. // - This allows BeginChild() to return false when not within boundaries (e.g. when scrolling), which is more optimal. BUT it won't update its auto-size while clipped. // While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional "resizing after becoming visible again" glitch. // - You may also use ImGuiChildFlags_AlwaysAutoResize to force an update even when child window is not in view. // HOWEVER PLEASE UNDERSTAND THAT DOING SO WILL PREVENT BeginChild() FROM EVER RETURNING FALSE, disabling benefits of coarse clipping. typedef enum { ImGuiChildFlags_None = 0, ImGuiChildFlags_Borders = 1<<0, // Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) ImGuiChildFlags_AlwaysUseWindowPadding = 1<<1, // Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) ImGuiChildFlags_ResizeX = 1<<2, // Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags_NoSavedSettings passed to window flags) ImGuiChildFlags_ResizeY = 1<<3, // Allow resize from bottom border (layout direction). " ImGuiChildFlags_AutoResizeX = 1<<4, // Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. ImGuiChildFlags_AutoResizeY = 1<<5, // Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. ImGuiChildFlags_AlwaysAutoResize = 1<<6, // Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. ImGuiChildFlags_FrameStyle = 1<<7, // Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. ImGuiChildFlags_NavFlattened = 1<<8, // [BETA] Share focus scope, allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows. // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiChildFlags_Border = ImGuiChildFlags_Borders, // Renamed in 1.91.1 (August 2024) for consistency. #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS } ImGuiChildFlags_; // Flags for ImGui::PushItemFlag() // (Those are shared by all items) typedef enum { ImGuiItemFlags_None = 0, // (Default) ImGuiItemFlags_NoTabStop = 1<<0, // false // Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags_NoNav. ImGuiItemFlags_NoNav = 1<<1, // false // Disable any form of focusing (keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls). ImGuiItemFlags_NoNavDefaultFocus = 1<<2, // false // Disable item being a candidate for default focus (e.g. used by title bar items). ImGuiItemFlags_ButtonRepeat = 1<<3, // false // Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. ImGuiItemFlags_AutoClosePopups = 1<<4, // true // MenuItem()/Selectable() automatically close their parent popup window. } ImGuiItemFlags_; // Flags for ImGui::InputText() // (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) typedef enum { // Basic filters (also see ImGuiInputTextFlags_CallbackCharFilter) ImGuiInputTextFlags_None = 0, ImGuiInputTextFlags_CharsDecimal = 1<<0, // Allow 0123456789.+-*/ ImGuiInputTextFlags_CharsHexadecimal = 1<<1, // Allow 0123456789ABCDEFabcdef ImGuiInputTextFlags_CharsScientific = 1<<2, // Allow 0123456789.+-*/eE (Scientific notation input) ImGuiInputTextFlags_CharsUppercase = 1<<3, // Turn a..z into A..Z ImGuiInputTextFlags_CharsNoBlank = 1<<4, // Filter out spaces, tabs // Inputs ImGuiInputTextFlags_AllowTabInput = 1<<5, // Pressing TAB input a '\t' character into the text field ImGuiInputTextFlags_EnterReturnsTrue = 1<<6, // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function. ImGuiInputTextFlags_EscapeClearsAll = 1<<7, // Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) ImGuiInputTextFlags_CtrlEnterForNewLine = 1<<8, // In multi-line mode, validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). // Other options ImGuiInputTextFlags_ReadOnly = 1<<9, // Read-only mode ImGuiInputTextFlags_Password = 1<<10, // Password mode, display all characters as '*', disable copy ImGuiInputTextFlags_AlwaysOverwrite = 1<<11, // Overwrite mode ImGuiInputTextFlags_AutoSelectAll = 1<<12, // Select entire text when first taking mouse focus ImGuiInputTextFlags_ParseEmptyRefVal = 1<<13, // InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. ImGuiInputTextFlags_DisplayEmptyRefVal = 1<<14, // InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags_ParseEmptyRefVal. ImGuiInputTextFlags_NoHorizontalScroll = 1<<15, // Disable following the cursor horizontally 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(). // Callback features ImGuiInputTextFlags_CallbackCompletion = 1<<17, // Callback on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1<<18, // Callback on pressing Up/Down arrows (for history handling) ImGuiInputTextFlags_CallbackAlways = 1<<19, // Callback on each iteration. User code may query cursor position, modify text buffer. ImGuiInputTextFlags_CallbackCharFilter = 1<<20, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. ImGuiInputTextFlags_CallbackResize = 1<<21, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) ImGuiInputTextFlags_CallbackEdit = 1<<22, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) // Obsolete names //ImGuiInputTextFlags_AlwaysInsertMode = ImGuiInputTextFlags_AlwaysOverwrite // [renamed in 1.82] name was not matching behavior } ImGuiInputTextFlags_; // Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() typedef enum { ImGuiTreeNodeFlags_None = 0, ImGuiTreeNodeFlags_Selected = 1<<0, // Draw as selected ImGuiTreeNodeFlags_Framed = 1<<1, // Draw frame with background (e.g. for CollapsingHeader) ImGuiTreeNodeFlags_AllowOverlap = 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 ImGuiTreeNodeFlags_OpenOnDoubleClick = 1<<6, // Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. ImGuiTreeNodeFlags_OpenOnArrow = 1<<7, // Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. 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. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! 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() before the node. ImGuiTreeNodeFlags_SpanAvailWidth = 1<<11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line without using AllowOverlap mode. ImGuiTreeNodeFlags_SpanFullWidth = 1<<12, // Extend hit box to the left-most and right-most edges (cover the indent area). ImGuiTreeNodeFlags_SpanTextWidth = 1<<13, // Narrow hit box + narrow hovering highlight, will only cover the label text. ImGuiTreeNodeFlags_SpanAllColumns = 1<<14, // Frame will span all columns of its container table (text will still fit in current column) ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1<<15, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 16, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiTreeNodeFlags_AllowItemOverlap = ImGuiTreeNodeFlags_AllowOverlap, // Renamed in 1.89.7 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS } ImGuiTreeNodeFlags_; // Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. // - To be backward compatible with older API which took an 'int mouse_button = 1' argument instead of 'ImGuiPopupFlags flags', // we need to treat small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags. // It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags. // - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0. // IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter // and want to use another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag explicitly. // - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). typedef enum { ImGuiPopupFlags_None = 0, ImGuiPopupFlags_MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left) ImGuiPopupFlags_MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right) ImGuiPopupFlags_MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle) ImGuiPopupFlags_MouseButtonMask_ = 0x1F, ImGuiPopupFlags_MouseButtonDefault_ = 1, ImGuiPopupFlags_NoReopen = 1<<5, // For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) //ImGuiPopupFlags_NoReopenAlwaysNavInit = 1 << 6, // For OpenPopup*(), BeginPopupContext*(): focus and initialize navigation even when not reopening. ImGuiPopupFlags_NoOpenOverExistingPopup = 1<<7, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack ImGuiPopupFlags_NoOpenOverItems = 1<<8, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space ImGuiPopupFlags_AnyPopupId = 1<<10, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. ImGuiPopupFlags_AnyPopupLevel = 1<<11, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) ImGuiPopupFlags_AnyPopup = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel, } ImGuiPopupFlags_; // Flags for ImGui::Selectable() typedef enum { ImGuiSelectableFlags_None = 0, ImGuiSelectableFlags_NoAutoClosePopups = 1<<0, // Clicking this doesn't close parent popup window (overrides ImGuiItemFlags_AutoClosePopups) ImGuiSelectableFlags_SpanAllColumns = 1<<1, // Frame will span all columns of its container table (text will still fit in current column) ImGuiSelectableFlags_AllowDoubleClick = 1<<2, // Generate press events on double clicks too ImGuiSelectableFlags_Disabled = 1<<3, // Cannot be selected, display grayed out text ImGuiSelectableFlags_AllowOverlap = 1<<4, // (WIP) Hit testing to allow subsequent widgets to overlap this one ImGuiSelectableFlags_Highlight = 1<<5, // Make the item be displayed as if it is hovered #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS } ImGuiSelectableFlags_; // Flags for ImGui::BeginCombo() typedef enum { ImGuiComboFlags_None = 0, 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_NoArrowButton = 1<<5, // Display on the preview box without the square arrow button ImGuiComboFlags_NoPreview = 1<<6, // Display only a square arrow button ImGuiComboFlags_WidthFitPreview = 1<<7, // Width dynamically calculated from preview contents ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest, } ImGuiComboFlags_; // Flags for ImGui::BeginTabBar() typedef enum { ImGuiTabBarFlags_None = 0, ImGuiTabBarFlags_Reorderable = 1<<0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list ImGuiTabBarFlags_AutoSelectNewTabs = 1<<1, // Automatically select new tabs when they appear ImGuiTabBarFlags_TabListPopupButton = 1<<2, // Disable buttons to open the tab list popup ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1<<3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabBarFlags_NoTabListScrollingButtons = 1<<4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) ImGuiTabBarFlags_NoTooltip = 1<<5, // Disable tooltips when hovering a tab ImGuiTabBarFlags_DrawSelectedOverline = 1<<6, // Draw selected overline markers over selected tab ImGuiTabBarFlags_FittingPolicyResizeDown = 1<<7, // Resize tabs when they don't fit ImGuiTabBarFlags_FittingPolicyScroll = 1<<8, // Add scroll buttons when tabs don't fit ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown, } ImGuiTabBarFlags_; // Flags for ImGui::BeginTabItem() typedef enum { ImGuiTabItemFlags_None = 0, ImGuiTabItemFlags_UnsavedDocument = 1<<0, // Display a dot next to the title + set ImGuiTabItemFlags_NoAssumedClosure. ImGuiTabItemFlags_SetSelected = 1<<1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1<<2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabItemFlags_NoPushId = 1<<3, // Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() ImGuiTabItemFlags_NoTooltip = 1<<4, // Disable tooltip for the given tab ImGuiTabItemFlags_NoReorder = 1<<5, // Disable reordering this tab or having another tab cross over this tab ImGuiTabItemFlags_Leading = 1<<6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) ImGuiTabItemFlags_Trailing = 1<<7, // Enforce the tab position to the right of the tab bar (before the scrolling buttons) ImGuiTabItemFlags_NoAssumedClosure = 1<<8, // Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. } ImGuiTabItemFlags_; // Flags for ImGui::IsWindowFocused() typedef enum { ImGuiFocusedFlags_None = 0, ImGuiFocusedFlags_ChildWindows = 1<<0, // Return true if any children of the window is focused ImGuiFocusedFlags_RootWindow = 1<<1, // Test from root window (top most parent of the current hierarchy) ImGuiFocusedFlags_AnyWindow = 1<<2, // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! ImGuiFocusedFlags_NoPopupHierarchy = 1<<3, // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) //ImGuiFocusedFlags_DockHierarchy = 1 << 4, // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows, } ImGuiFocusedFlags_; // Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() // Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! // Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. typedef enum { ImGuiHoveredFlags_None = 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_NoPopupHierarchy = 1<<3, // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) //ImGuiHoveredFlags_DockHierarchy = 1 << 4, // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1<<5, // Return true even if a popup window is normally blocking access to this item/window //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 6, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1<<7, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. ImGuiHoveredFlags_AllowWhenOverlappedByItem = 1<<8, // IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. ImGuiHoveredFlags_AllowWhenOverlappedByWindow = 1<<9, // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. ImGuiHoveredFlags_AllowWhenDisabled = 1<<10, // IsItemHovered() only: Return true even if the item is disabled ImGuiHoveredFlags_NoNavOverride = 1<<11, // IsItemHovered() only: Disable using gamepad/keyboard navigation state when active, always query mouse ImGuiHoveredFlags_AllowWhenOverlapped = ImGuiHoveredFlags_AllowWhenOverlappedByItem | ImGuiHoveredFlags_AllowWhenOverlappedByWindow, ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows, // Tooltips mode // - typically used in IsItemHovered() + SetTooltip() sequence. // - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. // e.g. 'TooltipHoveredFlagsForMouse' defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort'. // - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags_ForTooltip (stationary + delay) so the tooltip doesn't show too often. // - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. ImGuiHoveredFlags_ForTooltip = 1<<12, // Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. // (Advanced) Mouse Hovering delays. // - generally you can use ImGuiHoveredFlags_ForTooltip to use application-standardized flags. // - use those if you need specific overrides. ImGuiHoveredFlags_Stationary = 1<<13, // Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. ImGuiHoveredFlags_DelayNone = 1<<14, // IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. ImGuiHoveredFlags_DelayShort = 1<<15, // IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). ImGuiHoveredFlags_DelayNormal = 1<<16, // IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). ImGuiHoveredFlags_NoSharedDelay = 1<<17, // IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) } ImGuiHoveredFlags_; // Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() typedef enum { ImGuiDragDropFlags_None = 0, // BeginDragDropSource() flags ImGuiDragDropFlags_SourceNoPreviewTooltip = 1<<0, // Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. ImGuiDragDropFlags_SourceNoDisableHover = 1<<1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables 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 dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. ImGuiDragDropFlags_PayloadAutoExpire = 1<<5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) ImGuiDragDropFlags_PayloadNoCrossContext = 1<<6, // Hint to specify that the payload may not be copied outside current dear imgui context. ImGuiDragDropFlags_PayloadNoCrossProcess = 1<<7, // Hint to specify that the payload may not be copied outside current process. // 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_AcceptNoPreviewTooltip = 1<<12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiDragDropFlags_SourceAutoExpirePayload = ImGuiDragDropFlags_PayloadAutoExpire, // Renamed in 1.90.9 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS } ImGuiDragDropFlags_; // Standard Drag and Drop payload types. You can define you own payload types using short 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. // A primary data type typedef enum { ImGuiDataType_S8, // signed char / char (with sensible compilers) ImGuiDataType_U8, // unsigned char ImGuiDataType_S16, // short ImGuiDataType_U16, // unsigned short ImGuiDataType_S32, // int ImGuiDataType_U32, // unsigned int ImGuiDataType_S64, // long long / __int64 ImGuiDataType_U64, // unsigned long long / unsigned __int64 ImGuiDataType_Float, // float ImGuiDataType_Double, // double ImGuiDataType_Bool, // bool (provided for user convenience, not supported by scalar widgets) ImGuiDataType_COUNT, } ImGuiDataType_; // A cardinal direction enum // Forward declared enum type ImGuiDir { ImGuiDir_None = -1, ImGuiDir_Left = 0, ImGuiDir_Right = 1, ImGuiDir_Up = 2, ImGuiDir_Down = 3, ImGuiDir_COUNT, }; // A sorting direction enum // Forward declared enum type ImGuiSortDirection { ImGuiSortDirection_None = 0, ImGuiSortDirection_Ascending = 1, // Ascending = 0->9, A->Z etc. ImGuiSortDirection_Descending = 2, // Descending = 9->0, Z->A etc. }; // Since 1.90, defining IMGUI_DISABLE_OBSOLETE_FUNCTIONS automatically defines IMGUI_DISABLE_OBSOLETE_KEYIO as well. #if defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS)&&!defined(IMGUI_DISABLE_OBSOLETE_KEYIO) #define IMGUI_DISABLE_OBSOLETE_KEYIO #endif // #if defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS)&&!defined(IMGUI_DISABLE_OBSOLETE_KEYIO) // A key identifier (ImGuiKey_XXX or ImGuiMod_XXX value): can represent Keyboard, Mouse and Gamepad values. // All our named keys are >= 512. Keys value 0 to 511 are left unused as legacy native/opaque key values (< 1.87). // Since >= 1.89 we increased typing (went from int to enum), some legacy code may need a cast to ImGuiKey. // Read details about the 1.87 and 1.89 transition : https://github.com/ocornut/imgui/issues/4921 // Note that "Keys" related to physical keys and are not the same concept as input "Characters", the later are submitted via io.AddInputCharacter(). // The keyboard key enum values are named after the keys on a standard US keyboard, and on other keyboard types the keys reported may not match the keycaps. enum // Forward declared enum type ImGuiKey { // Keyboard ImGuiKey_None = 0, ImGuiKey_Tab = 512, // == ImGuiKey_NamedKey_BEGIN ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow, ImGuiKey_PageUp, ImGuiKey_PageDown, ImGuiKey_Home, ImGuiKey_End, ImGuiKey_Insert, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper, ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper, ImGuiKey_Menu, ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9, ImGuiKey_A, ImGuiKey_B, ImGuiKey_C, ImGuiKey_D, ImGuiKey_E, ImGuiKey_F, ImGuiKey_G, ImGuiKey_H, ImGuiKey_I, ImGuiKey_J, ImGuiKey_K, ImGuiKey_L, ImGuiKey_M, ImGuiKey_N, ImGuiKey_O, ImGuiKey_P, ImGuiKey_Q, ImGuiKey_R, ImGuiKey_S, ImGuiKey_T, ImGuiKey_U, ImGuiKey_V, ImGuiKey_W, ImGuiKey_X, ImGuiKey_Y, ImGuiKey_Z, ImGuiKey_F1, ImGuiKey_F2, ImGuiKey_F3, ImGuiKey_F4, ImGuiKey_F5, ImGuiKey_F6, ImGuiKey_F7, ImGuiKey_F8, ImGuiKey_F9, ImGuiKey_F10, ImGuiKey_F11, ImGuiKey_F12, ImGuiKey_F13, ImGuiKey_F14, ImGuiKey_F15, ImGuiKey_F16, ImGuiKey_F17, ImGuiKey_F18, ImGuiKey_F19, ImGuiKey_F20, ImGuiKey_F21, ImGuiKey_F22, ImGuiKey_F23, ImGuiKey_F24, ImGuiKey_Apostrophe, // ' ImGuiKey_Comma, // , ImGuiKey_Minus, // - ImGuiKey_Period, // . ImGuiKey_Slash, // / ImGuiKey_Semicolon, // ; ImGuiKey_Equal, // = ImGuiKey_LeftBracket, // [ ImGuiKey_Backslash, // \ (this text inhibit multiline comment caused by backslash) ImGuiKey_RightBracket, // ] ImGuiKey_GraveAccent, // ` ImGuiKey_CapsLock, ImGuiKey_ScrollLock, ImGuiKey_NumLock, ImGuiKey_PrintScreen, ImGuiKey_Pause, ImGuiKey_Keypad0, ImGuiKey_Keypad1, ImGuiKey_Keypad2, ImGuiKey_Keypad3, ImGuiKey_Keypad4, ImGuiKey_Keypad5, ImGuiKey_Keypad6, ImGuiKey_Keypad7, ImGuiKey_Keypad8, ImGuiKey_Keypad9, ImGuiKey_KeypadDecimal, ImGuiKey_KeypadDivide, ImGuiKey_KeypadMultiply, ImGuiKey_KeypadSubtract, ImGuiKey_KeypadAdd, ImGuiKey_KeypadEnter, ImGuiKey_KeypadEqual, ImGuiKey_AppBack, // Available on some keyboard/mouses. Often referred as "Browser Back" ImGuiKey_AppForward, // Gamepad (some of those are analog values, 0.0f to 1.0f) // NAVIGATION ACTION // (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) ImGuiKey_GamepadStart, // Menu (Xbox) + (Switch) Start/Options (PS) ImGuiKey_GamepadBack, // View (Xbox) - (Switch) Share (PS) ImGuiKey_GamepadFaceLeft, // X (Xbox) Y (Switch) Square (PS) // Tap: Toggle Menu. Hold: Windowing mode (Focus/Move/Resize windows) ImGuiKey_GamepadFaceRight, // B (Xbox) A (Switch) Circle (PS) // Cancel / Close / Exit ImGuiKey_GamepadFaceUp, // Y (Xbox) X (Switch) Triangle (PS) // Text Input / On-screen Keyboard ImGuiKey_GamepadFaceDown, // A (Xbox) B (Switch) Cross (PS) // Activate / Open / Toggle / Tweak ImGuiKey_GamepadDpadLeft, // D-pad Left // Move / Tweak / Resize Window (in Windowing mode) ImGuiKey_GamepadDpadRight, // D-pad Right // Move / Tweak / Resize Window (in Windowing mode) ImGuiKey_GamepadDpadUp, // D-pad Up // Move / Tweak / Resize Window (in Windowing mode) ImGuiKey_GamepadDpadDown, // D-pad Down // Move / Tweak / Resize Window (in Windowing mode) ImGuiKey_GamepadL1, // L Bumper (Xbox) L (Switch) L1 (PS) // Tweak Slower / Focus Previous (in Windowing mode) ImGuiKey_GamepadR1, // R Bumper (Xbox) R (Switch) R1 (PS) // Tweak Faster / Focus Next (in Windowing mode) ImGuiKey_GamepadL2, // L Trig. (Xbox) ZL (Switch) L2 (PS) [Analog] ImGuiKey_GamepadR2, // R Trig. (Xbox) ZR (Switch) R2 (PS) [Analog] ImGuiKey_GamepadL3, // L Stick (Xbox) L3 (Switch) L3 (PS) ImGuiKey_GamepadR3, // R Stick (Xbox) R3 (Switch) R3 (PS) ImGuiKey_GamepadLStickLeft, // [Analog] // Move Window (in Windowing mode) ImGuiKey_GamepadLStickRight, // [Analog] // Move Window (in Windowing mode) ImGuiKey_GamepadLStickUp, // [Analog] // Move Window (in Windowing mode) ImGuiKey_GamepadLStickDown, // [Analog] // Move Window (in Windowing mode) ImGuiKey_GamepadRStickLeft, // [Analog] ImGuiKey_GamepadRStickRight, // [Analog] ImGuiKey_GamepadRStickUp, // [Analog] ImGuiKey_GamepadRStickDown, // [Analog] // Aliases: Mouse Buttons (auto-submitted from AddMouseButtonEvent() calls) // - This is mirroring the data also written to io.MouseDown[], io.MouseWheel, in a format allowing them to be accessed via standard key API. ImGuiKey_MouseLeft, ImGuiKey_MouseRight, ImGuiKey_MouseMiddle, ImGuiKey_MouseX1, ImGuiKey_MouseX2, ImGuiKey_MouseWheelX, ImGuiKey_MouseWheelY, // [Internal] Reserved for mod storage ImGuiKey_ReservedForModCtrl, ImGuiKey_ReservedForModShift, ImGuiKey_ReservedForModAlt, ImGuiKey_ReservedForModSuper, ImGuiKey_COUNT, // Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing // them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc. // - Code polling every key (e.g. an interface to detect a key press for input mapping) might want to ignore those // and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiMod_Ctrl). // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys. // In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and // backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... // - On macOS, we swap Cmd(Super) and Ctrl keys at the time of the io.AddKeyEvent() call. ImGuiMod_None = 0, ImGuiMod_Ctrl = 1<<12, // Ctrl (non-macOS), Cmd (macOS) ImGuiMod_Shift = 1<<13, // Shift ImGuiMod_Alt = 1<<14, // Option/Menu ImGuiMod_Super = 1<<15, // Windows/Super (non-macOS), Ctrl (macOS) ImGuiMod_Mask_ = 0xF000, // 4-bits // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + the io.KeyMap[] array. // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE) // If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey_NamedKey_BEGIN..ImGuiKey_NamedKey_END. ImGuiKey_NamedKey_BEGIN = 512, ImGuiKey_NamedKey_END = ImGuiKey_COUNT, ImGuiKey_NamedKey_COUNT = ImGuiKey_NamedKey_END-ImGuiKey_NamedKey_BEGIN, #ifdef IMGUI_DISABLE_OBSOLETE_KEYIO ImGuiKey_KeysData_SIZE = ImGuiKey_NamedKey_COUNT, // Size of KeysData[]: only hold named keys ImGuiKey_KeysData_OFFSET = ImGuiKey_NamedKey_BEGIN, // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index. #else ImGuiKey_KeysData_SIZE = ImGuiKey_COUNT, // Size of KeysData[]: hold legacy 0..512 keycodes + named keys ImGuiKey_KeysData_OFFSET = 0, // Accesses to io.KeysData[] must use (key - ImGuiKey_KeysData_OFFSET) index. #endif // #ifdef IMGUI_DISABLE_OBSOLETE_KEYIO #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS }; // Flags for Shortcut(), SetNextItemShortcut(), // (and for upcoming extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() that are still in imgui_internal.h) // Don't mistake with ImGuiInputTextFlags! (which is for ImGui::InputText() function) typedef enum { ImGuiInputFlags_None = 0, ImGuiInputFlags_Repeat = 1<<0, // Enable repeat. Return true on successive repeats. Default for legacy IsKeyPressed(). NOT Default for legacy IsMouseClicked(). MUST BE == 1. // Flags for Shortcut(), SetNextItemShortcut() // - Routing policies: RouteGlobal+OverActive >> RouteActive or RouteFocused (if owner is active item) >> RouteGlobal+OverFocused >> RouteFocused (if in focused window stack) >> RouteGlobal. // - Default policy is RouteFocused. Can select only 1 policy among all available. ImGuiInputFlags_RouteActive = 1<<10, // Route to active item only. ImGuiInputFlags_RouteFocused = 1<<11, // Route to windows in the focus stack (DEFAULT). Deep-most focused window takes inputs. Active item takes inputs over deep-most focused window. ImGuiInputFlags_RouteGlobal = 1<<12, // Global route (unless a focused window or active item registered the route). ImGuiInputFlags_RouteAlways = 1<<13, // Do not register route, poll keys directly. // - Routing options ImGuiInputFlags_RouteOverFocused = 1<<14, // Option: global route: higher priority than focused route (unless active item in focused route). ImGuiInputFlags_RouteOverActive = 1<<15, // Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. CTRL+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. ImGuiInputFlags_RouteUnlessBgFocused = 1<<16, // Option: global route: will not be applied if underlying background/void is focused (== no Dear ImGui windows are focused). Useful for overlay applications. ImGuiInputFlags_RouteFromRootWindow = 1<<17, // Option: route evaluated from the point of view of root window rather than current window. // Flags for SetNextItemShortcut() ImGuiInputFlags_Tooltip = 1<<18, // Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out) } ImGuiInputFlags_; #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO // OBSOLETED in 1.88 (from July 2022): ImGuiNavInput and io.NavInputs[]. // Official backends between 1.60 and 1.86: will keep working and feed gamepad inputs as long as IMGUI_DISABLE_OBSOLETE_KEYIO is not set. // Custom backends: feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. typedef enum { ImGuiNavInput_Activate, ImGuiNavInput_Cancel, ImGuiNavInput_Input, ImGuiNavInput_Menu, ImGuiNavInput_DpadLeft, ImGuiNavInput_DpadRight, ImGuiNavInput_DpadUp, ImGuiNavInput_DpadDown, ImGuiNavInput_LStickLeft, ImGuiNavInput_LStickRight, ImGuiNavInput_LStickUp, ImGuiNavInput_LStickDown, ImGuiNavInput_FocusPrev, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakSlow, ImGuiNavInput_TweakFast, ImGuiNavInput_COUNT, } ImGuiNavInput; #endif // #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO // Configuration flags stored in io.ConfigFlags. Set by user/application. typedef enum { ImGuiConfigFlags_None = 0, ImGuiConfigFlags_NavEnableKeyboard = 1<<0, // Master keyboard navigation enable flag. Enable full Tabbing + directional arrows + space/enter to activate. ImGuiConfigFlags_NavEnableGamepad = 1<<1, // Master gamepad navigation enable flag. Backend also needs to set ImGuiBackendFlags_HasGamepad. ImGuiConfigFlags_NavEnableSetMousePos = 1<<2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth. ImGuiConfigFlags_NavNoCaptureKeyboard = 1<<3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. ImGuiConfigFlags_NoMouse = 1<<4, // Instruct dear imgui to disable mouse inputs and interactions. ImGuiConfigFlags_NoMouseCursorChange = 1<<5, // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. ImGuiConfigFlags_NoKeyboard = 1<<6, // Instruct dear imgui to disable keyboard inputs and interactions. This is done by ignoring keyboard events and clearing existing states. // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are NOT used by core Dear ImGui) ImGuiConfigFlags_IsSRGB = 1<<20, // Application is SRGB-aware. ImGuiConfigFlags_IsTouchScreen = 1<<21, // Application is using a touch screen instead of a mouse. } ImGuiConfigFlags_; // Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. typedef enum { ImGuiBackendFlags_None = 0, ImGuiBackendFlags_HasGamepad = 1<<0, // Backend Platform supports gamepad and currently has one connected. ImGuiBackendFlags_HasMouseCursors = 1<<1, // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. ImGuiBackendFlags_HasSetMousePos = 1<<2, // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). ImGuiBackendFlags_RendererHasVtxOffset = 1<<3, // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. } ImGuiBackendFlags_; // Enumeration for PushStyleColor() / PopStyleColor() typedef enum { ImGuiCol_Text, ImGuiCol_TextDisabled, ImGuiCol_WindowBg, // Background of normal windows ImGuiCol_ChildBg, // Background of child windows ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows ImGuiCol_Border, ImGuiCol_BorderShadow, ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive, ImGuiCol_TitleBg, // Title bar ImGuiCol_TitleBgActive, // Title bar when focused ImGuiCol_TitleBgCollapsed, // Title bar when collapsed ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, ImGuiCol_CheckMark, // Checkbox tick and RadioButton circle ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem ImGuiCol_HeaderHovered, ImGuiCol_HeaderActive, ImGuiCol_Separator, ImGuiCol_SeparatorHovered, ImGuiCol_SeparatorActive, ImGuiCol_ResizeGrip, // Resize grip in lower-right and lower-left corners of windows. ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, ImGuiCol_TabHovered, // Tab background, when hovered ImGuiCol_Tab, // Tab background, when tab-bar is focused & tab is unselected ImGuiCol_TabSelected, // Tab background, when tab-bar is focused & tab is selected ImGuiCol_TabSelectedOverline, // Tab horizontal overline, when tab-bar is focused & tab is selected ImGuiCol_TabDimmed, // Tab background, when tab-bar is unfocused & tab is unselected ImGuiCol_TabDimmedSelected, // Tab background, when tab-bar is unfocused & tab is selected ImGuiCol_TabDimmedSelectedOverline, //..horizontal overline, when tab-bar is unfocused & tab is selected ImGuiCol_PlotLines, ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TableHeaderBg, // Table header background ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here) ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here) ImGuiCol_TableRowBg, // Table row background (even rows) ImGuiCol_TableRowBgAlt, // Table row background (odd rows) ImGuiCol_TextLink, // Hyperlink color ImGuiCol_TextSelectedBg, ImGuiCol_DragDropTarget, // Rectangle highlighting a drop target ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active ImGuiCol_COUNT, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS } ImGuiCol_; // Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. // - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. // During initialization or between frames, feel free to just poke into ImGuiStyle directly. // - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description. // - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. // - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments. // - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. typedef enum { // Enum name -------------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions) ImGuiStyleVar_Alpha, // float Alpha ImGuiStyleVar_DisabledAlpha, // float DisabledAlpha 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_CellPadding, // ImVec2 CellPadding ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding ImGuiStyleVar_GrabMinSize, // float GrabMinSize ImGuiStyleVar_GrabRounding, // float GrabRounding ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_TabBorderSize, // float TabBorderSize ImGuiStyleVar_TabBarBorderSize, // float TabBarBorderSize ImGuiStyleVar_TabBarOverlineSize, // float TabBarOverlineSize ImGuiStyleVar_TableAngledHeadersAngle, // float TableAngledHeadersAngle ImGuiStyleVar_TableAngledHeadersTextAlign, // ImVec2 TableAngledHeadersTextAlign ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_SelectableTextAlign, // ImVec2 SelectableTextAlign ImGuiStyleVar_SeparatorTextBorderSize, // float SeparatorTextBorderSize ImGuiStyleVar_SeparatorTextAlign, // ImVec2 SeparatorTextAlign ImGuiStyleVar_SeparatorTextPadding, // ImVec2 SeparatorTextPadding ImGuiStyleVar_COUNT, } ImGuiStyleVar_; // Flags for InvisibleButton() [extended in imgui_internal.h] typedef enum { ImGuiButtonFlags_None = 0, ImGuiButtonFlags_MouseButtonLeft = 1<<0, // React on left mouse button (default) ImGuiButtonFlags_MouseButtonRight = 1<<1, // React on right mouse button ImGuiButtonFlags_MouseButtonMiddle = 1<<2, // React on center mouse button ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle, // [Internal] //ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft, } ImGuiButtonFlags_; // Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() typedef enum { ImGuiColorEditFlags_None = 0, ImGuiColorEditFlags_NoAlpha = 1<<1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). ImGuiColorEditFlags_NoPicker = 1<<2, // // ColorEdit: disable picker when clicking on color square. ImGuiColorEditFlags_NoOptions = 1<<3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. ImGuiColorEditFlags_NoSmallPreview = 1<<4, // // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) ImGuiColorEditFlags_NoInputs = 1<<5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). ImGuiColorEditFlags_NoTooltip = 1<<6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. ImGuiColorEditFlags_NoLabel = 1<<7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). ImGuiColorEditFlags_NoSidePreview = 1<<8, // // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. ImGuiColorEditFlags_NoDragDrop = 1<<9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. ImGuiColorEditFlags_NoBorder = 1<<10, // // ColorButton: disable border (which is enforced by default) // User Options (right-click on widget to change some of them). ImGuiColorEditFlags_AlphaBar = 1<<16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_AlphaPreview = 1<<17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf = 1<<18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. ImGuiColorEditFlags_HDR = 1<<19, // // (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_DisplayRGB = 1<<20, // [Display] // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. ImGuiColorEditFlags_DisplayHSV = 1<<21, // [Display] // " ImGuiColorEditFlags_DisplayHex = 1<<22, // [Display] // " ImGuiColorEditFlags_Uint8 = 1<<23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. ImGuiColorEditFlags_Float = 1<<24, // [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<<25, // [Picker] // ColorPicker: bar for Hue, rectangle for Sat/Value. ImGuiColorEditFlags_PickerHueWheel = 1<<26, // [Picker] // ColorPicker: wheel for Hue, triangle for Sat/Value. ImGuiColorEditFlags_InputRGB = 1<<27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format. ImGuiColorEditFlags_InputHSV = 1<<28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format. // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup. ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar, // [Internal] Masks ImGuiColorEditFlags_DisplayMask_ = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex, ImGuiColorEditFlags_DataTypeMask_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float, ImGuiColorEditFlags_PickerMask_ = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags_InputMask_ = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV, // Obsolete names //ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex // [renamed in 1.69] } ImGuiColorEditFlags_; // Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. // We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. // (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigDragClickToInputText) typedef enum { ImGuiSliderFlags_None = 0, ImGuiSliderFlags_AlwaysClamp = 1<<4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds. ImGuiSliderFlags_Logarithmic = 1<<5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits. ImGuiSliderFlags_NoRoundToFormat = 1<<6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). ImGuiSliderFlags_NoInput = 1<<7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget. ImGuiSliderFlags_WrapAround = 1<<8, // Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions for now. ImGuiSliderFlags_InvalidMask_ = 0x7000000F, // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed. // Obsolete names //ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp, // [renamed in 1.79] } ImGuiSliderFlags_; // Identify a mouse button. // Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. typedef enum { ImGuiMouseButton_Left = 0, ImGuiMouseButton_Right = 1, ImGuiMouseButton_Middle = 2, ImGuiMouseButton_COUNT = 5, } ImGuiMouseButton_; // Enumeration for GetMouseCursor() // User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here typedef enum { ImGuiMouseCursor_None = -1, ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. ImGuiMouseCursor_ResizeAll, // (Unused by Dear ImGui functions) ImGuiMouseCursor_ResizeNS, // When hovering over a 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_Hand, // (Unused by Dear ImGui functions. Use for e.g. hyperlinks) ImGuiMouseCursor_NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle. ImGuiMouseCursor_COUNT, } ImGuiMouseCursor_; // Enumeration for AddMouseSourceEvent() actual source of Mouse Input data. // Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent() // But that "Mouse" data can come from different source which occasionally may be useful for application to know about. // You can submit a change of pointer type using io.AddMouseSourceEvent(). enum // Forward declared enum type ImGuiMouseSource { ImGuiMouseSource_Mouse = 0, // Input is coming from an actual mouse. ImGuiMouseSource_TouchScreen, // Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible). ImGuiMouseSource_Pen, // Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates). ImGuiMouseSource_COUNT, }; // Enumeration for ImGui::SetNextWindow***(), SetWindow***(), SetNextItem***() functions // Represent a condition. // Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. typedef enum { ImGuiCond_None = 0, // No condition (always set the variable), same as _Always ImGuiCond_Always = 1<<0, // No condition (always set the variable), same as _None ImGuiCond_Once = 1<<1, // Set the variable once per runtime session (only the first call will succeed) ImGuiCond_FirstUseEver = 1<<2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) ImGuiCond_Appearing = 1<<3, // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) } ImGuiCond_; //----------------------------------------------------------------------------- // [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) //----------------------------------------------------------------------------- // Flags for ImGui::BeginTable() // - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. // Read comments/demos carefully + experiment with live demos to get acquainted with them. // - The DEFAULT sizing policies are: // - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. // - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. // - When ScrollX is off: // - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. // - Columns sizing policy allowed: Stretch (default), Fixed/Auto. // - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). // - Stretch Columns will share the remaining width according to their respective weight. // - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. // The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. // (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). // - When ScrollX is on: // - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed // - Columns sizing policy allowed: Fixed/Auto mostly. // - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. // - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. // - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). // If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. // - Read on documentation at the top of imgui_tables.cpp for details. typedef enum { // Features ImGuiTableFlags_None = 0, ImGuiTableFlags_Resizable = 1<<0, // Enable resizing columns. ImGuiTableFlags_Reorderable = 1<<1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) ImGuiTableFlags_Hideable = 1<<2, // Enable hiding/disabling columns in context menu. ImGuiTableFlags_Sortable = 1<<3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. ImGuiTableFlags_NoSavedSettings = 1<<4, // Disable persisting columns order, width and sort settings in the .ini file. ImGuiTableFlags_ContextMenuInBody = 1<<5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). // Decorations ImGuiTableFlags_RowBg = 1<<6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) ImGuiTableFlags_BordersInnerH = 1<<7, // Draw horizontal borders between rows. ImGuiTableFlags_BordersOuterH = 1<<8, // Draw horizontal borders at the top and bottom. ImGuiTableFlags_BordersInnerV = 1<<9, // Draw vertical borders between columns. ImGuiTableFlags_BordersOuterV = 1<<10, // Draw vertical borders on the left and right sides. ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. ImGuiTableFlags_NoBordersInBody = 1<<11, // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style ImGuiTableFlags_NoBordersInBodyUntilResize = 1<<12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style // Sizing Policy (read above for defaults) ImGuiTableFlags_SizingFixedFit = 1<<13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. ImGuiTableFlags_SizingFixedSame = 2<<13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. ImGuiTableFlags_SizingStretchProp = 3<<13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. ImGuiTableFlags_SizingStretchSame = 4<<13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). // Sizing Extra Options ImGuiTableFlags_NoHostExtendX = 1<<16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. ImGuiTableFlags_NoHostExtendY = 1<<17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. ImGuiTableFlags_NoKeepColumnsVisible = 1<<18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. ImGuiTableFlags_PreciseWidths = 1<<19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. // Clipping ImGuiTableFlags_NoClip = 1<<20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). // Padding ImGuiTableFlags_PadOuterX = 1<<21, // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. ImGuiTableFlags_NoPadOuterX = 1<<22, // Default if BordersOuterV is off. Disable outermost padding. ImGuiTableFlags_NoPadInnerX = 1<<23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). // Scrolling ImGuiTableFlags_ScrollX = 1<<24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. ImGuiTableFlags_ScrollY = 1<<25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. // Sorting ImGuiTableFlags_SortMulti = 1<<26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). ImGuiTableFlags_SortTristate = 1<<27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). // Miscellaneous ImGuiTableFlags_HighlightHoveredColumn = 1<<28, // Highlight column headers when hovered (may evolve into a fuller highlight) // [Internal] Combinations and masks ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, } ImGuiTableFlags_; // Flags for ImGui::TableSetupColumn() typedef enum { // Input configuration flags ImGuiTableColumnFlags_None = 0, ImGuiTableColumnFlags_Disabled = 1<<0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) ImGuiTableColumnFlags_DefaultHide = 1<<1, // Default as a hidden/disabled column. ImGuiTableColumnFlags_DefaultSort = 1<<2, // Default as a sorting column. ImGuiTableColumnFlags_WidthStretch = 1<<3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). ImGuiTableColumnFlags_WidthFixed = 1<<4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). ImGuiTableColumnFlags_NoResize = 1<<5, // Disable manual resizing. ImGuiTableColumnFlags_NoReorder = 1<<6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. ImGuiTableColumnFlags_NoHide = 1<<7, // Disable ability to hide/disable this column. ImGuiTableColumnFlags_NoClip = 1<<8, // Disable clipping for this column (all NoClip columns will render in a same draw command). ImGuiTableColumnFlags_NoSort = 1<<9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). ImGuiTableColumnFlags_NoSortAscending = 1<<10, // Disable ability to sort in the ascending direction. ImGuiTableColumnFlags_NoSortDescending = 1<<11, // Disable ability to sort in the descending direction. ImGuiTableColumnFlags_NoHeaderLabel = 1<<12, // TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. ImGuiTableColumnFlags_NoHeaderWidth = 1<<13, // Disable header text width contribution to automatic column width. ImGuiTableColumnFlags_PreferSortAscending = 1<<14, // Make the initial sort direction Ascending when first sorting on this column (default). ImGuiTableColumnFlags_PreferSortDescending = 1<<15, // Make the initial sort direction Descending when first sorting on this column. ImGuiTableColumnFlags_IndentEnable = 1<<16, // Use current Indent value when entering cell (default for column 0). ImGuiTableColumnFlags_IndentDisable = 1<<17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. ImGuiTableColumnFlags_AngledHeader = 1<<18, // TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. // Output status flags, read-only via TableGetColumnFlags() ImGuiTableColumnFlags_IsEnabled = 1<<24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. ImGuiTableColumnFlags_IsVisible = 1<<25, // Status: is visible == is enabled AND not clipped by scrolling. ImGuiTableColumnFlags_IsSorted = 1<<26, // Status: is currently part of the sort specs ImGuiTableColumnFlags_IsHovered = 1<<27, // Status: is hovered by mouse // [Internal] Combinations and masks ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, ImGuiTableColumnFlags_NoDirectResize_ = 1<<30, // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) } ImGuiTableColumnFlags_; // Flags for ImGui::TableNextRow() typedef enum { ImGuiTableRowFlags_None = 0, ImGuiTableRowFlags_Headers = 1<<0, // Identify header row (set default background color + width of its contents accounted differently for auto column width) } ImGuiTableRowFlags_; // Enum for ImGui::TableSetBgColor() // Background colors are rendering in 3 layers: // - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. // - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. // - Layer 2: draw with CellBg color if set. // The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. // When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. // If you set the color of RowBg0 target, your color will override the existing RowBg0 color. // If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. typedef enum { ImGuiTableBgTarget_None = 0, ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) ImGuiTableBgTarget_CellBg = 3, // Set cell background color (top-most color) } ImGuiTableBgTarget_; // Sorting specifications for a table (often handling sort specs for a single column, occasionally more) // Obtained by calling TableGetSortSpecs(). // When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. // Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! typedef struct ImGuiTableSortSpecs_t { const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. } ImGuiTableSortSpecs; // Sorting specification for one column of a table (sizeof == 12 bytes) typedef struct ImGuiTableColumnSortSpecs_t { ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) ImS16 ColumnIndex; // Index of the column ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) ImGuiSortDirection SortDirection; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending } ImGuiTableColumnSortSpecs; //----------------------------------------------------------------------------- // [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> //----------------------------------------------------------------------------- // Extra helpers for C applications CIMGUI_API void ImVector_Construct(void* vector); // Construct a zero-size ImVector<> (of any type). This is primarily useful when calling ImFontGlyphRangesBuilder_BuildRanges() CIMGUI_API void ImVector_Destruct(void* vector); // Destruct an ImVector<> (of any type). Important: Frees the vector memory but does not call destructors on contained objects (if they have them) #if defined(IMGUI_HAS_IMSTR) #if IMGUI_HAS_IMSTR CIMGUI_API ImStr ImStr_FromCharStr(const char* b); // Build an ImStr from a regular const char* (no data is copied, so you need to make sure the original char* isn't altered as long as you are using the ImStr). #endif // #if IMGUI_HAS_IMSTR #endif // #if defined(IMGUI_HAS_IMSTR) //----------------------------------------------------------------------------- // Debug Logging into ShowDebugLogWindow(), tty and more. //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_DEBUG_TOOLS #define IMGUI_DEBUG_LOG(...) ImGui::DebugLog(__VA_ARGS__) #else #define IMGUI_DEBUG_LOG(...) ((void)0) #endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS //----------------------------------------------------------------------------- // IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() // We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. // Defining a custom placement new() with a custom parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions. //----------------------------------------------------------------------------- #define CIM_ALLOC(_SIZE) ImGui_MemAlloc(_SIZE) #define CIM_FREE(_PTR) ImGui_MemFree(_PTR) //----------------------------------------------------------------------------- // ImVector<> // Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug). //----------------------------------------------------------------------------- // - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it. // - We use std-like naming convention here, which is a little unusual for this codebase. // - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs. // - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that, // Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset. //----------------------------------------------------------------------------- IM_MSVC_RUNTIME_CHECKS_OFF // Instantiation of ImVector<ImWchar> typedef struct ImVector_ImWchar_t { int Size; int Capacity; ImWchar* Data; } ImVector_ImWchar; // Instantiation of ImVector<ImGuiTextFilter_ImGuiTextRange> typedef struct ImVector_ImGuiTextFilter_ImGuiTextRange_t { int Size; int Capacity; ImGuiTextFilter_ImGuiTextRange* Data; } ImVector_ImGuiTextFilter_ImGuiTextRange; // Instantiation of ImVector<char> typedef struct ImVector_char_t { int Size; int Capacity; char* Data; } ImVector_char; // Instantiation of ImVector<ImGuiStoragePair> typedef struct ImVector_ImGuiStoragePair_t { int Size; int Capacity; ImGuiStoragePair* Data; } ImVector_ImGuiStoragePair; // Instantiation of ImVector<ImGuiSelectionRequest> typedef struct ImVector_ImGuiSelectionRequest_t { int Size; int Capacity; ImGuiSelectionRequest* Data; } ImVector_ImGuiSelectionRequest; // Instantiation of ImVector<ImDrawCmd> typedef struct ImVector_ImDrawCmd_t { int Size; int Capacity; ImDrawCmd* Data; } ImVector_ImDrawCmd; // Instantiation of ImVector<ImDrawIdx> typedef struct ImVector_ImDrawIdx_t { int Size; int Capacity; ImDrawIdx* Data; } ImVector_ImDrawIdx; // Instantiation of ImVector<ImDrawChannel> typedef struct ImVector_ImDrawChannel_t { int Size; int Capacity; ImDrawChannel* Data; } ImVector_ImDrawChannel; // Instantiation of ImVector<ImDrawVert> typedef struct ImVector_ImDrawVert_t { int Size; int Capacity; ImDrawVert* Data; } ImVector_ImDrawVert; // Instantiation of ImVector<ImVec2> typedef struct ImVector_ImVec2_t { int Size; int Capacity; ImVec2* Data; } ImVector_ImVec2; // Instantiation of ImVector<ImVec4> typedef struct ImVector_ImVec4_t { int Size; int Capacity; ImVec4* Data; } ImVector_ImVec4; // Instantiation of ImVector<ImTextureID> typedef struct ImVector_ImTextureID_t { int Size; int Capacity; ImTextureID* Data; } ImVector_ImTextureID; // Instantiation of ImVector<ImDrawList*> typedef struct ImVector_ImDrawListPtr_t { int Size; int Capacity; ImDrawList** Data; } ImVector_ImDrawListPtr; // Instantiation of ImVector<ImU32> typedef struct ImVector_ImU32_t { int Size; int Capacity; ImU32* Data; } ImVector_ImU32; // Instantiation of ImVector<ImFont*> typedef struct ImVector_ImFontPtr_t { int Size; int Capacity; ImFont** Data; } ImVector_ImFontPtr; // Instantiation of ImVector<ImFontAtlasCustomRect> typedef struct ImVector_ImFontAtlasCustomRect_t { int Size; int Capacity; ImFontAtlasCustomRect* Data; } ImVector_ImFontAtlasCustomRect; // Instantiation of ImVector<ImFontConfig> typedef struct ImVector_ImFontConfig_t { int Size; int Capacity; ImFontConfig* Data; } ImVector_ImFontConfig; // Instantiation of ImVector<float> typedef struct ImVector_float_t { int Size; int Capacity; float* Data; } ImVector_float; // Instantiation of ImVector<ImFontGlyph> typedef struct ImVector_ImFontGlyph_t { int Size; int Capacity; ImFontGlyph* Data; } ImVector_ImFontGlyph; IM_MSVC_RUNTIME_CHECKS_RESTORE //----------------------------------------------------------------------------- // [SECTION] ImGuiStyle //----------------------------------------------------------------------------- // You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). // During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, // and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. //----------------------------------------------------------------------------- typedef struct ImGuiStyle_t { float Alpha; // Global alpha applies to everything in Dear ImGui. float DisabledAlpha; // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. ImVec2 WindowPadding; // Padding within a window. float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constrain individual windows, use SetNextWindowSizeConstraints(). ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left. 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. (Note that tooltip windows use WindowRounding) float PopupBorderSize; // Thickness of border around popup/tooltip 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 CellPadding; // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows. ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. float ScrollbarRounding; // Radius of grab corners for scrollbar. float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. float TabMinWidthForCloseButton; // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. float TabBarBorderSize; // Thickness of tab-bar separator, which takes on the tab active color to denote focus. float TabBarOverlineSize; // Thickness of tab-bar overline, which highlights the selected tab-bar. float TableAngledHeadersAngle; // Angle of angled headers (supported values range from -50.0f degrees to +50.0f degrees). ImVec2 TableAngledHeadersTextAlign; // Alignment of angled headers within the cell ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered). ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. float SeparatorTextBorderSize; // Thickness of border in SeparatorText() ImVec2 SeparatorTextAlign; // Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center). ImVec2 SeparatorTextPadding; // Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. ImVec2 DisplayWindowPadding; // Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen. ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured). float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. ImVec4 Colors[ImGuiCol_COUNT]; // Behaviors // (It is possible to modify those fields mid-frame if specific behavior need it, unlike e.g. configuration fields in ImGuiIO) float HoverStationaryDelay; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. float HoverDelayShort; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay. float HoverDelayNormal; // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). " ImGuiHoveredFlags HoverFlagsForTooltipMouse; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. ImGuiHoveredFlags HoverFlagsForTooltipNav; // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. } ImGuiStyle; CIMGUI_API void ImGuiStyle_ScaleAllSizes(ImGuiStyle* self, float scale_factor); //----------------------------------------------------------------------------- // [SECTION] ImGuiIO //----------------------------------------------------------------------------- // Communicate most settings and inputs/outputs to Dear ImGui using this structure. // Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. // It is generally expected that: // - initialization: backends and user code writes to ImGuiIO. // - main loop: backends writes to ImGuiIO, user code and imgui code reads from ImGuiIO. //----------------------------------------------------------------------------- // Also see ImGui::GetPlatformIO() and ImGuiPlatformIO struct for OS/platform related functions: clipboard, IME etc. //----------------------------------------------------------------------------- // [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. // If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. typedef struct ImGuiKeyData_t { bool Down; // True for if key is down float DownDuration; // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held) float DownDurationPrev; // Last frame duration the key has been down float AnalogValue; // 0.0f..1.0f for gamepad values } ImGuiKeyData; typedef struct ImGuiIO_t { //------------------------------------------------------------------ // Configuration // Default value //------------------------------------------------------------------ ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. ImVec2 DisplaySize; // <unset> // Main display size, in pixels (generally == GetMainViewport()->Size). May change every frame. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. May change every frame. float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file (important: default "imgui.ini" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions. const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified). void* UserData; // = NULL // Store your own data. ImFontAtlas* Fonts; // <auto> // Font atlas: load, rasterize and pack one or more fonts into a single texture. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. ImVec2 DisplayFramebufferScale; // = (1, 1) // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale. // Miscellaneous options bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // Swap Cmd<>Ctrl keys + 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 ConfigNavSwapGamepadButtons; // = false // Swap Activate<>Cancel (A<>B) buttons, matching typical "Nintendo/Japanese style" gamepad layout. bool ConfigInputTrickleEventQueue; // = true // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor (optional as some users consider it to be distracting). bool ConfigInputTextEnterKeepActive; // = false // [BETA] Pressing Enter will keep item active and select contents (single-line only). bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard. bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag) bool ConfigWindowsMoveFromTitleBarOnly; // = false // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. // Inputs Behaviors // (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) 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. float KeyRepeatDelay; // = 0.275f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. //------------------------------------------------------------------ // Debug options //------------------------------------------------------------------ // Option to enable various debug tools showing buttons that will call the IM_DEBUG_BREAK() macro. // - The Item Picker tool will be available regardless of this being enabled, in order to maximize its discoverability. // - Requires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application. // e.g. io.ConfigDebugIsDebuggerPresent = ::IsDebuggerPresent() on Win32, or refer to ImOsIsDebuggerPresent() imgui_test_engine/imgui_te_utils.cpp for a Unix compatible version). bool ConfigDebugIsDebuggerPresent; // = false // Enable various tools calling IM_DEBUG_BREAK(). // Tools to test correct Begin/End and BeginChild/EndChild behaviors. // - Presently Begin()/End() and BeginChild()/EndChild() needs to ALWAYS be called in tandem, regardless of return value of BeginXXX() // - This is inconsistent with other BeginXXX functions and create confusion for many users. // - We expect to update the API eventually. In the meanwhile we provide tools to facilitate checking user-code behavior. bool ConfigDebugBeginReturnValueOnce; // = false // First-time calls to Begin()/BeginChild() will return false. NEEDS TO BE SET AT APPLICATION BOOT TIME if you don't want to miss windows. bool ConfigDebugBeginReturnValueLoop; // = false // Some calls to Begin()/BeginChild() will return false. Will cycle through window depths then repeat. Suggested use: add "io.ConfigDebugBeginReturnValue = io.KeyShift" in your main loop then occasionally press SHIFT. Windows should be flickering while running. // Option to deactivate io.AddFocusEvent(false) handling. // - May facilitate interactions with a debugger when focus loss leads to clearing inputs data. // - Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. // Option to audit .ini data bool ConfigDebugIniSettings; // = false // Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) //------------------------------------------------------------------ // Platform Functions // (the imgui_impl_xxxx backend files are setting those up for you) //------------------------------------------------------------------ // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff. const char* BackendPlatformName; // = NULL const char* BackendRendererName; // = NULL void* BackendPlatformUserData; // = NULL // User data for platform backend void* BackendRendererUserData; // = NULL // User data for renderer backend void* BackendLanguageUserData; // = NULL // User data for non C++ programming language backend //------------------------------------------------------------------ // Input - Call before calling NewFrame() //------------------------------------------------------------------ //------------------------------------------------------------------ // Output - Updated by NewFrame() or EndFrame()/Render() // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is // generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!) //------------------------------------------------------------------ bool WantCaptureMouse; // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). bool WantCaptureKeyboard; // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). bool WantTextInput; // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). bool WantSetMousePos; // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! bool NavActive; // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. bool NavVisible; // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events). float Framerate; // Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. int MetricsRenderVertices; // Vertices output during last call to Render() int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 int MetricsRenderWindows; // Number of visible windows int MetricsActiveWindows; // Number of active windows 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. //------------------------------------------------------------------ // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed! //------------------------------------------------------------------ ImGuiContext* Ctx; // Parent UI context (needs to be set explicitly by parent). // Main Input State // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold SHIFT to turn vertical scroll into horizontal scroll. float MouseWheelH; // Mouse wheel Horizontal. >0 scrolls Left, <0 scrolls Right. Most users don't have a mouse with a horizontal wheel, may not be filled by all backends. ImGuiMouseSource MouseSource; // Mouse actual input peripheral (Mouse/TouchScreen/Pen). bool KeyCtrl; // Keyboard modifier down: Control bool KeyShift; // Keyboard modifier down: Shift bool KeyAlt; // Keyboard modifier down: Alt bool KeySuper; // Keyboard modifier down: Cmd/Super/Windows // Other state maintained from data above + IO function calls ImGuiKeyChord KeyMods; // Key mods flags (any of ImGuiMod_Ctrl/ImGuiMod_Shift/ImGuiMod_Alt/ImGuiMod_Super flags, same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags. Read-only, updated by NewFrame() ImGuiKeyData KeysData[ImGuiKey_KeysData_SIZE]; // Key state for all known keys. Use IsKeyXXX() functions to access this. bool WantCaptureMouseUnlessPopupClose; // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup. ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) ImVec2 MouseClickedPos[5]; // Position at time of clicking double MouseClickedTime[5]; // Time of last click (used to figure out double-click) bool MouseClicked[5]; // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) ImU16 MouseClickedCount[5]; // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down ImU16 MouseClickedLastCount[5]; // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. bool MouseReleased[5]; // Mouse button went from Down to !Down bool MouseDownOwned[5]; // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds. bool MouseDownOwnedUnlessPopupClose[5]; // Track if button was clicked inside a dear imgui window. bool MouseWheelRequestAxisSwap; // On a non-Mac system, holding SHIFT requests WheelY to perform the equivalent of a WheelX event. On a Mac system this is already enforced by the system. bool MouseCtrlLeftAsRightClick; // (OSX) Set to true when the current click was a ctrl-click that spawned a simulated right click 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 clicking point (used for moving thresholds) float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui. bool AppFocusLost; // Only modify via AddFocusEvent() bool AppAcceptingEvents; // Only modify via SetAppAcceptingEvents() ImS8 BackendUsingLegacyKeyArrays; // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[] bool BackendUsingLegacyNavInputArray; // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16() ImVector_ImWchar InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame. // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent(). // Old (<1.87): ImGui::IsKeyPressed(ImGui::GetIO().KeyMap[ImGuiKey_Space]) --> New (1.87+) ImGui::IsKeyPressed(ImGuiKey_Space) #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO int KeyMap[ImGuiKey_COUNT]; // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512. bool KeysDown[ImGuiKey_COUNT]; // [LEGACY] Input: 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). This used to be [512] sized. It is now ImGuiKey_COUNT to allow legacy io.KeysDown[GetKeyIndex(...)] to work without an overflow. float NavInputs[ImGuiNavInput_COUNT]; // [LEGACY] Since 1.88, NavInputs[] was removed. Backends from 1.60 to 1.86 won't build. Feed gamepad inputs via io.AddKeyEvent() and ImGuiKey_GamepadXXX enums. //void* ImeWindowHandle; // [Obsoleted in 1.87] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning. #endif // #ifndef IMGUI_DISABLE_OBSOLETE_KEYIO // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS const char* (*GetClipboardTextFn)(void* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS } ImGuiIO; // Input Functions CIMGUI_API void ImGuiIO_AddKeyEvent(ImGuiIO* self, ImGuiKey key, bool down); // Queue a new key down/up event. Key should be "translated" (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character) CIMGUI_API void ImGuiIO_AddKeyAnalogEvent(ImGuiIO* self, ImGuiKey key, bool down, float v); // Queue a new key down/up event for analog values (e.g. ImGuiKey_Gamepad_ values). Dead-zones should be handled by the backend. CIMGUI_API void ImGuiIO_AddMousePosEvent(ImGuiIO* self, float x, float y); // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered) CIMGUI_API void ImGuiIO_AddMouseButtonEvent(ImGuiIO* self, int button, bool down); // Queue a mouse button change CIMGUI_API void ImGuiIO_AddMouseWheelEvent(ImGuiIO* self, float wheel_x, float wheel_y); // Queue a mouse wheel update. wheel_y<0: scroll down, wheel_y>0: scroll up, wheel_x<0: scroll right, wheel_x>0: scroll left. CIMGUI_API void ImGuiIO_AddMouseSourceEvent(ImGuiIO* self, ImGuiMouseSource source); // Queue a mouse source change (Mouse/TouchScreen/Pen) CIMGUI_API void ImGuiIO_AddFocusEvent(ImGuiIO* self, bool focused); // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window) CIMGUI_API void ImGuiIO_AddInputCharacter(ImGuiIO* self, unsigned int c); // Queue a new character input CIMGUI_API void ImGuiIO_AddInputCharacterUTF16(ImGuiIO* self, ImWchar16 c); // Queue a new character input from a UTF-16 character, it can be a surrogate CIMGUI_API void ImGuiIO_AddInputCharactersUTF8(ImGuiIO* self, const char* str); // Queue a new characters input from a UTF-8 string CIMGUI_API void ImGuiIO_SetKeyEventNativeData(ImGuiIO* self, ImGuiKey key, int native_keycode, int native_scancode); // Implied native_legacy_index = -1 CIMGUI_API void ImGuiIO_SetKeyEventNativeDataEx(ImGuiIO* self, ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index /* = -1 */); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode. CIMGUI_API void ImGuiIO_SetAppAcceptingEvents(ImGuiIO* self, bool accepting_events); // Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen. CIMGUI_API void ImGuiIO_ClearEventsQueue(ImGuiIO* self); // Clear all incoming events. CIMGUI_API void ImGuiIO_ClearInputKeys(ImGuiIO* self); // Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. CIMGUI_API void ImGuiIO_ClearInputMouse(ImGuiIO* self); // Clear current mouse state. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS CIMGUI_API void ImGuiIO_ClearInputCharacters(ImGuiIO* self); // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS //----------------------------------------------------------------------------- // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) //----------------------------------------------------------------------------- // Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. // The callback function should return 0 by default. // Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) // - ImGuiInputTextFlags_CallbackEdit: Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active) // - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration // - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB // - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows // - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. // - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. typedef struct ImGuiInputTextCallbackData_t { ImGuiContext* Ctx; // Parent UI context ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only void* UserData; // What user passed to InputText() // Read-only // Arguments for the different callback events // - During Resize callback, Buf will be same as your input buffer. // - However, during Completion/History/Always callback, Buf always points to our own internal data (it is not the same as your buffer)! Changes to it will be reflected into your own buffer shortly after the callback. // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] int CursorPos; // // Read-write // [Completion,History,Always] int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) int SelectionEnd; // // Read-write // [Completion,History,Always] } ImGuiInputTextCallbackData; CIMGUI_API void ImGuiInputTextCallbackData_DeleteChars(ImGuiInputTextCallbackData* self, int pos, int bytes_count); CIMGUI_API void ImGuiInputTextCallbackData_InsertChars(ImGuiInputTextCallbackData* self, int pos, const char* text, const char* text_end /* = NULL */); CIMGUI_API void ImGuiInputTextCallbackData_SelectAll(ImGuiInputTextCallbackData* self); CIMGUI_API void ImGuiInputTextCallbackData_ClearSelection(ImGuiInputTextCallbackData* self); CIMGUI_API bool ImGuiInputTextCallbackData_HasSelection(const ImGuiInputTextCallbackData* self); // 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. typedef struct ImGuiSizeCallbackData_t { void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints(). Generally store an integer or float in here (need reinterpret_cast<>). 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. } ImGuiSizeCallbackData; // Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() typedef struct ImGuiPayload_t { // Members 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[32+1]; // Data type tag (short user-supplied string, 32 characters max) bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. } ImGuiPayload; CIMGUI_API void ImGuiPayload_Clear(ImGuiPayload* self); CIMGUI_API bool ImGuiPayload_IsDataType(const ImGuiPayload* self, const char* type); CIMGUI_API bool ImGuiPayload_IsPreview(const ImGuiPayload* self); CIMGUI_API bool ImGuiPayload_IsDelivery(const ImGuiPayload* self); //----------------------------------------------------------------------------- // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) //----------------------------------------------------------------------------- // Helper: Unicode defines #define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value). #ifdef IMGUI_USE_WCHAR32 #define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build. #else #define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build. #endif // #ifdef IMGUI_USE_WCHAR32 // [Internal] typedef struct ImGuiTextFilter_ImGuiTextRange_t { const char* b; const char* e; } ImGuiTextFilter_ImGuiTextRange; CIMGUI_API bool ImGuiTextFilter_ImGuiTextRange_empty(const ImGuiTextFilter_ImGuiTextRange* self); CIMGUI_API void ImGuiTextFilter_ImGuiTextRange_split(const ImGuiTextFilter_ImGuiTextRange* self, char separator, ImVector_ImGuiTextFilter_ImGuiTextRange* out); // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" typedef struct ImGuiTextFilter_t { char InputBuf[256]; ImVector_ImGuiTextFilter_ImGuiTextRange Filters; int CountGrep; } ImGuiTextFilter; CIMGUI_API bool ImGuiTextFilter_Draw(ImGuiTextFilter* self, const char* label /* = "Filter (inc,-exc)" */, float width /* = 0.0f */); // Helper calling InputText+Build CIMGUI_API bool ImGuiTextFilter_PassFilter(const ImGuiTextFilter* self, const char* text, const char* text_end /* = NULL */); CIMGUI_API void ImGuiTextFilter_Build(ImGuiTextFilter* self); CIMGUI_API void ImGuiTextFilter_Clear(ImGuiTextFilter* self); CIMGUI_API bool ImGuiTextFilter_IsActive(const ImGuiTextFilter* self); // Helper: Growable text buffer for logging/accumulating text // (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') typedef struct ImGuiTextBuffer_t { ImVector_char Buf; } ImGuiTextBuffer; CIMGUI_API const char* ImGuiTextBuffer_begin(const ImGuiTextBuffer* self); CIMGUI_API const char* ImGuiTextBuffer_end(const ImGuiTextBuffer* self); // Buf is zero-terminated, so end() will point on the zero-terminator CIMGUI_API int ImGuiTextBuffer_size(const ImGuiTextBuffer* self); CIMGUI_API bool ImGuiTextBuffer_empty(const ImGuiTextBuffer* self); CIMGUI_API void ImGuiTextBuffer_clear(ImGuiTextBuffer* self); CIMGUI_API void ImGuiTextBuffer_reserve(ImGuiTextBuffer* self, int capacity); CIMGUI_API const char* ImGuiTextBuffer_c_str(const ImGuiTextBuffer* self); CIMGUI_API void ImGuiTextBuffer_append(ImGuiTextBuffer* self, const char* str, const char* str_end /* = NULL */); CIMGUI_API void ImGuiTextBuffer_appendf(ImGuiTextBuffer* self, const char* fmt, ...) IM_FMTARGS(2); CIMGUI_API void ImGuiTextBuffer_appendfv(ImGuiTextBuffer* self, const char* fmt, va_list args) IM_FMTLIST(2); // [Internal] Key+Value for ImGuiStorage typedef struct ImGuiStoragePair_t { ImGuiID key; union { int val_i; float val_f; void* val_p; }; } ImGuiStoragePair; // Helper: 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) // This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) // 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 (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. typedef struct ImGuiStorage_t { // [Internal] ImVector_ImGuiStoragePair Data; } 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. CIMGUI_API void ImGuiStorage_Clear(ImGuiStorage* self); CIMGUI_API int ImGuiStorage_GetInt(const ImGuiStorage* self, ImGuiID key, int default_val /* = 0 */); CIMGUI_API void ImGuiStorage_SetInt(ImGuiStorage* self, ImGuiID key, int val); CIMGUI_API bool ImGuiStorage_GetBool(const ImGuiStorage* self, ImGuiID key, bool default_val /* = false */); CIMGUI_API void ImGuiStorage_SetBool(ImGuiStorage* self, ImGuiID key, bool val); CIMGUI_API float ImGuiStorage_GetFloat(const ImGuiStorage* self, ImGuiID key, float default_val /* = 0.0f */); CIMGUI_API void ImGuiStorage_SetFloat(ImGuiStorage* self, ImGuiID key, float val); CIMGUI_API void* ImGuiStorage_GetVoidPtr(const ImGuiStorage* self, ImGuiID key); // default_val is NULL CIMGUI_API void ImGuiStorage_SetVoidPtr(ImGuiStorage* self, ImGuiID key, void* val); // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; CIMGUI_API int* ImGuiStorage_GetIntRef(ImGuiStorage* self, ImGuiID key, int default_val /* = 0 */); CIMGUI_API bool* ImGuiStorage_GetBoolRef(ImGuiStorage* self, ImGuiID key, bool default_val /* = false */); CIMGUI_API float* ImGuiStorage_GetFloatRef(ImGuiStorage* self, ImGuiID key, float default_val /* = 0.0f */); CIMGUI_API void** ImGuiStorage_GetVoidPtrRef(ImGuiStorage* self, ImGuiID key, void* default_val /* = NULL */); // Advanced: for quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. CIMGUI_API void ImGuiStorage_BuildSortByKey(ImGuiStorage* self); // Obsolete: use on your own storage if you know only integer are being stored (open/close all tree nodes) CIMGUI_API void ImGuiStorage_SetAllInt(ImGuiStorage* self, int val); // Helper: Manually clip large list of items. // If you have lots evenly spaced items and you have random access to the list, you can perform coarse // clipping based on visibility to only submit items that are in view. // The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. // (Dear ImGui already clip items based on their bounds but: it needs to first layout the item to do so, and generally // fetching/submitting your own data incurs additional cost. Coarse clipping using ImGuiListClipper allows you to easily // scale using lists with tens of thousands of items without a problem) // Usage: // ImGuiListClipper clipper; // clipper.Begin(1000); // We have 1000 elements, evenly spaced. // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) // ImGui::Text("line number %d", i); // Generally what happens is: // - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. // - User code submit that one element. // - Clipper can measure the height of the first element // - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. // - User code submit visible elements. // - The clipper also handles various subtleties related to keyboard/gamepad navigation, wrapping etc. typedef struct ImGuiListClipper_t { ImGuiContext* Ctx; // Parent UI context int DisplayStart; // First item to display, updated by each call to Step() int DisplayEnd; // End of items to display (exclusive) int ItemsCount; // [Internal] Number of items float ItemsHeight; // [Internal] Height of item after a first step and item submission can calculate it float StartPosY; // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed double StartSeekOffsetY; // [Internal] Account for frozen rows in a table and initial loss of precision in very large windows. void* TempData; // [Internal] Internal data } ImGuiListClipper; CIMGUI_API void ImGuiListClipper_Begin(ImGuiListClipper* self, int items_count, float items_height /* = -1.0f */); CIMGUI_API void ImGuiListClipper_End(ImGuiListClipper* self); // Automatically called on the last call of Step() that returns false. CIMGUI_API bool ImGuiListClipper_Step(ImGuiListClipper* self); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. // Call IncludeItemByIndex() or IncludeItemsByIndex() *BEFORE* first call to Step() if you need a range of items to not be clipped, regardless of their visibility. // (Due to alignment / padding of certain items it is possible that an extra item may be included on either end of the display range). CIMGUI_API void ImGuiListClipper_IncludeItemByIndex(ImGuiListClipper* self, int item_index); CIMGUI_API void ImGuiListClipper_IncludeItemsByIndex(ImGuiListClipper* self, int item_begin, int item_end); // item_end is exclusive e.g. use (42, 42+1) to make item 42 never clipped. // Seek cursor toward given item. This is automatically called while stepping. // - The only reason to call this is: you can use ImGuiListClipper::Begin(INT_MAX) if you don't know item count ahead of time. // - In this case, after all steps are done, you'll want to call SeekCursorForItem(item_count). CIMGUI_API void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* self, int item_index); #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS CIMGUI_API void ImGuiListClipper_IncludeRangeByIndices(ImGuiListClipper* self, int item_begin, int item_end); // [renamed in 1.89.9] CIMGUI_API void ImGuiListClipper_ForceDisplayRangeByIndices(ImGuiListClipper* self, int item_begin, int item_end); // [renamed in 1.89.6] #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Helpers: ImVec2/ImVec4 operators // - It is important that we are keeping those disabled by default so they don't leak in user space. // - This is in order to allow user enabling implicit cast operators between ImVec2/ImVec4 and their own types (using IM_VEC2_CLASS_EXTRA in imconfig.h) // - Add '#define IMGUI_DEFINE_MATH_OPERATORS' before including this file (or in imconfig.h) to access courtesy maths operators for ImVec2 and ImVec4. #ifdef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS_IMPLEMENTED IM_MSVC_RUNTIME_CHECKS_OFF IM_MSVC_RUNTIME_CHECKS_RESTORE #endif // #ifdef IMGUI_DEFINE_MATH_OPERATORS // Helpers macros to generate 32-bit encoded colors // User can declare their own format by #defining the 5 _SHIFT/_MASK macros in their imconfig file. #ifndef IM_COL32_R_SHIFT #ifdef IMGUI_USE_BGRA_PACKED_COLOR #define IM_COL32_R_SHIFT 16 #define IM_COL32_G_SHIFT 8 #define IM_COL32_B_SHIFT 0 #define IM_COL32_A_SHIFT 24 #define IM_COL32_A_MASK 0xFF000000 #else #define IM_COL32_R_SHIFT 0 #define IM_COL32_G_SHIFT 8 #define IM_COL32_B_SHIFT 16 #define IM_COL32_A_SHIFT 24 #define IM_COL32_A_MASK 0xFF000000 #endif // #ifdef IMGUI_USE_BGRA_PACKED_COLOR #endif // #ifndef IM_COL32_R_SHIFT #define IM_COL32(R,G,B,A) (((ImU32)(A)<<IM_COL32_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT)) #define IM_COL32_WHITE IM_COL32(255,255,255,255) // Opaque white = 0xFFFFFFFF #define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black #define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000 // Helper: ImColor() implicitly converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) // Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API. // **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE. // **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed. typedef struct ImColor_t { ImVec4 Value; } ImColor; // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. CIMGUI_API void ImColor_SetHSV(ImColor* self, float h, float s, float v, float a /* = 1.0f */); CIMGUI_API ImColor ImColor_HSV(ImColor* self, float h, float s, float v, float a /* = 1.0f */); //----------------------------------------------------------------------------- // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiSelectionRequestType, ImGuiSelectionRequest, ImGuiMultiSelectIO, ImGuiSelectionBasicStorage) //----------------------------------------------------------------------------- // Multi-selection system // Documentation at: https://github.com/ocornut/imgui/wiki/Multi-Select // - Refer to 'Demo->Widgets->Selection State & Multi-Select' for demos using this. // - This system implements standard multi-selection idioms (CTRL+Mouse/Keyboard, SHIFT+Mouse/Keyboard, etc) // with support for clipper (skipping non-visible items), box-select and many other details. // - Selectable(), Checkbox() are supported but custom widgets may use it as well. // - TreeNode() is technically supported but... using this correctly is more complicated: you need some sort of linear/random access to your tree, // which is suited to advanced trees setups also implementing filters and clipper. We will work toward simplifying and demoing it. // - In the spirit of Dear ImGui design, your code owns actual selection data. // This is designed to allow all kinds of selection storage you may use in your application e.g. set/map/hash. // About ImGuiSelectionBasicStorage: // - This is an optional helper to store a selection state and apply selection requests. // - It is used by our demos and provided as a convenience to quickly implement multi-selection. // Usage: // - Identify submitted items with SetNextItemSelectionUserData(), most likely using an index into your current data-set. // - Store and maintain actual selection data using persistent object identifiers. // - Usage flow: // BEGIN - (1) Call BeginMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (2) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 6. // - (3) [If using clipper] You need to make sure RangeSrcItem is always submitted. Calculate its index and pass to clipper.IncludeItemByIndex(). If storing indices in ImGuiSelectionUserData, a simple clipper.IncludeItemByIndex(ms_io->RangeSrcItem) call will work. // LOOP - (4) Submit your items with SetNextItemSelectionUserData() + Selectable()/TreeNode() calls. // END - (5) Call EndMultiSelect() and retrieve the ImGuiMultiSelectIO* result. // - (6) Honor request list (SetAll/SetRange requests) by updating your selection data. Same code as Step 2. // If you submit all items (no clipper), Step 2 and 3 are optional and will be handled by each item themselves. It is fine to always honor those steps. // About ImGuiSelectionUserData: // - This can store an application-defined identifier (e.g. index or pointer) submitted via SetNextItemSelectionUserData(). // - In return we store them into RangeSrcItem/RangeFirstItem/RangeLastItem and other fields in ImGuiMultiSelectIO. // - Most applications will store an object INDEX, hence the chosen name and type. Storing an index is natural, because // SetRange requests will give you two end-points and you will need to iterate/interpolate between them to update your selection. // - However it is perfectly possible to store a POINTER or another IDENTIFIER inside ImGuiSelectionUserData. // Our system never assume that you identify items by indices, it never attempts to interpolate between two values. // - If you enable ImGuiMultiSelectFlags_NoRangeSelect then it is guaranteed that you will never have to interpolate // between two ImGuiSelectionUserData, which may be a convenient way to use part of the feature with less code work. // - As most users will want to store an index, for convenience and to reduce confusion we use ImS64 instead of void*, // being syntactically easier to downcast. Feel free to reinterpret_cast and store a pointer inside. // Flags for BeginMultiSelect() typedef enum { ImGuiMultiSelectFlags_None = 0, ImGuiMultiSelectFlags_SingleSelect = 1<<0, // Disable selecting more than one item. This is available to allow single-selection code to share same code/logic if desired. It essentially disables the main purpose of BeginMultiSelect() tho! ImGuiMultiSelectFlags_NoSelectAll = 1<<1, // Disable CTRL+A shortcut to select all. ImGuiMultiSelectFlags_NoRangeSelect = 1<<2, // Disable Shift+selection mouse/keyboard support (useful for unordered 2D selection). With BoxSelect is also ensure contiguous SetRange requests are not combined into one. This allows not handling interpolation in SetRange requests. ImGuiMultiSelectFlags_NoAutoSelect = 1<<3, // Disable selecting items when navigating (useful for e.g. supporting range-select in a list of checkboxes). ImGuiMultiSelectFlags_NoAutoClear = 1<<4, // Disable clearing selection when navigating or selecting another one (generally used with ImGuiMultiSelectFlags_NoAutoSelect. useful for e.g. supporting range-select in a list of checkboxes). ImGuiMultiSelectFlags_NoAutoClearOnReselect = 1<<5, // Disable clearing selection when clicking/selecting an already selected item. ImGuiMultiSelectFlags_BoxSelect1d = 1<<6, // Enable box-selection with same width and same x pos items (e.g. full row Selectable()). Box-selection works better with little bit of spacing between items hit-box in order to be able to aim at empty space. ImGuiMultiSelectFlags_BoxSelect2d = 1<<7, // Enable box-selection with varying width or varying x pos items support (e.g. different width labels, or 2D layout/grid). This is slower: alters clipping logic so that e.g. horizontal movements will update selection of normally clipped items. ImGuiMultiSelectFlags_BoxSelectNoScroll = 1<<8, // Disable scrolling when box-selecting near edges of scope. ImGuiMultiSelectFlags_ClearOnEscape = 1<<9, // Clear selection when pressing Escape while scope is focused. ImGuiMultiSelectFlags_ClearOnClickVoid = 1<<10, // Clear selection when clicking on empty location within scope. ImGuiMultiSelectFlags_ScopeWindow = 1<<11, // Scope for _BoxSelect and _ClearOnClickVoid is whole window (Default). Use if BeginMultiSelect() covers a whole window or used a single time in same window. ImGuiMultiSelectFlags_ScopeRect = 1<<12, // Scope for _BoxSelect and _ClearOnClickVoid is rectangle encompassing BeginMultiSelect()/EndMultiSelect(). Use if BeginMultiSelect() is called multiple times in same window. ImGuiMultiSelectFlags_SelectOnClick = 1<<13, // Apply selection on mouse down when clicking on unselected item. (Default) ImGuiMultiSelectFlags_SelectOnClickRelease = 1<<14, // Apply selection on mouse release when clicking an unselected item. Allow dragging an unselected item without altering selection. //ImGuiMultiSelectFlags_RangeSelect2d = 1 << 15, // Shift+Selection uses 2d geometry instead of linear sequence, so possible to use Shift+up/down to select vertically in grid. Analogous to what BoxSelect does. ImGuiMultiSelectFlags_NavWrapX = 1<<16, // [Temporary] Enable navigation wrapping on X axis. Provided as a convenience because we don't have a design for the general Nav API for this yet. When the more general feature be public we may obsolete this flag in favor of new one. } ImGuiMultiSelectFlags_; // Main IO structure returned by BeginMultiSelect()/EndMultiSelect(). // This mainly contains a list of selection requests. // - Use 'Demo->Tools->Debug Log->Selection' to see requests as they happen. // - Some fields are only useful if your list is dynamic and allows deletion (getting post-deletion focus/state right is shown in the demo) // - Below: who reads/writes each fields? 'r'=read, 'w'=write, 'ms'=multi-select code, 'app'=application/user code. typedef struct ImGuiMultiSelectIO_t { //------------------------------------------// BeginMultiSelect / EndMultiSelect ImVector_ImGuiSelectionRequest Requests; // ms:w, app:r / ms:w app:r // Requests to apply to your selection data. ImGuiSelectionUserData RangeSrcItem; // ms:w app:r / // (If using clipper) Begin: Source item (often the first selected item) must never be clipped: use clipper.IncludeItemByIndex() to ensure it is submitted. ImGuiSelectionUserData NavIdItem; // ms:w, app:r / // (If using deletion) Last known SetNextItemSelectionUserData() value for NavId (if part of submitted items). bool NavIdSelected; // ms:w, app:r / app:r // (If using deletion) Last known selection state for NavId (if part of submitted items). bool RangeSrcReset; // app:w / ms:r // (If using deletion) Set before EndMultiSelect() to reset ResetSrcItem (e.g. if deleted selection). int ItemsCount; // ms:w, app:r / app:r // 'int items_count' parameter to BeginMultiSelect() is copied here for convenience, allowing simpler calls to your ApplyRequests handler. Not used internally. } ImGuiMultiSelectIO; // Selection request type typedef enum { ImGuiSelectionRequestType_None = 0, ImGuiSelectionRequestType_SetAll, // Request app to clear selection (if Selected==false) or select all items (if Selected==true). We cannot set RangeFirstItem/RangeLastItem as its contents is entirely up to user (not necessarily an index) ImGuiSelectionRequestType_SetRange, // Request app to select/unselect [RangeFirstItem..RangeLastItem] items (inclusive) based on value of Selected. Only EndMultiSelect() request this, app code can read after BeginMultiSelect() and it will always be false. } ImGuiSelectionRequestType; // Selection request item typedef struct ImGuiSelectionRequest_t { //------------------------------------------// BeginMultiSelect / EndMultiSelect ImGuiSelectionRequestType Type; // ms:w, app:r / ms:w, app:r // Request type. You'll most often receive 1 Clear + 1 SetRange with a single-item range. bool Selected; // ms:w, app:r / ms:w, app:r // Parameter for SetAll/SetRange requests (true = select, false = unselect) ImS8 RangeDirection; // / ms:w app:r // Parameter for SetRange request: +1 when RangeFirstItem comes before RangeLastItem, -1 otherwise. Useful if you want to preserve selection order on a backward Shift+Click. ImGuiSelectionUserData RangeFirstItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from top to bottom). ImGuiSelectionUserData RangeLastItem; // / ms:w, app:r // Parameter for SetRange request (this is generally == RangeSrcItem when shift selecting from bottom to top). Inclusive! } ImGuiSelectionRequest; // Optional helper to store multi-selection state + apply multi-selection requests. // - Used by our demos and provided as a convenience to easily implement basic multi-selection. // - Iterate selection with 'void* it = NULL; ImGuiID id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' // Or you can check 'if (Contains(id)) { ... }' for each possible object if their number is not too high to iterate. // - USING THIS IS NOT MANDATORY. This is only a helper and not a required API. // To store a multi-selection, in your application you could: // - Use this helper as a convenience. We use our simple key->value ImGuiStorage as a std::set<ImGuiID> replacement. // - Use your own external storage: e.g. std::set<MyObjectId>, std::vector<MyObjectId>, interval trees, intrusively stored selection etc. // In ImGuiSelectionBasicStorage we: // - always use indices in the multi-selection API (passed to SetNextItemSelectionUserData(), retrieved in ImGuiMultiSelectIO) // - use the AdapterIndexToStorageId() indirection layer to abstract how persistent selection data is derived from an index. // - use decently optimized logic to allow queries and insertion of very large selection sets. // - do not preserve selection order. // Many combinations are possible depending on how you prefer to store your items and how you prefer to store your selection. // Large applications are likely to eventually want to get rid of this indirection layer and do their own thing. // See https://github.com/ocornut/imgui/wiki/Multi-Select for details and pseudo-code using this helper. typedef struct ImGuiSelectionBasicStorage_t { // Members int Size; // // Number of selected items, maintained by this helper. bool PreserveOrder; // = false // GetNextSelectedItem() will return ordered selection (currently implemented by two additional sorts of selection. Could be improved) void* UserData; // = NULL // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; ImGuiID (*AdapterIndexToStorageId)(ImGuiSelectionBasicStorage* self, int idx); // e.g. selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { return ((MyItems**)self->UserData)[idx]->ID; }; int _SelectionOrder; // [Internal] Increasing counter to store selection order ImGuiStorage _Storage; // [Internal] Selection set. Think of this as similar to e.g. std::set<ImGuiID>. Prefer not accessing directly: iterate with GetNextSelectedItem(). } ImGuiSelectionBasicStorage; CIMGUI_API void ImGuiSelectionBasicStorage_ApplyRequests(ImGuiSelectionBasicStorage* self, ImGuiMultiSelectIO* ms_io); // Apply selection requests coming from BeginMultiSelect() and EndMultiSelect() functions. It uses 'items_count' passed to BeginMultiSelect() CIMGUI_API bool ImGuiSelectionBasicStorage_Contains(const ImGuiSelectionBasicStorage* self, ImGuiID id); // Query if an item id is in selection. CIMGUI_API void ImGuiSelectionBasicStorage_Clear(ImGuiSelectionBasicStorage* self); // Clear selection CIMGUI_API void ImGuiSelectionBasicStorage_Swap(ImGuiSelectionBasicStorage* self, ImGuiSelectionBasicStorage* r); // Swap two selections CIMGUI_API void ImGuiSelectionBasicStorage_SetItemSelected(ImGuiSelectionBasicStorage* self, ImGuiID id, bool selected); // Add/remove an item from selection (generally done by ApplyRequests() function) CIMGUI_API bool ImGuiSelectionBasicStorage_GetNextSelectedItem(ImGuiSelectionBasicStorage* self, void** opaque_it, ImGuiID* out_id); // Iterate selection with 'void* it = NULL; ImGuiId id; while (selection.GetNextSelectedItem(&it, &id)) { ... }' CIMGUI_API ImGuiID ImGuiSelectionBasicStorage_GetStorageIdFromIndex(ImGuiSelectionBasicStorage* self, int idx); // Convert index to item id based on provided adapter. // Optional helper to apply multi-selection requests to existing randomly accessible storage. // Convenient if you want to quickly wire multi-select API on e.g. an array of bool or items storing their own selection state. typedef struct ImGuiSelectionExternalStorage_t { // Members void* UserData; // User data for use by adapter function // e.g. selection.UserData = (void*)my_items; void (*AdapterSetItemSelected)(ImGuiSelectionExternalStorage* self, int idx, bool selected); // e.g. AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int idx, bool selected) { ((MyItems**)self->UserData)[idx]->Selected = selected; } } ImGuiSelectionExternalStorage; CIMGUI_API void ImGuiSelectionExternalStorage_ApplyRequests(ImGuiSelectionExternalStorage* self, ImGuiMultiSelectIO* ms_io); // Apply selection requests by using AdapterSetItemSelected() calls //----------------------------------------------------------------------------- // [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- // The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX #define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (63) #endif // #ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX // ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] // NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, // you can poke into the draw list for that! Draw callback may be useful for example to: // A) Change your GPU render state, // B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' // If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly. #ifndef ImDrawCallback typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); #endif // #ifndef ImDrawCallback // Special Draw callback value to request renderer backend to reset the graphics/render state. // The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address. // This is useful, for example, if you submitted callbacks which you know have altered the render state and you want it to be restored. // Render state is not reset by default because they are many perfectly useful way of altering render state (e.g. changing shader/blending settings before an Image call). #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) // Typically, 1 command = 1 GPU draw call (unless command is a callback) // - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled, // this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices. // Backends made for <1.71. will typically ignore the VtxOffset fields. // - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for). typedef struct ImDrawCmd_t { ImVec4 ClipRect; // 4*4 // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates ImTextureID TextureId; // 4-8 // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. unsigned int VtxOffset; // 4 // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices. unsigned int IdxOffset; // 4 // Start offset in index buffer. unsigned int ElemCount; // 4 // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. ImDrawCallback UserCallback; // 4-8 // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // 4-8 // The draw callback code can access this. } ImDrawCmd; // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature) CIMGUI_API ImTextureID ImDrawCmd_GetTexID(const ImDrawCmd* self); // Vertex layout #ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT typedef struct ImDrawVert_t { ImVec2 pos; ImVec2 uv; ImU32 col; } ImDrawVert; #else // You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h // The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. // The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared at the time you'd want to set your type up. // NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT #endif // #ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT // [Internal] For use by ImDrawList typedef struct ImDrawCmdHeader_t { ImVec4 ClipRect; ImTextureID TextureId; unsigned int VtxOffset; } ImDrawCmdHeader; // [Internal] For use by ImDrawListSplitter typedef struct ImDrawChannel_t { ImVector_ImDrawCmd _CmdBuffer; ImVector_ImDrawIdx _IdxBuffer; } ImDrawChannel; // Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order. // This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call. typedef struct ImDrawListSplitter_t { int _Current; // Current channel number (0) int _Count; // Number of active channels (1+) ImVector_ImDrawChannel _Channels; // Draw channels (not resized down so _Count might be < Channels.Size) } ImDrawListSplitter; CIMGUI_API void ImDrawListSplitter_Clear(ImDrawListSplitter* self); // Do not clear Channels[] so our allocations are reused next frame CIMGUI_API void ImDrawListSplitter_ClearFreeMemory(ImDrawListSplitter* self); CIMGUI_API void ImDrawListSplitter_Split(ImDrawListSplitter* self, ImDrawList* draw_list, int count); CIMGUI_API void ImDrawListSplitter_Merge(ImDrawListSplitter* self, ImDrawList* draw_list); CIMGUI_API void ImDrawListSplitter_SetCurrentChannel(ImDrawListSplitter* self, ImDrawList* draw_list, int channel_idx); // Flags for ImDrawList functions // (Legacy: bit 0 must always correspond to ImDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused) typedef enum { ImDrawFlags_None = 0, ImDrawFlags_Closed = 1<<0, // PathStroke(), AddPolyline(): specify that shape should be closed (Important: this is always == 1 for legacy reason) ImDrawFlags_RoundCornersTopLeft = 1<<4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01. ImDrawFlags_RoundCornersTopRight = 1<<5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02. ImDrawFlags_RoundCornersBottomLeft = 1<<6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04. ImDrawFlags_RoundCornersBottomRight = 1<<7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08. ImDrawFlags_RoundCornersNone = 1<<8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag! ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified. ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, } ImDrawFlags_; // Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. // It is however possible to temporarily alter flags between calls to ImDrawList:: functions. typedef enum { ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1<<0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedLinesUseTex = 1<<1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). ImDrawListFlags_AntiAliasedFill = 1<<2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). ImDrawListFlags_AllowVtxOffset = 1<<3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. } ImDrawListFlags_; // 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. // Each dear 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. // In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize). // You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may 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. typedef struct ImDrawList_t { // This is what you have to render ImVector_ImDrawCmd CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector_ImDrawIdx IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector_ImDrawVert VtxBuffer; // Vertex buffer. ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. // [Internal, used while building lists] unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImVector_ImVec2 _Path; // [Internal] current path building ImDrawCmdHeader _CmdHeader; // [Internal] template of active commands. Fields should match those of CmdBuffer.back(). ImDrawListSplitter _Splitter; // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) ImVector_ImVec4 _ClipRectStack; // [Internal] ImVector_ImTextureID _TextureIdStack; // [Internal] float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content const char* _OwnerName; // Pointer to owner window's name for debugging // Obsolete names //inline void AddEllipse(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f) { AddEllipse(center, ImVec2(radius_x, radius_y), col, rot, num_segments, thickness); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void AddEllipseFilled(const ImVec2& center, float radius_x, float radius_y, ImU32 col, float rot = 0.0f, int num_segments = 0) { AddEllipseFilled(center, ImVec2(radius_x, radius_y), col, rot, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void PathEllipticalArcTo(const ImVec2& center, float radius_x, float radius_y, float rot, float a_min, float a_max, int num_segments = 0) { PathEllipticalArcTo(center, ImVec2(radius_x, radius_y), rot, a_min, a_max, num_segments); } // OBSOLETED in 1.90.5 (Mar 2024) //inline void AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021) //inline void PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021) } ImDrawList; CIMGUI_API void ImDrawList_PushClipRect(ImDrawList* self, 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) CIMGUI_API void ImDrawList_PushClipRectFullScreen(ImDrawList* self); CIMGUI_API void ImDrawList_PopClipRect(ImDrawList* self); CIMGUI_API void ImDrawList_PushTextureID(ImDrawList* self, ImTextureID texture_id); CIMGUI_API void ImDrawList_PopTextureID(ImDrawList* self); CIMGUI_API ImVec2 ImDrawList_GetClipRectMin(const ImDrawList* self); CIMGUI_API ImVec2 ImDrawList_GetClipRectMax(const ImDrawList* self); // Primitives // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. // - For rectangular primitives, "p_min" and "p_max" represent the upper-left and lower-right corners. // - For circle primitives, use "num_segments == 0" to automatically calculate tessellation (preferred). // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. // In future versions we will use textures to provide cheaper and higher-quality circles. // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. CIMGUI_API void ImDrawList_AddLine(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImU32 col); // Implied thickness = 1.0f CIMGUI_API void ImDrawList_AddLineEx(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImU32 col, float thickness /* = 1.0f */); CIMGUI_API void ImDrawList_AddRect(ImDrawList* self, ImVec2 p_min, ImVec2 p_max, ImU32 col); // Implied rounding = 0.0f, flags = 0, thickness = 1.0f CIMGUI_API void ImDrawList_AddRectEx(ImDrawList* self, ImVec2 p_min, ImVec2 p_max, ImU32 col, float rounding /* = 0.0f */, ImDrawFlags flags /* = 0 */, float thickness /* = 1.0f */); // a: upper-left, b: lower-right (== upper-left + size) CIMGUI_API void ImDrawList_AddRectFilled(ImDrawList* self, ImVec2 p_min, ImVec2 p_max, ImU32 col); // Implied rounding = 0.0f, flags = 0 CIMGUI_API void ImDrawList_AddRectFilledEx(ImDrawList* self, ImVec2 p_min, ImVec2 p_max, ImU32 col, float rounding /* = 0.0f */, ImDrawFlags flags /* = 0 */); // a: upper-left, b: lower-right (== upper-left + size) CIMGUI_API void ImDrawList_AddRectFilledMultiColor(ImDrawList* self, ImVec2 p_min, ImVec2 p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); CIMGUI_API void ImDrawList_AddQuad(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImVec2 p4, ImU32 col); // Implied thickness = 1.0f CIMGUI_API void ImDrawList_AddQuadEx(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImVec2 p4, ImU32 col, float thickness /* = 1.0f */); CIMGUI_API void ImDrawList_AddQuadFilled(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImVec2 p4, ImU32 col); CIMGUI_API void ImDrawList_AddTriangle(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImU32 col); // Implied thickness = 1.0f CIMGUI_API void ImDrawList_AddTriangleEx(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImU32 col, float thickness /* = 1.0f */); CIMGUI_API void ImDrawList_AddTriangleFilled(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImU32 col); CIMGUI_API void ImDrawList_AddCircle(ImDrawList* self, ImVec2 center, float radius, ImU32 col); // Implied num_segments = 0, thickness = 1.0f CIMGUI_API void ImDrawList_AddCircleEx(ImDrawList* self, ImVec2 center, float radius, ImU32 col, int num_segments /* = 0 */, float thickness /* = 1.0f */); CIMGUI_API void ImDrawList_AddCircleFilled(ImDrawList* self, ImVec2 center, float radius, ImU32 col, int num_segments /* = 0 */); CIMGUI_API void ImDrawList_AddNgon(ImDrawList* self, ImVec2 center, float radius, ImU32 col, int num_segments); // Implied thickness = 1.0f CIMGUI_API void ImDrawList_AddNgonEx(ImDrawList* self, ImVec2 center, float radius, ImU32 col, int num_segments, float thickness /* = 1.0f */); CIMGUI_API void ImDrawList_AddNgonFilled(ImDrawList* self, ImVec2 center, float radius, ImU32 col, int num_segments); CIMGUI_API void ImDrawList_AddEllipse(ImDrawList* self, ImVec2 center, ImVec2 radius, ImU32 col); // Implied rot = 0.0f, num_segments = 0, thickness = 1.0f CIMGUI_API void ImDrawList_AddEllipseEx(ImDrawList* self, ImVec2 center, ImVec2 radius, ImU32 col, float rot /* = 0.0f */, int num_segments /* = 0 */, float thickness /* = 1.0f */); CIMGUI_API void ImDrawList_AddEllipseFilled(ImDrawList* self, ImVec2 center, ImVec2 radius, ImU32 col); // Implied rot = 0.0f, num_segments = 0 CIMGUI_API void ImDrawList_AddEllipseFilledEx(ImDrawList* self, ImVec2 center, ImVec2 radius, ImU32 col, float rot /* = 0.0f */, int num_segments /* = 0 */); CIMGUI_API void ImDrawList_AddText(ImDrawList* self, ImVec2 pos, ImU32 col, const char* text_begin); // Implied text_end = NULL CIMGUI_API void ImDrawList_AddTextEx(ImDrawList* self, ImVec2 pos, ImU32 col, const char* text_begin, const char* text_end /* = NULL */); CIMGUI_API void ImDrawList_AddTextImFontPtr(ImDrawList* self, const ImFont* font, float font_size, ImVec2 pos, ImU32 col, const char* text_begin); // Implied text_end = NULL, wrap_width = 0.0f, cpu_fine_clip_rect = NULL CIMGUI_API void ImDrawList_AddTextImFontPtrEx(ImDrawList* self, const ImFont* font, float font_size, 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 */); CIMGUI_API void ImDrawList_AddBezierCubic(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImVec2 p4, ImU32 col, float thickness, int num_segments /* = 0 */); // Cubic Bezier (4 control points) CIMGUI_API void ImDrawList_AddBezierQuadratic(ImDrawList* self, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImU32 col, float thickness, int num_segments /* = 0 */); // Quadratic Bezier (3 control points) // General polygon // - Only simple polygons are supported by filling functions (no self-intersections, no holes). // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience fo user but not used by main library. CIMGUI_API void ImDrawList_AddPolyline(ImDrawList* self, const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness); CIMGUI_API void ImDrawList_AddConvexPolyFilled(ImDrawList* self, const ImVec2* points, int num_points, ImU32 col); CIMGUI_API void ImDrawList_AddConcavePolyFilled(ImDrawList* self, const ImVec2* points, int num_points, ImU32 col); // Image primitives // - Read FAQ to understand what ImTextureID is. // - "p_min" and "p_max" represent the upper-left and lower-right corners of the rectangle. // - "uv_min" and "uv_max" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture. CIMGUI_API void ImDrawList_AddImage(ImDrawList* self, ImTextureID user_texture_id, ImVec2 p_min, ImVec2 p_max); // Implied uv_min = ImVec2(0, 0), uv_max = ImVec2(1, 1), col = IM_COL32_WHITE CIMGUI_API void ImDrawList_AddImageEx(ImDrawList* self, ImTextureID user_texture_id, ImVec2 p_min, ImVec2 p_max, ImVec2 uv_min /* = ImVec2(0, 0) */, ImVec2 uv_max /* = ImVec2(1, 1) */, ImU32 col /* = IM_COL32_WHITE */); CIMGUI_API void ImDrawList_AddImageQuad(ImDrawList* self, ImTextureID user_texture_id, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImVec2 p4); // Implied uv1 = ImVec2(0, 0), uv2 = ImVec2(1, 0), uv3 = ImVec2(1, 1), uv4 = ImVec2(0, 1), col = IM_COL32_WHITE CIMGUI_API void ImDrawList_AddImageQuadEx(ImDrawList* self, ImTextureID user_texture_id, ImVec2 p1, ImVec2 p2, ImVec2 p3, ImVec2 p4, ImVec2 uv1 /* = ImVec2(0, 0) */, ImVec2 uv2 /* = ImVec2(1, 0) */, ImVec2 uv3 /* = ImVec2(1, 1) */, ImVec2 uv4 /* = ImVec2(0, 1) */, ImU32 col /* = IM_COL32_WHITE */); CIMGUI_API void ImDrawList_AddImageRounded(ImDrawList* self, ImTextureID user_texture_id, ImVec2 p_min, ImVec2 p_max, ImVec2 uv_min, ImVec2 uv_max, ImU32 col, float rounding, ImDrawFlags flags /* = 0 */); // Stateful path API, add points then finish with PathFillConvex() or PathStroke() // - Important: filled shapes must always use clockwise winding order! The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. // so e.g. 'PathArcTo(center, radius, PI * -0.5f, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5f)' won't have correct anti-aliasing when followed by PathFillConvex(). CIMGUI_API void ImDrawList_PathClear(ImDrawList* self); CIMGUI_API void ImDrawList_PathLineTo(ImDrawList* self, ImVec2 pos); CIMGUI_API void ImDrawList_PathLineToMergeDuplicate(ImDrawList* self, ImVec2 pos); CIMGUI_API void ImDrawList_PathFillConvex(ImDrawList* self, ImU32 col); CIMGUI_API void ImDrawList_PathFillConcave(ImDrawList* self, ImU32 col); CIMGUI_API void ImDrawList_PathStroke(ImDrawList* self, ImU32 col, ImDrawFlags flags /* = 0 */, float thickness /* = 1.0f */); CIMGUI_API void ImDrawList_PathArcTo(ImDrawList* self, ImVec2 center, float radius, float a_min, float a_max, int num_segments /* = 0 */); CIMGUI_API void ImDrawList_PathArcToFast(ImDrawList* self, ImVec2 center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle CIMGUI_API void ImDrawList_PathEllipticalArcTo(ImDrawList* self, ImVec2 center, ImVec2 radius, float rot, float a_min, float a_max); // Implied num_segments = 0 CIMGUI_API void ImDrawList_PathEllipticalArcToEx(ImDrawList* self, ImVec2 center, ImVec2 radius, float rot, float a_min, float a_max, int num_segments /* = 0 */); // Ellipse CIMGUI_API void ImDrawList_PathBezierCubicCurveTo(ImDrawList* self, ImVec2 p2, ImVec2 p3, ImVec2 p4, int num_segments /* = 0 */); // Cubic Bezier (4 control points) CIMGUI_API void ImDrawList_PathBezierQuadraticCurveTo(ImDrawList* self, ImVec2 p2, ImVec2 p3, int num_segments /* = 0 */); // Quadratic Bezier (3 control points) CIMGUI_API void ImDrawList_PathRect(ImDrawList* self, ImVec2 rect_min, ImVec2 rect_max, float rounding /* = 0.0f */, ImDrawFlags flags /* = 0 */); // Advanced CIMGUI_API void ImDrawList_AddCallback(ImDrawList* self, ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. CIMGUI_API void ImDrawList_AddDrawCmd(ImDrawList* self); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible CIMGUI_API ImDrawList* ImDrawList_CloneOutput(const ImDrawList* self); // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. // Advanced: Channels // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives) // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end) // - This API shouldn't have been in ImDrawList in the first place! // Prefer using your own persistent instance of ImDrawListSplitter as you can stack them. // Using the ImDrawList::ChannelsXXXX you cannot stack a split over another. CIMGUI_API void ImDrawList_ChannelsSplit(ImDrawList* self, int count); CIMGUI_API void ImDrawList_ChannelsMerge(ImDrawList* self); CIMGUI_API void ImDrawList_ChannelsSetCurrent(ImDrawList* self, int n); // Advanced: Primitives allocations // - We render triangles (three vertices) // - All primitives needs to be reserved via PrimReserve() beforehand. CIMGUI_API void ImDrawList_PrimReserve(ImDrawList* self, int idx_count, int vtx_count); CIMGUI_API void ImDrawList_PrimUnreserve(ImDrawList* self, int idx_count, int vtx_count); CIMGUI_API void ImDrawList_PrimRect(ImDrawList* self, ImVec2 a, ImVec2 b, ImU32 col); // Axis aligned rectangle (composed of two triangles) CIMGUI_API void ImDrawList_PrimRectUV(ImDrawList* self, ImVec2 a, ImVec2 b, ImVec2 uv_a, ImVec2 uv_b, ImU32 col); CIMGUI_API void ImDrawList_PrimQuadUV(ImDrawList* self, ImVec2 a, ImVec2 b, ImVec2 c, ImVec2 d, ImVec2 uv_a, ImVec2 uv_b, ImVec2 uv_c, ImVec2 uv_d, ImU32 col); CIMGUI_API void ImDrawList_PrimWriteVtx(ImDrawList* self, ImVec2 pos, ImVec2 uv, ImU32 col); CIMGUI_API void ImDrawList_PrimWriteIdx(ImDrawList* self, ImDrawIdx idx); CIMGUI_API void ImDrawList_PrimVtx(ImDrawList* self, ImVec2 pos, ImVec2 uv, ImU32 col); // Write vertex with unique index // [Internal helpers] CIMGUI_API void ImDrawList__ResetForNewFrame(ImDrawList* self); CIMGUI_API void ImDrawList__ClearFreeMemory(ImDrawList* self); CIMGUI_API void ImDrawList__PopUnusedDrawCmd(ImDrawList* self); CIMGUI_API void ImDrawList__TryMergeDrawCmds(ImDrawList* self); CIMGUI_API void ImDrawList__OnChangedClipRect(ImDrawList* self); CIMGUI_API void ImDrawList__OnChangedTextureID(ImDrawList* self); CIMGUI_API void ImDrawList__OnChangedVtxOffset(ImDrawList* self); CIMGUI_API void ImDrawList__SetTextureID(ImDrawList* self, ImTextureID texture_id); CIMGUI_API int ImDrawList__CalcCircleAutoSegmentCount(const ImDrawList* self, float radius); CIMGUI_API void ImDrawList__PathArcToFastEx(ImDrawList* self, ImVec2 center, float radius, int a_min_sample, int a_max_sample, int a_step); CIMGUI_API void ImDrawList__PathArcToN(ImDrawList* self, ImVec2 center, float radius, float a_min, float a_max, int num_segments); // All draw data to render a Dear ImGui frame // (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, // as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) typedef struct ImDrawData_t { bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. int CmdListsCount; // Number of ImDrawList* to render (should always be == CmdLists.size) int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size ImVector_ImDrawListPtr CmdLists; // Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. ImVec2 DisplayPos; // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications) ImVec2 DisplaySize; // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications) ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display. ImGuiViewport* OwnerViewport; // Viewport carrying the ImDrawData instance, might be of use to the renderer (generally not). } ImDrawData; CIMGUI_API void ImDrawData_Clear(ImDrawData* self); CIMGUI_API void ImDrawData_AddDrawList(ImDrawData* self, ImDrawList* draw_list); // Helper to add an external draw list into an existing ImDrawData. CIMGUI_API void ImDrawData_DeIndexAllBuffers(ImDrawData* self); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! CIMGUI_API void ImDrawData_ScaleClipRects(ImDrawData* self, ImVec2 fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. //----------------------------------------------------------------------------- // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) //----------------------------------------------------------------------------- typedef struct ImFontConfig_t { 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 (more or less maps to the resulting font height). int OversampleH; // 2 // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal. You can reduce this to 1 for large glyphs save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details. int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. This is not really useful as 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. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs 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 FontBuilderFlags; // 0 // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. float RasterizerMultiply; // 1.0f // Linearly brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. This is a silly thing we may remove in the future. float RasterizerDensity; // 1.0f // DPI scale for rasterization, not altering other font metrics: make it easy to swap between e.g. a 100% and a 400% fonts for a zooming display. IMPORTANT: If you increase this it is expected that you increase font scale accordingly, otherwise quality may look lowered. ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. // [Internal] char Name[40]; // Name (strictly to ease debugging) ImFont* DstFont; } ImFontConfig; // Hold rendering data for one glyph. // (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this) typedef struct ImFontGlyph_t { unsigned int Colored : 1; // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops) unsigned int Visible : 1; // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering. unsigned int Codepoint : 30; // 0x0000..0x10FFFF float AdvanceX; // 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 } ImFontGlyph; // Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges(). // This is essentially a tightly packed of vector of 64k booleans = 8KB storage. typedef struct ImFontGlyphRangesBuilder_t { ImVector_ImU32 UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) } ImFontGlyphRangesBuilder; CIMGUI_API void ImFontGlyphRangesBuilder_Clear(ImFontGlyphRangesBuilder* self); CIMGUI_API bool ImFontGlyphRangesBuilder_GetBit(const ImFontGlyphRangesBuilder* self, size_t n); // Get bit n in the array CIMGUI_API void ImFontGlyphRangesBuilder_SetBit(ImFontGlyphRangesBuilder* self, size_t n); // Set bit n in the array CIMGUI_API void ImFontGlyphRangesBuilder_AddChar(ImFontGlyphRangesBuilder* self, ImWchar c); // Add character CIMGUI_API void ImFontGlyphRangesBuilder_AddText(ImFontGlyphRangesBuilder* self, const char* text, const char* text_end /* = NULL */); // Add string (each character of the UTF-8 string are added) CIMGUI_API void ImFontGlyphRangesBuilder_AddRanges(ImFontGlyphRangesBuilder* self, const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext CIMGUI_API void ImFontGlyphRangesBuilder_BuildRanges(ImFontGlyphRangesBuilder* self, ImVector_ImWchar* out_ranges); // Output new ranges (ImVector_Construct()/ImVector_Destruct() can be used to safely construct out_ranges) // See ImFontAtlas::AddCustomRectXXX functions. typedef struct ImFontAtlasCustomRect_t { unsigned short Width, Height; // Input // Desired rectangle dimension unsigned short X, Y; // Output // Packed position in Atlas unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000) float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset ImFont* Font; // Input // For custom font glyphs only: target font } ImFontAtlasCustomRect; CIMGUI_API bool ImFontAtlasCustomRect_IsPacked(const ImFontAtlasCustomRect* self); // Flags for ImFontAtlas build typedef enum { ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1<<0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1<<1, // Don't build software mouse cursors into the atlas (save a little texture memory) ImFontAtlasFlags_NoBakedLines = 1<<2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). } ImFontAtlasFlags_; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: // - One or more fonts. // - Custom graphics data needed to render the shapes needed by Dear ImGui. // - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). // It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. // - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. // - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. // - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) // - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. // This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. // Common pitfalls: // - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the // atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. // - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. // You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, // - Even though many functions are suffixed with "TTF", OTF data is supported just as well. // - This is an old API and it is currently awkward for those and various other reasons! We will address them in the future! typedef struct ImFontAtlas_t { //------------------------------------------- // Glyph Ranges //------------------------------------------- //------------------------------------------- // [BETA] Custom Rectangles/Glyphs API //------------------------------------------- //------------------------------------------- // Members //------------------------------------------- ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. void* UserData; // Store your own atlas related user-data (if e.g. you have multiple font atlas). // [Internal] // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. bool TexReady; // Set when texture was built matching current font input bool TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format. unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 int TexWidth; // Texture width calculated during Build(). int TexHeight; // Texture height calculated during Build(). ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector_ImFontPtr Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector_ImFontAtlasCustomRect CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector_ImFontConfig ConfigData; // Configuration data ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX+1]; // UVs for baked anti-aliased lines // [Internal] Font builder const ImFontBuilderIO* FontBuilderIO; // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE). unsigned int FontBuilderFlags; // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig. // [Internal] Packing data int PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors int PackIdLines; // Custom texture rectangle ID for baked anti-aliased lines // [Obsolete] //typedef ImFontAtlasCustomRect CustomRect; // OBSOLETED in 1.72+ //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+ } ImFontAtlas; CIMGUI_API ImFont* ImFontAtlas_AddFont(ImFontAtlas* self, const ImFontConfig* font_cfg); CIMGUI_API ImFont* ImFontAtlas_AddFontDefault(ImFontAtlas* self, const ImFontConfig* font_cfg /* = NULL */); CIMGUI_API ImFont* ImFontAtlas_AddFontFromFileTTF(ImFontAtlas* self, const char* filename, float size_pixels, const ImFontConfig* font_cfg /* = NULL */, const ImWchar* glyph_ranges /* = NULL */); CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryTTF(ImFontAtlas* self, void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg /* = NULL */, const ImWchar* glyph_ranges /* = NULL */); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryCompressedTTF(ImFontAtlas* self, const void* compressed_font_data, int compressed_font_data_size, float size_pixels, const ImFontConfig* font_cfg /* = NULL */, const ImWchar* glyph_ranges /* = NULL */); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. CIMGUI_API ImFont* ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(ImFontAtlas* self, 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. CIMGUI_API void ImFontAtlas_ClearInputData(ImFontAtlas* self); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. CIMGUI_API void ImFontAtlas_ClearTexData(ImFontAtlas* self); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. CIMGUI_API void ImFontAtlas_ClearFonts(ImFontAtlas* self); // Clear output font data (glyphs storage, UV coordinates). CIMGUI_API void ImFontAtlas_Clear(ImFontAtlas* self); // Clear all input and output. // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). // The pitch is always = Width * BytesPerPixels (1 or 4) // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. CIMGUI_API bool ImFontAtlas_Build(ImFontAtlas* self); // Build pixels data. This is called automatically for you by the GetTexData*** functions. CIMGUI_API void ImFontAtlas_GetTexDataAsAlpha8(ImFontAtlas* self, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel /* = NULL */); // 1 byte per-pixel CIMGUI_API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* self, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel /* = NULL */); // 4 bytes-per-pixel CIMGUI_API bool ImFontAtlas_IsBuilt(const ImFontAtlas* self); // Bit ambiguous: used to detect when user didn't build texture but effectively we should check TexID != 0 except that would be backend dependent... CIMGUI_API void ImFontAtlas_SetTexID(ImFontAtlas* self, ImTextureID id); // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) // NB: Make sure that your string are UTF-8 and NOT in your local code page. // Read https://github.com/ocornut/imgui/blob/master/docs/FONTS.md/#about-utf-8-encoding for details. // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data. CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesDefault(ImFontAtlas* self); // Basic Latin, Extended Latin CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesGreek(ImFontAtlas* self); // Default + Greek and Coptic CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesKorean(ImFontAtlas* self); // Default + Korean characters CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesJapanese(ImFontAtlas* self); // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseFull(ImFontAtlas* self); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon(ImFontAtlas* self); // Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesCyrillic(ImFontAtlas* self); // Default + about 400 Cyrillic characters CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesThai(ImFontAtlas* self); // Default + Thai characters CIMGUI_API const ImWchar* ImFontAtlas_GetGlyphRangesVietnamese(ImFontAtlas* self); // Default + Vietnamese characters // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. // - After calling Build(), you can query the rectangle position and render your pixels. // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of preferred texture format. // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), // so you can render e.g. custom colorful icons and use them as regular glyphs. // - Read docs/FONTS.md for more details about using colorful icons. // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings. CIMGUI_API int ImFontAtlas_AddCustomRectRegular(ImFontAtlas* self, int width, int height); CIMGUI_API int ImFontAtlas_AddCustomRectFontGlyph(ImFontAtlas* self, ImFont* font, ImWchar id, int width, int height, float advance_x, ImVec2 offset /* = ImVec2(0, 0) */); CIMGUI_API ImFontAtlasCustomRect* ImFontAtlas_GetCustomRectByIndex(ImFontAtlas* self, int index); // [Internal] CIMGUI_API void ImFontAtlas_CalcCustomRectUV(const ImFontAtlas* self, const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max); CIMGUI_API bool ImFontAtlas_GetMouseCursorTexData(ImFontAtlas* self, ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); // Font runtime data and rendering // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). typedef struct ImFont_t { // Members: Hot ~20/24 bytes (for CalcTextSize) ImVector_float IndexAdvanceX; // 12-16 // out // // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this info, and are often bottleneck in large UI). float FallbackAdvanceX; // 4 // out // = FallbackGlyph->AdvanceX float FontSize; // 4 // in // // Height of characters/line, set during loading (don't change after loading) // Members: Hot ~28/40 bytes (for CalcTextSize + render loop) ImVector_ImWchar IndexLookup; // 12-16 // out // // Sparse. Index glyphs by Unicode code-point. ImVector_ImFontGlyph Glyphs; // 12-16 // out // // All glyphs. const ImFontGlyph* FallbackGlyph; // 4-8 // out // = FindGlyph(FontFallbackChar) // Members: Cold ~32/40 bytes ImFontAtlas* ContainerAtlas; // 4-8 // out // // What we has been loaded into const ImFontConfig* ConfigData; // 4-8 // in // // Pointer within ContainerAtlas->ConfigData short ConfigDataCount; // 2 // in // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. ImWchar FallbackChar; // 2 // out // = FFFD/'?' // Character used if a glyph isn't found. ImWchar EllipsisChar; // 2 // out // = '...'/'.'// Character used for ellipsis rendering. short EllipsisCharCount; // 1 // out // 1 or 3 float EllipsisWidth; // 4 // out // Width float EllipsisCharStep; // 4 // out // Step between characters when EllipsisCount > 0 bool DirtyLookupTables; // 1 // out // float Scale; // 4 // in // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale() float Ascent, Descent; // 4+4 // out // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) int MetricsTotalSurface; // 4 // out // // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) ImU8 Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX +1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. } ImFont; CIMGUI_API const ImFontGlyph* ImFont_FindGlyph(const ImFont* self, ImWchar c); CIMGUI_API const ImFontGlyph* ImFont_FindGlyphNoFallback(const ImFont* self, ImWchar c); CIMGUI_API float ImFont_GetCharAdvance(const ImFont* self, ImWchar c); CIMGUI_API bool ImFont_IsLoaded(const ImFont* self); CIMGUI_API const char* ImFont_GetDebugName(const ImFont* self); // '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. CIMGUI_API ImVec2 ImFont_CalcTextSizeA(const ImFont* self, float size, float max_width, float wrap_width, const char* text_begin); // Implied text_end = NULL, remaining = NULL CIMGUI_API ImVec2 ImFont_CalcTextSizeAEx(const ImFont* self, float size, float max_width, float wrap_width, const char* text_begin, const char* text_end /* = NULL */, const char** remaining /* = NULL */); // utf8 CIMGUI_API const char* ImFont_CalcWordWrapPositionA(const ImFont* self, float scale, const char* text, const char* text_end, float wrap_width); CIMGUI_API void ImFont_RenderChar(const ImFont* self, ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c); CIMGUI_API void ImFont_RenderText(const ImFont* self, ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImVec4 clip_rect, const char* text_begin, const char* text_end, float wrap_width /* = 0.0f */, bool cpu_fine_clip /* = false */); // [Internal] Don't use! CIMGUI_API void ImFont_BuildLookupTable(ImFont* self); CIMGUI_API void ImFont_ClearOutputData(ImFont* self); CIMGUI_API void ImFont_GrowIndex(ImFont* self, int new_size); CIMGUI_API void ImFont_AddGlyph(ImFont* self, const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); CIMGUI_API void ImFont_AddRemapChar(ImFont* self, ImWchar dst, ImWchar src, bool overwrite_dst /* = true */); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. CIMGUI_API void ImFont_SetGlyphVisible(ImFont* self, ImWchar c, bool visible); CIMGUI_API bool ImFont_IsGlyphRangeUnused(ImFont* self, unsigned int c_begin, unsigned int c_last); //----------------------------------------------------------------------------- // [SECTION] Viewports //----------------------------------------------------------------------------- // Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. typedef enum { ImGuiViewportFlags_None = 0, ImGuiViewportFlags_IsPlatformWindow = 1<<0, // Represent a Platform Window ImGuiViewportFlags_IsPlatformMonitor = 1<<1, // Represent a Platform Monitor (unused yet) ImGuiViewportFlags_OwnedByApp = 1<<2, // Platform Window: Is created/managed by the application (rather than a dear imgui backend) } ImGuiViewportFlags_; // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports. // - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. // - About Main Area vs Work Area: // - Main Area = entire viewport. // - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). // - Windows are generally trying to stay within the Work Area of their host viewport. typedef struct ImGuiViewport_t { ImGuiID ID; // Unique identifier for the viewport ImGuiViewportFlags Flags; // See ImGuiViewportFlags_ ImVec2 Pos; // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) ImVec2 Size; // Main Area: Size of the viewport. ImVec2 WorkPos; // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) ImVec2 WorkSize; // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) // Platform/Backend Dependent Data void* PlatformHandle; // void* to hold higher-level, platform window handle (e.g. HWND, GLFWWindow*, SDL_Window*) void* PlatformHandleRaw; // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms) } ImGuiViewport; // Helpers CIMGUI_API ImVec2 ImGuiViewport_GetCenter(const ImGuiViewport* self); CIMGUI_API ImVec2 ImGuiViewport_GetWorkCenter(const ImGuiViewport* self); //----------------------------------------------------------------------------- // [SECTION] Platform Dependent Interfaces //----------------------------------------------------------------------------- // Access via ImGui::GetPlatformIO() typedef struct ImGuiPlatformIO_t { //------------------------------------------------------------------ // Input - Interface with OS/backends //------------------------------------------------------------------ // Optional: Access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) const char* (*Platform_GetClipboardTextFn)(ImGuiContext* ctx); void (*Platform_SetClipboardTextFn)(ImGuiContext* ctx, const char* text); void* Platform_ClipboardUserData; // Optional: Open link/folder/file in OS Shell // (default to use ShellExecuteA() on Windows, system() on Linux/Mac) bool (*Platform_OpenInShellFn)(ImGuiContext* ctx, const char* path); void* Platform_OpenInShellUserData; // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) // (default to use native imm32 api on Windows) void (*Platform_SetImeDataFn)(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data); void* Platform_ImeUserData; //void (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data); // [Renamed to platform_io.PlatformSetImeDataFn in 1.91.1] // Optional: Platform locale // [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point ImWchar Platform_LocaleDecimalPoint; // '.' } ImGuiPlatformIO; // (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. typedef struct ImGuiPlatformImeData_t { bool WantVisible; // A widget wants the IME to be visible ImVec2 InputPos; // Position of the input cursor float InputLineHeight; // Line height } ImGuiPlatformImeData; //----------------------------------------------------------------------------- // [SECTION] Obsolete functions and types // (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) // Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead. //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // OBSOLETED in 1.91.0 (from July 2024) CIMGUI_API void ImGui_PushButtonRepeat(bool repeat); CIMGUI_API void ImGui_PopButtonRepeat(void); CIMGUI_API void ImGui_PushTabStop(bool tab_stop); CIMGUI_API void ImGui_PopTabStop(void); CIMGUI_API ImVec2 ImGui_GetContentRegionMax(void); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! CIMGUI_API ImVec2 ImGui_GetWindowContentRegionMin(void); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! CIMGUI_API ImVec2 ImGui_GetWindowContentRegionMax(void); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // OBSOLETED in 1.90.0 (from September 2023) CIMGUI_API bool ImGui_BeginChildFrame(ImGuiID id, ImVec2 size); // Implied window_flags = 0 CIMGUI_API bool ImGui_BeginChildFrameEx(ImGuiID id, ImVec2 size, ImGuiWindowFlags window_flags /* = 0 */); CIMGUI_API void ImGui_EndChildFrame(void); //static inline bool BeginChild(const char* str_id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags){ return BeginChild(str_id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders //static inline bool BeginChild(ImGuiID id, const ImVec2& size_arg, bool borders, ImGuiWindowFlags window_flags) { return BeginChild(id, size_arg, borders ? ImGuiChildFlags_Borders : ImGuiChildFlags_None, window_flags); } // Unnecessary as true == ImGuiChildFlags_Borders CIMGUI_API void ImGui_ShowStackToolWindow(bool* p_open /* = NULL */); CIMGUI_API bool ImGui_ComboObsolete(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count); // Implied popup_max_height_in_items = -1 CIMGUI_API bool ImGui_ComboObsoleteEx(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items /* = -1 */); CIMGUI_API bool ImGui_ListBoxObsolete(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count); // Implied height_in_items = -1 CIMGUI_API bool ImGui_ListBoxObsoleteEx(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items /* = -1 */); // OBSOLETED in 1.89.7 (from June 2023) CIMGUI_API void ImGui_SetItemAllowOverlap(void); // Use SetNextItemAllowOverlap() before item. // OBSOLETED in 1.89.4 (from March 2023) CIMGUI_API void ImGui_PushAllowKeyboardFocus(bool tab_stop); CIMGUI_API void ImGui_PopAllowKeyboardFocus(void); // OBSOLETED in 1.87 (from February 2022 but more formally obsoleted April 2024) CIMGUI_API ImGuiKey ImGui_GetKeyIndex(ImGuiKey key); // Map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]. When using a 1.87+ backend using io.AddKeyEvent(), calling GetKeyIndex() with ANY ImGuiKey_XXXX values will return the same value! //static inline ImGuiKey GetKeyIndex(ImGuiKey key) { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END); return key; } // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) //-- OBSOLETED in 1.89 (from August 2022) //IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // --> Use new ImageButton() signature (explicit item id, regular FramePadding). Refer to code in 1.91 if you want to grab a copy of this version. //-- OBSOLETED in 1.88 (from May 2022) //static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. //static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. //-- OBSOLETED in 1.86 (from November 2021) //IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper. //-- OBSOLETED in 1.85 (from August 2021) //static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; } //-- OBSOLETED in 1.81 (from February 2021) //static inline bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)) { return BeginListBox(label, size); } //static inline bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1) { float height = GetTextLineHeightWithSpacing() * ((height_in_items < 0 ? ImMin(items_count, 7) : height_in_items) + 0.25f) + GetStyle().FramePadding.y * 2.0f; return BeginListBox(label, ImVec2(0.0f, height)); } // Helper to calculate size from items_count and height_in_items //static inline void ListBoxFooter() { EndListBox(); } //-- OBSOLETED in 1.79 (from August 2020) //static inline void OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry! //-- OBSOLETED in 1.78 (from June 2020): Old drag/sliders functions that took a 'float power > 1.0f' argument instead of ImGuiSliderFlags_Logarithmic. See github.com/ocornut/imgui/issues/3361 for details. //IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f) // OBSOLETED in 1.78 (from June 2020) //IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) //IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) //IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power = 1.0f); // OBSOLETED in 1.78 (from June 2020) //static inline bool DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //static inline bool DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //static inline bool DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //static inline bool DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power = 1.0f) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //static inline bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //static inline bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //static inline bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //static inline bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power = 1.0f) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } // OBSOLETED in 1.78 (from June 2020) //-- OBSOLETED in 1.77 and before //static inline bool BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); } // OBSOLETED in 1.77 (from June 2020) //static inline void TreeAdvanceToLabelPos() { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); } // OBSOLETED in 1.72 (from July 2019) //static inline void SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); } // OBSOLETED in 1.71 (from June 2019) //static inline float GetContentRegionAvailWidth() { return GetContentRegionAvail().x; } // OBSOLETED in 1.70 (from May 2019) //static inline ImDrawList* GetOverlayDrawList() { return GetForegroundDrawList(); } // OBSOLETED in 1.69 (from Mar 2019) //static inline void SetScrollHere(float ratio = 0.5f) { SetScrollHereY(ratio); } // OBSOLETED in 1.66 (from Nov 2018) //static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } // OBSOLETED in 1.63 (from Aug 2018) //-- OBSOLETED in 1.60 and before //static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } // OBSOLETED in 1.60 (from Apr 2018) //static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018) //static inline void ShowTestWindow() { return ShowDemoWindow(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) //static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) //static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) //static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) //static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) //IMGUI_API bool Begin(char* name, bool* p_open, ImVec2 size_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags=0); // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017): Equivalent of using SetNextWindowSize(size, ImGuiCond_FirstUseEver) and SetNextWindowBgAlpha(). //static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) //static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) //static inline void SetNextWindowPosCenter(ImGuiCond c=0) { SetNextWindowPos(GetMainViewport()->GetCenter(), c, ImVec2(0.5f,0.5f)); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) //static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) //static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017): This was misleading and partly broken. You probably want to use the io.WantCaptureMouse flag instead. //static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) //static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) //-- OBSOLETED in 1.50 and before //static inline bool CollapsingHeader(char* label, const char* str_id, bool framed = true, bool default_open = false) { return CollapsingHeader(label, (default_open ? (1 << 5) : 0)); } // OBSOLETED in 1.49 //static inline ImFont*GetWindowFont() { return GetFont(); } // OBSOLETED in 1.48 //static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETED in 1.48 //static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETED in 1.42 //-- OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect() //typedef ImDrawFlags ImDrawCornerFlags; //enum ImDrawCornerFlags_ //{ // ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit // ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). // ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. // ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. // ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. // ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 // ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, // ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, // ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, // ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, //}; // RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) // RENAMED ImGuiKeyModFlags -> ImGuiModFlags in 1.88 (from April 2022). Exceptionally commented out ahead of obscolescence schedule to reduce confusion and because they were not meant to be used in the first place. //typedef ImGuiKeyChord ImGuiModFlags; // == int. We generally use ImGuiKeyChord to mean "a ImGuiKey or-ed with any number of ImGuiMod_XXX value", so you may store mods in there. //enum ImGuiModFlags_ { ImGuiModFlags_None = 0, ImGuiModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiModFlags_Shift = ImGuiMod_Shift, ImGuiModFlags_Alt = ImGuiMod_Alt, ImGuiModFlags_Super = ImGuiMod_Super }; //typedef ImGuiKeyChord ImGuiKeyModFlags; // == int //enum ImGuiKeyModFlags_ { ImGuiKeyModFlags_None = 0, ImGuiKeyModFlags_Ctrl = ImGuiMod_Ctrl, ImGuiKeyModFlags_Shift = ImGuiMod_Shift, ImGuiKeyModFlags_Alt = ImGuiMod_Alt, ImGuiKeyModFlags_Super = ImGuiMod_Super }; #define IM_OFFSETOF(_TYPE,_MEMBER) offsetof(_TYPE, _MEMBER) // OBSOLETED IN 1.90 (now using C++11 standard version) #endif// #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // RENAMED IMGUI_DISABLE_METRICS_WINDOW > IMGUI_DISABLE_DEBUG_TOOLS in 1.88 (from June 2022) #if defined(IMGUI_DISABLE_METRICS_WINDOW)&&!defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS)&&!defined(IMGUI_DISABLE_DEBUG_TOOLS) #define IMGUI_DISABLE_DEBUG_TOOLS #endif // #if defined(IMGUI_DISABLE_METRICS_WINDOW)&&!defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS)&&!defined(IMGUI_DISABLE_DEBUG_TOOLS) #if defined(IMGUI_DISABLE_METRICS_WINDOW)&& defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) #error IMGUI_DISABLE_METRICS_WINDOW was renamed to IMGUI_DISABLE_DEBUG_TOOLS, please use new name. #endif // #if defined(IMGUI_DISABLE_METRICS_WINDOW)&& defined(IMGUI_DISABLE_OBSOLETE_FUNCTIONS) //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #else #if defined(__GNUC__) #pragma GCC diagnostic pop #endif // #if defined(__GNUC__) #endif // #if defined(__clang__) #ifdef _MSC_VER #pragma warning (pop) #endif // #ifdef _MSC_VER // Include imgui_user.h at the end of imgui.h // May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included. #ifdef IMGUI_INCLUDE_IMGUI_USER_H #ifdef IMGUI_USER_H_FILENAME #include IMGUI_USER_H_FILENAME #else #include "imgui_user.h" #endif // #ifdef IMGUI_USER_H_FILENAME #endif // #ifdef IMGUI_INCLUDE_IMGUI_USER_H #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_glut.cpp
// dear imgui: Platform Backend for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! // !!! Nowadays, prefer using GLFW or SDL instead! // Implemented features: // [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I // [ ] Platform: Missing horizontal mouse wheel support. // [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2023-04-17: BREAKING: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame(). Needs to be called from the main application loop, like with every other backends. // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2019-04-03: Misc: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. // 2019-03-25: Misc: Made io.DeltaTime always above zero. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-03-22: Added GLUT Platform binding. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_glut.h" #define GL_SILENCE_DEPRECATION #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif #ifdef _MSC_VER #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #endif static int g_Time = 0; // Current time, in milliseconds // Glut has 1 function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above. static ImGuiKey ImGui_ImplGLUT_KeyToImGuiKey(int key) { switch (key) { case '\t': return ImGuiKey_Tab; case 256 + GLUT_KEY_LEFT: return ImGuiKey_LeftArrow; case 256 + GLUT_KEY_RIGHT: return ImGuiKey_RightArrow; case 256 + GLUT_KEY_UP: return ImGuiKey_UpArrow; case 256 + GLUT_KEY_DOWN: return ImGuiKey_DownArrow; case 256 + GLUT_KEY_PAGE_UP: return ImGuiKey_PageUp; case 256 + GLUT_KEY_PAGE_DOWN: return ImGuiKey_PageDown; case 256 + GLUT_KEY_HOME: return ImGuiKey_Home; case 256 + GLUT_KEY_END: return ImGuiKey_End; case 256 + GLUT_KEY_INSERT: return ImGuiKey_Insert; case 127: return ImGuiKey_Delete; case 8: return ImGuiKey_Backspace; case ' ': return ImGuiKey_Space; case 13: return ImGuiKey_Enter; case 27: return ImGuiKey_Escape; case 39: return ImGuiKey_Apostrophe; case 44: return ImGuiKey_Comma; case 45: return ImGuiKey_Minus; case 46: return ImGuiKey_Period; case 47: return ImGuiKey_Slash; case 59: return ImGuiKey_Semicolon; case 61: return ImGuiKey_Equal; case 91: return ImGuiKey_LeftBracket; case 92: return ImGuiKey_Backslash; case 93: return ImGuiKey_RightBracket; case 96: return ImGuiKey_GraveAccent; //case 0: return ImGuiKey_CapsLock; //case 0: return ImGuiKey_ScrollLock; case 256 + 0x006D: return ImGuiKey_NumLock; //case 0: return ImGuiKey_PrintScreen; //case 0: return ImGuiKey_Pause; //case '0': return ImGuiKey_Keypad0; //case '1': return ImGuiKey_Keypad1; //case '2': return ImGuiKey_Keypad2; //case '3': return ImGuiKey_Keypad3; //case '4': return ImGuiKey_Keypad4; //case '5': return ImGuiKey_Keypad5; //case '6': return ImGuiKey_Keypad6; //case '7': return ImGuiKey_Keypad7; //case '8': return ImGuiKey_Keypad8; //case '9': return ImGuiKey_Keypad9; //case 46: return ImGuiKey_KeypadDecimal; //case 47: return ImGuiKey_KeypadDivide; case 42: return ImGuiKey_KeypadMultiply; //case 45: return ImGuiKey_KeypadSubtract; case 43: return ImGuiKey_KeypadAdd; //case 13: return ImGuiKey_KeypadEnter; //case 0: return ImGuiKey_KeypadEqual; case 256 + 0x0072: return ImGuiKey_LeftCtrl; case 256 + 0x0070: return ImGuiKey_LeftShift; case 256 + 0x0074: return ImGuiKey_LeftAlt; //case 0: return ImGuiKey_LeftSuper; case 256 + 0x0073: return ImGuiKey_RightCtrl; case 256 + 0x0071: return ImGuiKey_RightShift; case 256 + 0x0075: return ImGuiKey_RightAlt; //case 0: return ImGuiKey_RightSuper; //case 0: return ImGuiKey_Menu; case '0': return ImGuiKey_0; case '1': return ImGuiKey_1; case '2': return ImGuiKey_2; case '3': return ImGuiKey_3; case '4': return ImGuiKey_4; case '5': return ImGuiKey_5; case '6': return ImGuiKey_6; case '7': return ImGuiKey_7; case '8': return ImGuiKey_8; case '9': return ImGuiKey_9; case 'A': case 'a': return ImGuiKey_A; case 'B': case 'b': return ImGuiKey_B; case 'C': case 'c': return ImGuiKey_C; case 'D': case 'd': return ImGuiKey_D; case 'E': case 'e': return ImGuiKey_E; case 'F': case 'f': return ImGuiKey_F; case 'G': case 'g': return ImGuiKey_G; case 'H': case 'h': return ImGuiKey_H; case 'I': case 'i': return ImGuiKey_I; case 'J': case 'j': return ImGuiKey_J; case 'K': case 'k': return ImGuiKey_K; case 'L': case 'l': return ImGuiKey_L; case 'M': case 'm': return ImGuiKey_M; case 'N': case 'n': return ImGuiKey_N; case 'O': case 'o': return ImGuiKey_O; case 'P': case 'p': return ImGuiKey_P; case 'Q': case 'q': return ImGuiKey_Q; case 'R': case 'r': return ImGuiKey_R; case 'S': case 's': return ImGuiKey_S; case 'T': case 't': return ImGuiKey_T; case 'U': case 'u': return ImGuiKey_U; case 'V': case 'v': return ImGuiKey_V; case 'W': case 'w': return ImGuiKey_W; case 'X': case 'x': return ImGuiKey_X; case 'Y': case 'y': return ImGuiKey_Y; case 'Z': case 'z': return ImGuiKey_Z; case 256 + GLUT_KEY_F1: return ImGuiKey_F1; case 256 + GLUT_KEY_F2: return ImGuiKey_F2; case 256 + GLUT_KEY_F3: return ImGuiKey_F3; case 256 + GLUT_KEY_F4: return ImGuiKey_F4; case 256 + GLUT_KEY_F5: return ImGuiKey_F5; case 256 + GLUT_KEY_F6: return ImGuiKey_F6; case 256 + GLUT_KEY_F7: return ImGuiKey_F7; case 256 + GLUT_KEY_F8: return ImGuiKey_F8; case 256 + GLUT_KEY_F9: return ImGuiKey_F9; case 256 + GLUT_KEY_F10: return ImGuiKey_F10; case 256 + GLUT_KEY_F11: return ImGuiKey_F11; case 256 + GLUT_KEY_F12: return ImGuiKey_F12; default: return ImGuiKey_None; } } bool ImGui_ImplGLUT_Init() { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); #ifdef FREEGLUT io.BackendPlatformName = "imgui_impl_glut (freeglut)"; #else io.BackendPlatformName = "imgui_impl_glut"; #endif g_Time = 0; return true; } void ImGui_ImplGLUT_InstallFuncs() { glutReshapeFunc(ImGui_ImplGLUT_ReshapeFunc); glutMotionFunc(ImGui_ImplGLUT_MotionFunc); glutPassiveMotionFunc(ImGui_ImplGLUT_MotionFunc); glutMouseFunc(ImGui_ImplGLUT_MouseFunc); #ifdef __FREEGLUT_EXT_H__ glutMouseWheelFunc(ImGui_ImplGLUT_MouseWheelFunc); #endif glutKeyboardFunc(ImGui_ImplGLUT_KeyboardFunc); glutKeyboardUpFunc(ImGui_ImplGLUT_KeyboardUpFunc); glutSpecialFunc(ImGui_ImplGLUT_SpecialFunc); glutSpecialUpFunc(ImGui_ImplGLUT_SpecialUpFunc); } void ImGui_ImplGLUT_Shutdown() { ImGuiIO& io = ImGui::GetIO(); io.BackendPlatformName = nullptr; } void ImGui_ImplGLUT_NewFrame() { // Setup time step ImGuiIO& io = ImGui::GetIO(); int current_time = glutGet(GLUT_ELAPSED_TIME); int delta_time_ms = (current_time - g_Time); if (delta_time_ms <= 0) delta_time_ms = 1; io.DeltaTime = delta_time_ms / 1000.0f; g_Time = current_time; } static void ImGui_ImplGLUT_UpdateKeyModifiers() { ImGuiIO& io = ImGui::GetIO(); int glut_key_mods = glutGetModifiers(); io.AddKeyEvent(ImGuiMod_Ctrl, (glut_key_mods & GLUT_ACTIVE_CTRL) != 0); io.AddKeyEvent(ImGuiMod_Shift, (glut_key_mods & GLUT_ACTIVE_SHIFT) != 0); io.AddKeyEvent(ImGuiMod_Alt, (glut_key_mods & GLUT_ACTIVE_ALT) != 0); } static void ImGui_ImplGLUT_AddKeyEvent(ImGuiKey key, bool down, int native_keycode) { ImGuiIO& io = ImGui::GetIO(); io.AddKeyEvent(key, down); io.SetKeyEventNativeData(key, native_keycode, -1); // To support legacy indexing (<1.87 user code) } void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) { // Send character to imgui //printf("char_down_func %d '%c'\n", c, c); ImGuiIO& io = ImGui::GetIO(); if (c >= 32) io.AddInputCharacter((unsigned int)c); ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c); ImGui_ImplGLUT_AddKeyEvent(key, true, c); ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y) { //printf("char_up_func %d '%c'\n", c, c); ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c); ImGui_ImplGLUT_AddKeyEvent(key, false, c); ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y) { //printf("key_down_func %d\n", key); ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256); ImGui_ImplGLUT_AddKeyEvent(imgui_key, true, key + 256); ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y) { //printf("key_up_func %d\n", key); ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256); ImGui_ImplGLUT_AddKeyEvent(imgui_key, false, key + 256); ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_MouseFunc(int glut_button, int state, int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.AddMousePosEvent((float)x, (float)y); int button = -1; if (glut_button == GLUT_LEFT_BUTTON) button = 0; if (glut_button == GLUT_RIGHT_BUTTON) button = 1; if (glut_button == GLUT_MIDDLE_BUTTON) button = 2; if (button != -1 && (state == GLUT_DOWN || state == GLUT_UP)) io.AddMouseButtonEvent(button, state == GLUT_DOWN); } #ifdef __FREEGLUT_EXT_H__ void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.AddMousePosEvent((float)x, (float)y); if (dir != 0) io.AddMouseWheelEvent(0.0f, dir > 0 ? 1.0f : -1.0f); (void)button; // Unused } #endif void ImGui_ImplGLUT_ReshapeFunc(int w, int h) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2((float)w, (float)h); } void ImGui_ImplGLUT_MotionFunc(int x, int y) { ImGuiIO& io = ImGui::GetIO(); io.AddMousePosEvent((float)x, (float)y); } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx12.h
// dear imgui: Renderer Backend for DirectX12 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // See imgui_impl_dx12.cpp file for details. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE #include <dxgiformat.h> // DXGI_FORMAT struct ID3D12Device; struct ID3D12DescriptorHeap; struct ID3D12GraphicsCommandList; struct D3D12_CPU_DESCRIPTOR_HANDLE; struct D3D12_GPU_DESCRIPTOR_HANDLE; // Follow "Getting Started" link and check examples/ folder to learn about using backends! // cmd_list is the command list that the implementation will use to render imgui draw lists. // Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate // render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle. // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture. IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle); IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_opengl3.cpp
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline // - Desktop GL: 2.x 3.x 4.x // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). // About WebGL/ES: // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. // - This is done automatically on iOS, Android and Emscripten targets. // - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748) // 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562) // 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447) // 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink. // 2023-11-08: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983) // 2023-10-05: OpenGL: Rename symbols in our internal loader so that LTO compilation with another copy of gl3w is possible. (#6875, #6668, #4445) // 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333) // 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375) // 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333) // 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224) // 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530) // 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224) // 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes). // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-09-27: OpenGL: Added ability to '#define IMGUI_IMPL_OPENGL_DEBUG'. // 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127). // 2022-05-13: OpenGL: Fixed state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states. // 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers. // 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions. // 2021-08-19: OpenGL: Embed and use our own minimal GL loader (imgui_impl_opengl3_loader.h), removing requirement and support for third-party loader. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-06-25: OpenGL: Use OES_vertex_array extension on Emscripten + backup/restore current state. // 2021-06-21: OpenGL: Destroy individual vertex/fragment shader objects right after they are linked into the main shader. // 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version. // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater. // 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer. // 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state. // 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state. // 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x) // 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader. // 2020-07-10: OpenGL: Added support for glad2 OpenGL loader. // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX. // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix. // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset. // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader. // 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader. // 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders. // 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility. // 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call. // 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop. // 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early. // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0). // 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN. // 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used. // 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES". // 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation. // 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link. // 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples. // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state. // 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a nullptr pointer. // 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150". // 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself. // 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150. // 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode. // 2017-05-01: OpenGL: Fixed save and restore of current blend func state. // 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE. // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. // 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752) //---------------------------------------- // OpenGL GLSL GLSL // version version string //---------------------------------------- // 2.0 110 "#version 110" // 2.1 120 "#version 120" // 3.0 130 "#version 130" // 3.1 140 "#version 140" // 3.2 150 "#version 150" // 3.3 330 "#version 330 core" // 4.0 400 "#version 400 core" // 4.1 410 "#version 410 core" // 4.2 420 "#version 410 core" // 4.3 430 "#version 430 core" // ES 2.0 100 "#version 100" = WebGL 1.0 // ES 3.0 300 "#version 300 es" = WebGL 2.0 //---------------------------------------- #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_opengl3.h" #include <stdio.h> #include <stdint.h> // intptr_t #if defined(__APPLE__) #include <TargetConditionals.h> #endif // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: ignore unknown flags #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used #pragma clang diagnostic ignored "-Wnonportable-system-include-path" #pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) #endif #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' #pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) #endif // GL includes #if defined(IMGUI_IMPL_OPENGL_ES2) #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) #include <OpenGLES/ES2/gl.h> // Use GL ES 2 #else #include <GLES2/gl2.h> // Use GL ES 2 #endif #if defined(__EMSCRIPTEN__) #ifndef GL_GLEXT_PROTOTYPES #define GL_GLEXT_PROTOTYPES #endif #include <GLES2/gl2ext.h> #endif #elif defined(IMGUI_IMPL_OPENGL_ES3) #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) #include <OpenGLES/ES3/gl.h> // Use GL ES 3 #else #include <GLES3/gl3.h> // Use GL ES 3 #endif #elif !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers. // Helper libraries are often used for this purpose! Here we are using our own minimal custom loader based on gl3w. // In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.). // If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp): // - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped // - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases // Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version. #define IMGL3W_IMPL #include "imgui_impl_opengl3_loader.h" #endif // Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension #ifndef IMGUI_IMPL_OPENGL_ES2 #define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY #elif defined(__EMSCRIPTEN__) #define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY #define glBindVertexArray glBindVertexArrayOES #define glGenVertexArrays glGenVertexArraysOES #define glDeleteVertexArrays glDeleteVertexArraysOES #define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES #endif // Desktop GL 2.0+ has extension and glPolygonMode() which GL ES and WebGL don't have.. // A desktop ES context can technically compile fine with our loader, so we also perform a runtime checks #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) #define IMGUI_IMPL_OPENGL_HAS_EXTENSIONS // has glGetIntegerv(GL_NUM_EXTENSIONS) #define IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE // may have glPolygonMode() #endif // Desktop GL 2.1+ and GL ES 3.0+ have glBindBuffer() with GL_PIXEL_UNPACK_BUFFER target. #if !defined(IMGUI_IMPL_OPENGL_ES2) #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK #endif // Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1) #define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART #endif // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have. #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2) #define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET #endif // Desktop GL 3.3+ and GL ES 3.0+ have glBindSampler() #if !defined(IMGUI_IMPL_OPENGL_ES2) && (defined(IMGUI_IMPL_OPENGL_ES3) || defined(GL_VERSION_3_3)) #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER #endif // [Debugging] //#define IMGUI_IMPL_OPENGL_DEBUG #ifdef IMGUI_IMPL_OPENGL_DEBUG #include <stdio.h> #define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check #else #define GL_CALL(_CALL) _CALL // Call without error check #endif // OpenGL Data struct ImGui_ImplOpenGL3_Data { GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2) char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings. bool GlProfileIsES2; bool GlProfileIsES3; bool GlProfileIsCompat; GLint GlProfileMask; GLuint FontTexture; GLuint ShaderHandle; GLint AttribLocationTex; // Uniforms location GLint AttribLocationProjMtx; GLuint AttribLocationVtxPos; // Vertex attributes location GLuint AttribLocationVtxUV; GLuint AttribLocationVtxColor; unsigned int VboHandle, ElementsHandle; GLsizeiptr VertexBufferSize; GLsizeiptr IndexBufferSize; bool HasPolygonMode; bool HasClipOrigin; bool UseBufferSubData; ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only) #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY struct ImGui_ImplOpenGL3_VtxAttribState { GLint Enabled, Size, Type, Normalized, Stride; GLvoid* Ptr; void GetState(GLint index) { glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled); glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size); glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type); glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized); glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride); glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr); } void SetState(GLint index) { glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr); if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index); } }; #endif // Functions bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Initialize our loader #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) if (imgl3wInit() != 0) { fprintf(stderr, "Failed to initialize OpenGL loader!\n"); return false; } #endif // Setup backend capabilities flags ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_opengl3"; // Query for GL version (e.g. 320 for GL 3.2) #if defined(IMGUI_IMPL_OPENGL_ES2) // GLES 2 bd->GlVersion = 200; bd->GlProfileIsES2 = true; #else // Desktop or GLES 3 const char* gl_version_str = (const char*)glGetString(GL_VERSION); GLint major = 0; GLint minor = 0; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); if (major == 0 && minor == 0) sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>" bd->GlVersion = (GLuint)(major * 100 + minor * 10); #if defined(GL_CONTEXT_PROFILE_MASK) if (bd->GlVersion >= 320) glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask); bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; #endif #if defined(IMGUI_IMPL_OPENGL_ES3) bd->GlProfileIsES3 = true; #else if (strncmp(gl_version_str, "OpenGL ES 3", 11) == 0) bd->GlProfileIsES3 = true; #endif bd->UseBufferSubData = false; /* // Query vendor to enable glBufferSubData kludge #ifdef _WIN32 if (const char* vendor = (const char*)glGetString(GL_VENDOR)) if (strncmp(vendor, "Intel", 5) == 0) bd->UseBufferSubData = true; #endif */ #endif #ifdef IMGUI_IMPL_OPENGL_DEBUG printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG] #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET if (bd->GlVersion >= 320) io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. #endif // Store GLSL version string so we can refer to it later in case we recreate shaders. // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure. if (glsl_version == nullptr) { #if defined(IMGUI_IMPL_OPENGL_ES2) glsl_version = "#version 100"; #elif defined(IMGUI_IMPL_OPENGL_ES3) glsl_version = "#version 300 es"; #elif defined(__APPLE__) glsl_version = "#version 150"; #else glsl_version = "#version 130"; #endif } IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(bd->GlslVersionString)); strcpy(bd->GlslVersionString, glsl_version); strcat(bd->GlslVersionString, "\n"); // Make an arbitrary GL call (we don't actually need the result) // IF YOU GET A CRASH HERE: it probably means the OpenGL function loader didn't do its job. Let us know! GLint current_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture); // Detect extensions we support #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE bd->HasPolygonMode = (!bd->GlProfileIsES2 && !bd->GlProfileIsES3); #endif bd->HasClipOrigin = (bd->GlVersion >= 450); #ifdef IMGUI_IMPL_OPENGL_HAS_EXTENSIONS GLint num_extensions = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); for (GLint i = 0; i < num_extensions; i++) { const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i); if (extension != nullptr && strcmp(extension, "GL_ARB_clip_control") == 0) bd->HasClipOrigin = true; } #endif return true; } void ImGui_ImplOpenGL3_Shutdown() { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL3_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplOpenGL3_NewFrame() { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?"); if (!bd->ShaderHandle) ImGui_ImplOpenGL3_CreateDeviceObjects(); if (!bd->FontTexture) ImGui_ImplOpenGL3_CreateFontsTexture(); } static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object) { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_STENCIL_TEST); glEnable(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART if (bd->GlVersion >= 310) glDisable(GL_PRIMITIVE_RESTART); #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE if (bd->HasPolygonMode) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) #if defined(GL_CLIP_ORIGIN) bool clip_origin_lower_left = true; if (bd->HasClipOrigin) { GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin); if (current_clip_origin == GL_UPPER_LEFT) clip_origin_lower_left = false; } #endif // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height)); float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; #if defined(GL_CLIP_ORIGIN) if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left #endif const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f }, }; glUseProgram(bd->ShaderHandle); glUniform1i(bd->AttribLocationTex, 0); glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER if (bd->GlVersion >= 330 || bd->GlProfileIsES3) glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise. #endif (void)vertex_array_object; #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY glBindVertexArray(vertex_array_object); #endif // Bind vertex/index buffers and setup attributes for ImDrawVert GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle)); GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle)); GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos)); GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV)); GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor)); GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos))); GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv))); GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col))); } // OpenGL3 Render function. // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. // This is in order to be able to run within an OpenGL engine that doesn't do so. void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width <= 0 || fb_height <= 0) return; ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); // Backup GL state GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture); glActiveTexture(GL_TEXTURE0); GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER GLuint last_sampler; if (bd->GlVersion >= 330 || bd->GlProfileIsES3) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } #endif GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY // This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+. GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos); ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV); ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor); #endif #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object); #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE GLint last_polygon_mode[2]; if (bd->HasPolygonMode) { glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); } #endif GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); 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_stencil_test = glIsEnabled(GL_STENCIL_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART GLboolean last_enable_primitive_restart = (bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; #endif // Setup desired GL state // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound. GLuint vertex_array_object = 0; #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY GL_CALL(glGenVertexArrays(1, &vertex_array_object)); #endif ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; // Upload vertex/index buffers // - OpenGL drivers are in a very sorry state nowadays.... // During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports // of leaks on Intel GPU when using multi-viewports on Windows. // - After this we kept hearing of various display corruptions issues. We started disabling on non-Intel GPU, but issues still got reported on Intel. // - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code. // We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path. // - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues. const GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert); const GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx); if (bd->UseBufferSubData) { if (bd->VertexBufferSize < vtx_buffer_size) { bd->VertexBufferSize = vtx_buffer_size; GL_CALL(glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, nullptr, GL_STREAM_DRAW)); } if (bd->IndexBufferSize < idx_buffer_size) { bd->IndexBufferSize = idx_buffer_size; GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW)); } GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data)); GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data)); } else { GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW)); GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW)); } for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply scissor/clipping rectangle (Y is inverted in OpenGL) GL_CALL(glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y))); // Bind texture, Draw GL_CALL(glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID())); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET if (bd->GlVersion >= 320) GL_CALL(glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset)); else #endif GL_CALL(glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)))); } } } // Destroy the temporary VAO #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY GL_CALL(glDeleteVertexArrays(1, &vertex_array_object)); #endif // Restore modified GL state // This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220. if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER if (bd->GlVersion >= 330 || bd->GlProfileIsES3) glBindSampler(0, last_sampler); #endif glActiveTexture(last_active_texture); #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY glBindVertexArray(last_vertex_array_object); #endif glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos); last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV); last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor); #endif glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); 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_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE // Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons if (bd->HasPolygonMode) { if (bd->GlVersion <= 310 || bd->GlProfileIsCompat) { glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]); } else { glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); } } #endif // IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE 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]); (void)bd; // Not all compilation paths use this } bool ImGui_ImplOpenGL3_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); // Build texture atlas unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) GLint last_texture; GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); GL_CALL(glGenTextures(1, &bd->FontTexture)); GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); #ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); #endif GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); // Restore state GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); return true; } void ImGui_ImplOpenGL3_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); if (bd->FontTexture) { glDeleteTextures(1, &bd->FontTexture); io.Fonts->SetTexID(0); bd->FontTexture = 0; } } // If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file. static bool CheckShader(GLuint handle, const char* desc) { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); GLint status = 0, log_length = 0; glGetShaderiv(handle, GL_COMPILE_STATUS, &status); glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length); if ((GLboolean)status == GL_FALSE) fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s! With GLSL: %s\n", desc, bd->GlslVersionString); if (log_length > 1) { ImVector<char> buf; buf.resize((int)(log_length + 1)); glGetShaderInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin()); fprintf(stderr, "%s\n", buf.begin()); } return (GLboolean)status == GL_TRUE; } // If you get an error please report on GitHub. You may try different GL context version or GLSL version. static bool CheckProgram(GLuint handle, const char* desc) { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); GLint status = 0, log_length = 0; glGetProgramiv(handle, GL_LINK_STATUS, &status); glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length); if ((GLboolean)status == GL_FALSE) fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! With GLSL %s\n", desc, bd->GlslVersionString); if (log_length > 1) { ImVector<char> buf; buf.resize((int)(log_length + 1)); glGetProgramInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin()); fprintf(stderr, "%s\n", buf.begin()); } return (GLboolean)status == GL_TRUE; } bool ImGui_ImplOpenGL3_CreateDeviceObjects() { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); // Backup GL state GLint last_texture, last_array_buffer; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK GLint last_pixel_unpack_buffer = 0; if (bd->GlVersion >= 210) { glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &last_pixel_unpack_buffer); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } #endif #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); #endif // Parse GLSL version string int glsl_version = 130; sscanf(bd->GlslVersionString, "#version %d", &glsl_version); const GLchar* vertex_shader_glsl_120 = "uniform mat4 ProjMtx;\n" "attribute vec2 Position;\n" "attribute vec2 UV;\n" "attribute vec4 Color;\n" "varying vec2 Frag_UV;\n" "varying vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* vertex_shader_glsl_130 = "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* vertex_shader_glsl_300_es = "precision highp float;\n" "layout (location = 0) in vec2 Position;\n" "layout (location = 1) in vec2 UV;\n" "layout (location = 2) in vec4 Color;\n" "uniform mat4 ProjMtx;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* vertex_shader_glsl_410_core = "layout (location = 0) in vec2 Position;\n" "layout (location = 1) in vec2 UV;\n" "layout (location = 2) in vec4 Color;\n" "uniform mat4 ProjMtx;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader_glsl_120 = "#ifdef GL_ES\n" " precision mediump float;\n" "#endif\n" "uniform sampler2D Texture;\n" "varying vec2 Frag_UV;\n" "varying vec4 Frag_Color;\n" "void main()\n" "{\n" " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" "}\n"; const GLchar* fragment_shader_glsl_130 = "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" "}\n"; const GLchar* fragment_shader_glsl_300_es = "precision mediump float;\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "layout (location = 0) out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" "}\n"; const GLchar* fragment_shader_glsl_410_core = "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "uniform sampler2D Texture;\n" "layout (location = 0) out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" "}\n"; // Select shaders matching our GLSL versions const GLchar* vertex_shader = nullptr; const GLchar* fragment_shader = nullptr; if (glsl_version < 130) { vertex_shader = vertex_shader_glsl_120; fragment_shader = fragment_shader_glsl_120; } else if (glsl_version >= 410) { vertex_shader = vertex_shader_glsl_410_core; fragment_shader = fragment_shader_glsl_410_core; } else if (glsl_version == 300) { vertex_shader = vertex_shader_glsl_300_es; fragment_shader = fragment_shader_glsl_300_es; } else { vertex_shader = vertex_shader_glsl_130; fragment_shader = fragment_shader_glsl_130; } // Create shaders const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader }; GLuint vert_handle = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr); glCompileShader(vert_handle); CheckShader(vert_handle, "vertex shader"); const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader }; GLuint frag_handle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr); glCompileShader(frag_handle); CheckShader(frag_handle, "fragment shader"); // Link bd->ShaderHandle = glCreateProgram(); glAttachShader(bd->ShaderHandle, vert_handle); glAttachShader(bd->ShaderHandle, frag_handle); glLinkProgram(bd->ShaderHandle); CheckProgram(bd->ShaderHandle, "shader program"); glDetachShader(bd->ShaderHandle, vert_handle); glDetachShader(bd->ShaderHandle, frag_handle); glDeleteShader(vert_handle); glDeleteShader(frag_handle); bd->AttribLocationTex = glGetUniformLocation(bd->ShaderHandle, "Texture"); bd->AttribLocationProjMtx = glGetUniformLocation(bd->ShaderHandle, "ProjMtx"); bd->AttribLocationVtxPos = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Position"); bd->AttribLocationVtxUV = (GLuint)glGetAttribLocation(bd->ShaderHandle, "UV"); bd->AttribLocationVtxColor = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Color"); // Create buffers glGenBuffers(1, &bd->VboHandle); glGenBuffers(1, &bd->ElementsHandle); ImGui_ImplOpenGL3_CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK if (bd->GlVersion >= 210) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, last_pixel_unpack_buffer); } #endif #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY glBindVertexArray(last_vertex_array); #endif return true; } void ImGui_ImplOpenGL3_DestroyDeviceObjects() { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; } if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; } if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; } ImGui_ImplOpenGL3_DestroyFontsTexture(); } //----------------------------------------------------------------------------- #if defined(__GNUC__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx12.cpp
// dear imgui: Renderer Backend for DirectX12 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // To build this on 32-bit systems: // - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file) // - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. // - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) // - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file) // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer. // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically. // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning. // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID. // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function. // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Various minor tidying up. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData(). // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example. // 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport). // 2018-02-22: Merged into master with all Win32 code synchronized to other examples. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_dx12.h" // DirectX #include <d3d12.h> #include <dxgi1_4.h> #include <d3dcompiler.h> #ifdef _MSC_VER #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif // DirectX data struct ImGui_ImplDX12_RenderBuffers; struct ImGui_ImplDX12_Data { ID3D12Device* pd3dDevice; ID3D12RootSignature* pRootSignature; ID3D12PipelineState* pPipelineState; DXGI_FORMAT RTVFormat; ID3D12Resource* pFontTextureResource; D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle; D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle; ID3D12DescriptorHeap* pd3dSrvDescHeap; UINT numFramesInFlight; ImGui_ImplDX12_RenderBuffers* pFrameResources; UINT frameIndex; ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Buffers used during the rendering of a frame struct ImGui_ImplDX12_RenderBuffers { ID3D12Resource* IndexBuffer; ID3D12Resource* VertexBuffer; int IndexBufferSize; int VertexBufferSize; }; struct VERTEX_CONSTANT_BUFFER_DX12 { float mvp[4][4]; }; // Functions static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr) { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer; { float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; float mvp[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, { 0.0f, 0.0f, 0.5f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp)); } // Setup viewport D3D12_VIEWPORT vp; memset(&vp, 0, sizeof(D3D12_VIEWPORT)); vp.Width = draw_data->DisplaySize.x; vp.Height = draw_data->DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0.0f; ctx->RSSetViewports(1, &vp); // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; D3D12_VERTEX_BUFFER_VIEW vbv; memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW)); vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset; vbv.SizeInBytes = fr->VertexBufferSize * stride; vbv.StrideInBytes = stride; ctx->IASetVertexBuffers(0, 1, &vbv); D3D12_INDEX_BUFFER_VIEW ibv; memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW)); ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress(); ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx); ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; ctx->IASetIndexBuffer(&ibv); ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->SetPipelineState(bd->pPipelineState); ctx->SetGraphicsRootSignature(bd->pRootSignature); ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); // Setup blend factor const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; ctx->OMSetBlendFactor(blend_factor); } template<typename T> static inline void SafeRelease(T*& res) { if (res) res->Release(); res = nullptr; } // Render function void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx) { // Avoid rendering when minimized if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; // FIXME: I'm assuming that this only gets called once per frame! // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); bd->frameIndex = bd->frameIndex + 1; ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight]; // Create and grow vertex/index buffers if needed if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount) { SafeRelease(fr->VertexBuffer); fr->VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; D3D12_RESOURCE_DESC desc; memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC)); desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert); desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.Format = DXGI_FORMAT_UNKNOWN; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) return; } if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount) { SafeRelease(fr->IndexBuffer); fr->IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; D3D12_RESOURCE_DESC desc; memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC)); desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx); desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.Format = DXGI_FORMAT_UNKNOWN; desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) return; } // Upload vertex/index data into a single contiguous GPU buffer void* vtx_resource, *idx_resource; D3D12_RANGE range; memset(&range, 0, sizeof(D3D12_RANGE)); if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK) return; if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK) return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } fr->VertexBuffer->Unmap(0, &range); fr->IndexBuffer->Unmap(0, &range); // Setup desired DX state ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply Scissor/clipping rectangle, Bind texture, Draw const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {}; texture_handle.ptr = (UINT64)pcmd->GetTexID(); ctx->SetGraphicsRootDescriptorTable(1, texture_handle); ctx->RSSetScissorRects(1, &r); ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } } global_idx_offset += cmd_list->IdxBuffer.Size; global_vtx_offset += cmd_list->VtxBuffer.Size; } } static void ImGui_ImplDX12_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system { D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_DEFAULT; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; D3D12_RESOURCE_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Alignment = 0; desc.Width = width; desc.Height = height; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; desc.Flags = D3D12_RESOURCE_FLAG_NONE; ID3D12Resource* pTexture = nullptr; bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture)); UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); UINT uploadSize = height * uploadPitch; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; desc.Alignment = 0; desc.Width = uploadSize; desc.Height = 1; desc.DepthOrArraySize = 1; desc.MipLevels = 1; desc.Format = DXGI_FORMAT_UNKNOWN; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; props.Type = D3D12_HEAP_TYPE_UPLOAD; props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; ID3D12Resource* uploadBuffer = nullptr; HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); IM_ASSERT(SUCCEEDED(hr)); void* mapped = nullptr; D3D12_RANGE range = { 0, uploadSize }; hr = uploadBuffer->Map(0, &range, &mapped); IM_ASSERT(SUCCEEDED(hr)); for (int y = 0; y < height; y++) memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4); uploadBuffer->Unmap(0, &range); D3D12_TEXTURE_COPY_LOCATION srcLocation = {}; srcLocation.pResource = uploadBuffer; srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srcLocation.PlacedFootprint.Footprint.Width = width; srcLocation.PlacedFootprint.Footprint.Height = height; srcLocation.PlacedFootprint.Footprint.Depth = 1; srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch; D3D12_TEXTURE_COPY_LOCATION dstLocation = {}; dstLocation.pResource = pTexture; dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dstLocation.SubresourceIndex = 0; D3D12_RESOURCE_BARRIER barrier = {}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.pResource = pTexture; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; ID3D12Fence* fence = nullptr; hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); IM_ASSERT(SUCCEEDED(hr)); HANDLE event = CreateEvent(0, 0, 0, 0); IM_ASSERT(event != nullptr); D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.NodeMask = 1; ID3D12CommandQueue* cmdQueue = nullptr; hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue)); IM_ASSERT(SUCCEEDED(hr)); ID3D12CommandAllocator* cmdAlloc = nullptr; hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); IM_ASSERT(SUCCEEDED(hr)); ID3D12GraphicsCommandList* cmdList = nullptr; hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList)); IM_ASSERT(SUCCEEDED(hr)); cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr); cmdList->ResourceBarrier(1, &barrier); hr = cmdList->Close(); IM_ASSERT(SUCCEEDED(hr)); cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList); hr = cmdQueue->Signal(fence, 1); IM_ASSERT(SUCCEEDED(hr)); fence->SetEventOnCompletion(1, event); WaitForSingleObject(event, INFINITE); cmdList->Release(); cmdAlloc->Release(); cmdQueue->Release(); CloseHandle(event); fence->Release(); uploadBuffer->Release(); // Create texture view D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle); SafeRelease(bd->pFontTextureResource); bd->pFontTextureResource = pTexture; } // Store our identifier // READ THIS IF THE STATIC_ASSERT() TRIGGERS: // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the 'example_win32_direct12/example_win32_direct12.vcxproj' project file) // [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. // [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) // [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file) static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr); } bool ImGui_ImplDX12_CreateDeviceObjects() { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); if (!bd || !bd->pd3dDevice) return false; if (bd->pPipelineState) ImGui_ImplDX12_InvalidateDeviceObjects(); // Create the root signature { D3D12_DESCRIPTOR_RANGE descRange = {}; descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; descRange.NumDescriptors = 1; descRange.BaseShaderRegister = 0; descRange.RegisterSpace = 0; descRange.OffsetInDescriptorsFromTableStart = 0; D3D12_ROOT_PARAMETER param[2] = {}; param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; param[0].Constants.ShaderRegister = 0; param[0].Constants.RegisterSpace = 0; param[0].Constants.Num32BitValues = 16; param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; param[1].DescriptorTable.NumDescriptorRanges = 1; param[1].DescriptorTable.pDescriptorRanges = &descRange; param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. D3D12_STATIC_SAMPLER_DESC staticSampler = {}; staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_WRAP; staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; staticSampler.MipLODBias = 0.f; staticSampler.MaxAnisotropy = 0; staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; staticSampler.MinLOD = 0.f; staticSampler.MaxLOD = 0.f; staticSampler.ShaderRegister = 0; staticSampler.RegisterSpace = 0; staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; D3D12_ROOT_SIGNATURE_DESC desc = {}; desc.NumParameters = _countof(param); desc.pParameters = param; desc.NumStaticSamplers = 1; desc.pStaticSamplers = &staticSampler; desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll"); if (d3d12_dll == nullptr) { // Attempt to load d3d12.dll from local directories. This will only succeed if // (1) the current OS is Windows 7, and // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories. // See https://github.com/ocornut/imgui/pull/3696 for details. const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++) if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr) break; // If failed, we are on Windows >= 10. if (d3d12_dll == nullptr) d3d12_dll = ::LoadLibraryA("d3d12.dll"); if (d3d12_dll == nullptr) return false; } PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); if (D3D12SerializeRootSignatureFn == nullptr) return false; ID3DBlob* blob = nullptr; if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK) return false; bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature)); blob->Release(); } // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) // If you would like to use this DX12 sample code but remove this dependency you can: // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution] // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc; memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC)); psoDesc.NodeMask = 1; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; psoDesc.pRootSignature = bd->pRootSignature; psoDesc.SampleMask = UINT_MAX; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = bd->RTVFormat; psoDesc.SampleDesc.Count = 1; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; ID3DBlob* vertexShaderBlob; ID3DBlob* pixelShaderBlob; // Create the vertex shader { static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ float2 pos : POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ PS_INPUT output;\ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ output.col = input.col;\ output.uv = input.uv;\ return output;\ }"; if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() }; // Create the input layout static D3D12_INPUT_ELEMENT_DESC local_layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; psoDesc.InputLayout = { local_layout, 3 }; } // Create the pixel shader { static const char* pixelShader = "struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ SamplerState sampler0 : register(s0);\ Texture2D texture0 : register(t0);\ \ float4 main(PS_INPUT input) : SV_Target\ {\ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ return out_col; \ }"; if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr))) { vertexShaderBlob->Release(); return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! } psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() }; } // Create the blending setup { D3D12_BLEND_DESC& desc = psoDesc.BlendState; desc.AlphaToCoverageEnable = false; desc.RenderTarget[0].BlendEnable = true; desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; } // Create the rasterizer state { D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState; desc.FillMode = D3D12_FILL_MODE_SOLID; desc.CullMode = D3D12_CULL_MODE_NONE; desc.FrontCounterClockwise = FALSE; desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS; desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; desc.DepthClipEnable = true; desc.MultisampleEnable = FALSE; desc.AntialiasedLineEnable = FALSE; desc.ForcedSampleCount = 0; desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; } // Create depth-stencil State { D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState; desc.DepthEnable = false; desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; desc.StencilEnable = false; desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP; desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS; desc.BackFace = desc.FrontFace; } HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState)); vertexShaderBlob->Release(); pixelShaderBlob->Release(); if (result_pipeline_state != S_OK) return false; ImGui_ImplDX12_CreateFontsTexture(); return true; } void ImGui_ImplDX12_InvalidateDeviceObjects() { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); if (!bd || !bd->pd3dDevice) return; ImGuiIO& io = ImGui::GetIO(); SafeRelease(bd->pRootSignature); SafeRelease(bd->pPipelineState); SafeRelease(bd->pFontTextureResource); io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. for (UINT i = 0; i < bd->numFramesInFlight; i++) { ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i]; SafeRelease(fr->IndexBuffer); SafeRelease(fr->VertexBuffer); } } bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx12"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. bd->pd3dDevice = device; bd->RTVFormat = rtv_format; bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle; bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle; bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[num_frames_in_flight]; bd->numFramesInFlight = num_frames_in_flight; bd->pd3dSrvDescHeap = cbv_srv_heap; bd->frameIndex = UINT_MAX; // Create buffers with a default size (they will later be grown as needed) for (int i = 0; i < num_frames_in_flight; i++) { ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i]; fr->IndexBuffer = nullptr; fr->VertexBuffer = nullptr; fr->IndexBufferSize = 10000; fr->VertexBufferSize = 5000; } return true; } void ImGui_ImplDX12_Shutdown() { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); // Clean up windows and device objects ImGui_ImplDX12_InvalidateDeviceObjects(); delete[] bd->pFrameResources; io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplDX12_NewFrame() { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?"); if (!bd->pPipelineState) ImGui_ImplDX12_CreateDeviceObjects(); } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdlrenderer3.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for SDL_Renderer for SDL3 // (Requires: SDL 3.0.0+) // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Note how SDL_Renderer is an _optional_ component of SDL3. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and // it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct SDL_Renderer SDL_Renderer; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer3_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer3_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer); // Called by Init/NewFrame/Shutdown CIMGUI_IMPL_API bool cImGui_ImplSDLRenderer3_CreateFontsTexture(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer3_DestroyFontsTexture(void); CIMGUI_IMPL_API bool cImGui_ImplSDLRenderer3_CreateDeviceObjects(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer3_DestroyDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx12.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_dx12.h" #include <stdio.h> #include <d3d12.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_dx12.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX12_Init(cimgui::ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, cimgui::ID3D12DescriptorHeap* cbv_srv_heap, cimgui::D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, cimgui::D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) { return ::ImGui_ImplDX12_Init(reinterpret_cast<::ID3D12Device*>(device), num_frames_in_flight, rtv_format, reinterpret_cast<::ID3D12DescriptorHeap*>(cbv_srv_heap), (*reinterpret_cast<::D3D12_CPU_DESCRIPTOR_HANDLE*>(&font_srv_cpu_desc_handle)), (*reinterpret_cast<::D3D12_GPU_DESCRIPTOR_HANDLE*>(&font_srv_gpu_desc_handle))); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX12_Shutdown(void) { ::ImGui_ImplDX12_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX12_NewFrame(void) { ::ImGui_ImplDX12_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX12_RenderDrawData(cimgui::ImDrawData* draw_data, cimgui::ID3D12GraphicsCommandList* graphics_command_list) { ::ImGui_ImplDX12_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data), reinterpret_cast<::ID3D12GraphicsCommandList*>(graphics_command_list)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX12_InvalidateDeviceObjects(void) { ::ImGui_ImplDX12_InvalidateDeviceObjects(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX12_CreateDeviceObjects(void) { return ::ImGui_ImplDX12_CreateDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx10.h
// dear imgui: Renderer Backend for DirectX10 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct ID3D10Device; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX10_Init(ID3D10Device* device); IMGUI_IMPL_API void ImGui_ImplDX10_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX10_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_allegro5.h
// dear imgui: Renderer + Platform Backend for Allegro 5 // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) // Implemented features: // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Clipboard support (from Allegro 5.1.12) // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Issues: // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct ALLEGRO_DISPLAY; union ALLEGRO_EVENT; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display); IMGUI_IMPL_API void ImGui_ImplAllegro5_Shutdown(); IMGUI_IMPL_API void ImGui_ImplAllegro5_NewFrame(); IMGUI_IMPL_API void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdl2.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_sdl2.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_sdl2.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL2_InitForOpenGL(cimgui::SDL_Window* window, void* sdl_gl_context) { return ::ImGui_ImplSDL2_InitForOpenGL(reinterpret_cast<::SDL_Window*>(window), sdl_gl_context); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL2_InitForVulkan(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL2_InitForVulkan(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL2_InitForD3D(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL2_InitForD3D(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL2_InitForMetal(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL2_InitForMetal(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL2_InitForSDLRenderer(cimgui::SDL_Window* window, cimgui::SDL_Renderer* renderer) { return ::ImGui_ImplSDL2_InitForSDLRenderer(reinterpret_cast<::SDL_Window*>(window), reinterpret_cast<::SDL_Renderer*>(renderer)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL2_InitForOther(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL2_InitForOther(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL2_Shutdown(void) { ::ImGui_ImplSDL2_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL2_NewFrame(void) { ::ImGui_ImplSDL2_NewFrame(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) { return ::ImGui_ImplSDL2_ProcessEvent(event); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL2_SetGamepadMode(cimgui::ImGui_ImplSDL2_GamepadMode mode) { ::ImGui_ImplSDL2_SetGamepadMode(static_cast<::ImGui_ImplSDL2_GamepadMode>(mode)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL2_SetGamepadModeEx(cimgui::ImGui_ImplSDL2_GamepadMode mode, struct cimgui::_SDL_GameController** manual_gamepads_array, int manual_gamepads_count) { ::ImGui_ImplSDL2_SetGamepadMode(static_cast<::ImGui_ImplSDL2_GamepadMode>(mode), reinterpret_cast<struct ::_SDL_GameController**>(manual_gamepads_array), manual_gamepads_count); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx10.cpp
// dear imgui: Renderer Backend for DirectX10 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX10: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: DirectX10: Change blending equation to preserve alpha in output buffer. // 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData(). // 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions. // 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the old combined DX10+Win32 example. // 2018-06-08: DirectX10: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-04-09: Misc: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) on other backends. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2016-05-07: DirectX10: Disabling depth-write. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_dx10.h" // DirectX #include <stdio.h> #include <d3d10_1.h> #include <d3d10.h> #include <d3dcompiler.h> #ifdef _MSC_VER #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif // DirectX data struct ImGui_ImplDX10_Data { ID3D10Device* pd3dDevice; IDXGIFactory* pFactory; ID3D10Buffer* pVB; ID3D10Buffer* pIB; ID3D10VertexShader* pVertexShader; ID3D10InputLayout* pInputLayout; ID3D10Buffer* pVertexConstantBuffer; ID3D10PixelShader* pPixelShader; ID3D10SamplerState* pFontSampler; ID3D10ShaderResourceView* pFontTextureView; ID3D10RasterizerState* pRasterizerState; ID3D10BlendState* pBlendState; ID3D10DepthStencilState* pDepthStencilState; int VertexBufferSize; int IndexBufferSize; ImGui_ImplDX10_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } }; struct VERTEX_CONSTANT_BUFFER_DX10 { float mvp[4][4]; }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* ctx) { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); // Setup viewport D3D10_VIEWPORT vp; memset(&vp, 0, sizeof(D3D10_VIEWPORT)); vp.Width = (UINT)draw_data->DisplaySize.x; vp.Height = (UINT)draw_data->DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0; ctx->RSSetViewports(1, &vp); // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; ctx->IASetInputLayout(bd->pInputLayout); ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset); ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); ctx->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->VSSetShader(bd->pVertexShader); ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); ctx->PSSetShader(bd->pPixelShader); ctx->PSSetSamplers(0, 1, &bd->pFontSampler); ctx->GSSetShader(nullptr); // Setup render state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff); ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0); ctx->RSSetState(bd->pRasterizerState); } // Render function void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); ID3D10Device* ctx = bd->pd3dDevice; // Create and grow vertex/index buffers if needed if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D10_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); desc.Usage = D3D10_USAGE_DYNAMIC; desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert); desc.BindFlags = D3D10_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; desc.MiscFlags = 0; if (ctx->CreateBuffer(&desc, nullptr, &bd->pVB) < 0) return; } if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) { if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D10_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); desc.Usage = D3D10_USAGE_DYNAMIC; desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D10_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; if (ctx->CreateBuffer(&desc, nullptr, &bd->pIB) < 0) return; } // Copy and convert all vertices into a single contiguous buffer ImDrawVert* vtx_dst = nullptr; ImDrawIdx* idx_dst = nullptr; bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst); bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } bd->pVB->Unmap(); bd->pIB->Unmap(); // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. { void* mapped_resource; if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) return; VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource; float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; float mvp[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, { 0.0f, 0.0f, 0.5f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); bd->pVertexConstantBuffer->Unmap(); } // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) struct BACKUP_DX10_STATE { UINT ScissorRectsCount, ViewportsCount; D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; ID3D10RasterizerState* RS; ID3D10BlendState* BlendState; FLOAT BlendFactor[4]; UINT SampleMask; UINT StencilRef; ID3D10DepthStencilState* DepthStencilState; ID3D10ShaderResourceView* PSShaderResource; ID3D10SamplerState* PSSampler; ID3D10PixelShader* PS; ID3D10VertexShader* VS; ID3D10GeometryShader* GS; D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology; ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; DXGI_FORMAT IndexBufferFormat; ID3D10InputLayout* InputLayout; }; BACKUP_DX10_STATE old = {}; old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects); ctx->RSGetViewports(&old.ViewportsCount, old.Viewports); ctx->RSGetState(&old.RS); ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask); ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); ctx->PSGetShaderResources(0, 1, &old.PSShaderResource); ctx->PSGetSamplers(0, 1, &old.PSSampler); ctx->PSGetShader(&old.PS); ctx->VSGetShader(&old.VS); ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); ctx->GSGetShader(&old.GS); ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology); ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); ctx->IAGetInputLayout(&old.InputLayout); // Setup desired DX state ImGui_ImplDX10_SetupRenderState(draw_data, ctx); // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplDX10_SetupRenderState(draw_data, ctx); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply scissor/clipping rectangle const D3D10_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; ctx->RSSetScissorRects(1, &r); // Bind texture, Draw ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->GetTexID(); ctx->PSSetShaderResources(0, 1, &texture_srv); ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset); } } global_idx_offset += cmd_list->IdxBuffer.Size; global_vtx_offset += cmd_list->VtxBuffer.Size; } // Restore modified DX state ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); ctx->RSSetViewports(old.ViewportsCount, old.Viewports); ctx->RSSetState(old.RS); if (old.RS) old.RS->Release(); ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release(); ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release(); ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release(); ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release(); ctx->PSSetShader(old.PS); if (old.PS) old.PS->Release(); ctx->VSSetShader(old.VS); if (old.VS) old.VS->Release(); ctx->GSSetShader(old.GS); if (old.GS) old.GS->Release(); ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); ctx->IASetPrimitiveTopology(old.PrimitiveTopology); ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release(); ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); } static void ImGui_ImplDX10_CreateFontsTexture() { // Build texture atlas ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system { D3D10_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D10_USAGE_DEFAULT; desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; ID3D10Texture2D* pTexture = nullptr; D3D10_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); IM_ASSERT(pTexture != nullptr); // Create texture view D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc; ZeroMemory(&srv_desc, sizeof(srv_desc)); srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; srv_desc.Texture2D.MipLevels = desc.MipLevels; srv_desc.Texture2D.MostDetailedMip = 0; bd->pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &bd->pFontTextureView); pTexture->Release(); } // Store our identifier io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView); // Create texture sampler // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) { D3D10_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D10_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D10_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D10_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler); } } bool ImGui_ImplDX10_CreateDeviceObjects() { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); if (!bd->pd3dDevice) return false; if (bd->pFontSampler) ImGui_ImplDX10_InvalidateDeviceObjects(); // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) // If you would like to use this DX10 sample code but remove this dependency you can: // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution] // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. // Create the vertex shader { static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ float2 pos : POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ PS_INPUT output;\ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ output.col = input.col;\ output.uv = input.uv;\ return output;\ }"; ID3DBlob* vertexShaderBlob; if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pVertexShader) != S_OK) { vertexShaderBlob->Release(); return false; } // Create the input layout D3D10_INPUT_ELEMENT_DESC local_layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) { vertexShaderBlob->Release(); return false; } vertexShaderBlob->Release(); // Create the constant buffer { D3D10_BUFFER_DESC desc; desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10); desc.Usage = D3D10_USAGE_DYNAMIC; desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; desc.MiscFlags = 0; bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer); } } // Create the pixel shader { static const char* pixelShader = "struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ sampler sampler0;\ Texture2D texture0;\ \ float4 main(PS_INPUT input) : SV_Target\ {\ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ return out_col; \ }"; ID3DBlob* pixelShaderBlob; if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &bd->pPixelShader) != S_OK) { pixelShaderBlob->Release(); return false; } pixelShaderBlob->Release(); } // Create the blending setup { D3D10_BLEND_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.AlphaToCoverageEnable = false; desc.BlendEnable[0] = true; desc.SrcBlend = D3D10_BLEND_SRC_ALPHA; desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA; desc.BlendOp = D3D10_BLEND_OP_ADD; desc.SrcBlendAlpha = D3D10_BLEND_ONE; desc.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA; desc.BlendOpAlpha = D3D10_BLEND_OP_ADD; desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL; bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState); } // Create the rasterizer state { D3D10_RASTERIZER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.FillMode = D3D10_FILL_SOLID; desc.CullMode = D3D10_CULL_NONE; desc.ScissorEnable = true; desc.DepthClipEnable = true; bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState); } // Create depth-stencil State { D3D10_DEPTH_STENCIL_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.DepthEnable = false; desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL; desc.DepthFunc = D3D10_COMPARISON_ALWAYS; desc.StencilEnable = false; desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP; desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS; desc.BackFace = desc.FrontFace; bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState); } ImGui_ImplDX10_CreateFontsTexture(); return true; } void ImGui_ImplDX10_InvalidateDeviceObjects() { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); if (!bd->pd3dDevice) return; if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; } if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; } if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; } if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; } if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; } if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; } } bool ImGui_ImplDX10_Init(ID3D10Device* device) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX10_Data* bd = IM_NEW(ImGui_ImplDX10_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx10"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device IDXGIDevice* pDXGIDevice = nullptr; IDXGIAdapter* pDXGIAdapter = nullptr; IDXGIFactory* pFactory = nullptr; if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK) if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK) if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK) { bd->pd3dDevice = device; bd->pFactory = pFactory; } if (pDXGIDevice) pDXGIDevice->Release(); if (pDXGIAdapter) pDXGIAdapter->Release(); bd->pd3dDevice->AddRef(); return true; } void ImGui_ImplDX10_Shutdown() { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX10_InvalidateDeviceObjects(); if (bd->pFactory) { bd->pFactory->Release(); } if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplDX10_NewFrame() { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?"); if (!bd->pFontSampler) ImGui_ImplDX10_CreateDeviceObjects(); } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_glfw.cpp
// dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) // (Requires: GLFW 3.1+. Prefer GLFW 3.3+ or GLFW 3.4+ for full feature support.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn // 2024-07-31: Added ImGui_ImplGlfw_Sleep() helper function for usage by our examples app, since GLFW doesn't provide one. // 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter. // 2024-07-08: Emscripten: Added support for GLFW3 contrib port (GLFW 3.4.0 features + bug fixes): to enable, replace -sUSE_GLFW=3 with --use-port=contrib.glfw3 (requires emscripten 3.1.59+) (https://github.com/pongasoft/emscripten-glfw) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys. // 2023-07-18: Inputs: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used differently. User may set ImGuiConfigFLags_NoMouse if desired. (#5625, #6609) // 2023-06-12: Accept glfwGetTime() not returning a monotonically increasing value. This seems to happens on some Windows setup when peripherals disconnect, and is likely to also happen on browser + Emscripten. (#6491) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen on Windows ONLY, using a custom WndProc hook. (#2702) // 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034) // 2023-03-14: Emscripten: Avoid using glfwGetError() and glfwGetGamepadState() which are not correctly implemented in Emscripten emulation. (#6240) // 2023-02-03: Emscripten: Registering custom low-level mouse wheel handler to get more accurate scrolling impulses on Emscripten. (#4019, #6096) // 2023-01-04: Inputs: Fixed mods state on Linux when using Alt-GR text input (e.g. German keyboard layout), could lead to broken text input. Revert a 2022/01/17 change were we resumed using mods provided by GLFW, turns out they were faulty. // 2022-11-22: Perform a dummy glfwGetError() read to cancel missing names with glfwGetKeyName(). (#5908) // 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). // 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position *EDIT* Reverted 2023-07-18. // 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX. // 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11. // 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend. // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). // 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates. // 2022-01-12: *BREAKING CHANGE*: Now using glfwSetCursorPosCallback(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetCursorPosCallback() and forward it to the backend via ImGui_ImplGlfw_CursorPosCallback(). // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2022-01-05: Inputs: Converting GLFW untranslated keycodes back to translated keycodes (in the ImGui_ImplGlfw_KeyCallback() function) in order to match the behavior of every other backend, and facilitate the use of GLFW with lettered-shortcuts API. // 2021-08-17: *BREAKING CHANGE*: Now using glfwSetWindowFocusCallback() to calling io.AddFocusEvent(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() and forward it to the backend via ImGui_ImplGlfw_WindowFocusCallback(). // 2021-07-29: *BREAKING CHANGE*: Now using glfwSetCursorEnterCallback(). MousePos is correctly reported when the host platform window is hovered but not focused. If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() callback and forward it to the backend via ImGui_ImplGlfw_CursorEnterCallback(). // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors. // 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor). // 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown. // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter(). // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them. // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls. // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. // 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()). // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. // 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set. // 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_glfw.h" // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #endif // GLFW #include <GLFW/glfw3.h> #ifdef _WIN32 #undef APIENTRY #ifndef GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WIN32 #endif #include <GLFW/glfw3native.h> // for glfwGetWin32Window() #endif #ifdef __APPLE__ #ifndef GLFW_EXPOSE_NATIVE_COCOA #define GLFW_EXPOSE_NATIVE_COCOA #endif #include <GLFW/glfw3native.h> // for glfwGetCocoaWindow() #endif #ifndef _WIN32 #include <unistd.h> // for usleep() #endif #ifdef __EMSCRIPTEN__ #include <emscripten.h> #include <emscripten/html5.h> #ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 #include <GLFW/emscripten_glfw3.h> #else #define EMSCRIPTEN_USE_EMBEDDED_GLFW3 #endif #endif // We gather version tests as define in order to easily see which features are version-dependent. #define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION) #ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released? #define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR #else #define GLFW_HAS_NEW_CURSORS (0) #endif #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() // GLFW data enum GlfwClientApi { GlfwClientApi_Unknown, GlfwClientApi_OpenGL, GlfwClientApi_Vulkan, }; struct ImGui_ImplGlfw_Data { GLFWwindow* Window; GlfwClientApi ClientApi; double Time; GLFWwindow* MouseWindow; GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT]; ImVec2 LastValidMousePos; bool InstalledCallbacks; bool CallbacksChainForAllWindows; #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 const char* CanvasSelector; #endif // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. GLFWwindowfocusfun PrevUserCallbackWindowFocus; GLFWcursorposfun PrevUserCallbackCursorPos; GLFWcursorenterfun PrevUserCallbackCursorEnter; GLFWmousebuttonfun PrevUserCallbackMousebutton; GLFWscrollfun PrevUserCallbackScroll; GLFWkeyfun PrevUserCallbackKey; GLFWcharfun PrevUserCallbackChar; GLFWmonitorfun PrevUserCallbackMonitor; #ifdef _WIN32 WNDPROC PrevWndProc; #endif ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. // - Because glfwPollEvents() process all windows and some events may be called outside of it, you will need to register your own callbacks // (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks. // - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } // Functions static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key) { switch (key) { case GLFW_KEY_TAB: return ImGuiKey_Tab; case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow; case GLFW_KEY_RIGHT: return ImGuiKey_RightArrow; case GLFW_KEY_UP: return ImGuiKey_UpArrow; case GLFW_KEY_DOWN: return ImGuiKey_DownArrow; case GLFW_KEY_PAGE_UP: return ImGuiKey_PageUp; case GLFW_KEY_PAGE_DOWN: return ImGuiKey_PageDown; case GLFW_KEY_HOME: return ImGuiKey_Home; case GLFW_KEY_END: return ImGuiKey_End; case GLFW_KEY_INSERT: return ImGuiKey_Insert; case GLFW_KEY_DELETE: return ImGuiKey_Delete; case GLFW_KEY_BACKSPACE: return ImGuiKey_Backspace; case GLFW_KEY_SPACE: return ImGuiKey_Space; case GLFW_KEY_ENTER: return ImGuiKey_Enter; case GLFW_KEY_ESCAPE: return ImGuiKey_Escape; case GLFW_KEY_APOSTROPHE: return ImGuiKey_Apostrophe; case GLFW_KEY_COMMA: return ImGuiKey_Comma; case GLFW_KEY_MINUS: return ImGuiKey_Minus; case GLFW_KEY_PERIOD: return ImGuiKey_Period; case GLFW_KEY_SLASH: return ImGuiKey_Slash; case GLFW_KEY_SEMICOLON: return ImGuiKey_Semicolon; case GLFW_KEY_EQUAL: return ImGuiKey_Equal; case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket; case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash; case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket; case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent; case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock; case GLFW_KEY_SCROLL_LOCK: return ImGuiKey_ScrollLock; case GLFW_KEY_NUM_LOCK: return ImGuiKey_NumLock; case GLFW_KEY_PRINT_SCREEN: return ImGuiKey_PrintScreen; case GLFW_KEY_PAUSE: return ImGuiKey_Pause; case GLFW_KEY_KP_0: return ImGuiKey_Keypad0; case GLFW_KEY_KP_1: return ImGuiKey_Keypad1; case GLFW_KEY_KP_2: return ImGuiKey_Keypad2; case GLFW_KEY_KP_3: return ImGuiKey_Keypad3; case GLFW_KEY_KP_4: return ImGuiKey_Keypad4; case GLFW_KEY_KP_5: return ImGuiKey_Keypad5; case GLFW_KEY_KP_6: return ImGuiKey_Keypad6; case GLFW_KEY_KP_7: return ImGuiKey_Keypad7; case GLFW_KEY_KP_8: return ImGuiKey_Keypad8; case GLFW_KEY_KP_9: return ImGuiKey_Keypad9; case GLFW_KEY_KP_DECIMAL: return ImGuiKey_KeypadDecimal; case GLFW_KEY_KP_DIVIDE: return ImGuiKey_KeypadDivide; case GLFW_KEY_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; case GLFW_KEY_KP_SUBTRACT: return ImGuiKey_KeypadSubtract; case GLFW_KEY_KP_ADD: return ImGuiKey_KeypadAdd; case GLFW_KEY_KP_ENTER: return ImGuiKey_KeypadEnter; case GLFW_KEY_KP_EQUAL: return ImGuiKey_KeypadEqual; case GLFW_KEY_LEFT_SHIFT: return ImGuiKey_LeftShift; case GLFW_KEY_LEFT_CONTROL: return ImGuiKey_LeftCtrl; case GLFW_KEY_LEFT_ALT: return ImGuiKey_LeftAlt; case GLFW_KEY_LEFT_SUPER: return ImGuiKey_LeftSuper; case GLFW_KEY_RIGHT_SHIFT: return ImGuiKey_RightShift; case GLFW_KEY_RIGHT_CONTROL: return ImGuiKey_RightCtrl; case GLFW_KEY_RIGHT_ALT: return ImGuiKey_RightAlt; case GLFW_KEY_RIGHT_SUPER: return ImGuiKey_RightSuper; case GLFW_KEY_MENU: return ImGuiKey_Menu; case GLFW_KEY_0: return ImGuiKey_0; case GLFW_KEY_1: return ImGuiKey_1; case GLFW_KEY_2: return ImGuiKey_2; case GLFW_KEY_3: return ImGuiKey_3; case GLFW_KEY_4: return ImGuiKey_4; case GLFW_KEY_5: return ImGuiKey_5; case GLFW_KEY_6: return ImGuiKey_6; case GLFW_KEY_7: return ImGuiKey_7; case GLFW_KEY_8: return ImGuiKey_8; case GLFW_KEY_9: return ImGuiKey_9; case GLFW_KEY_A: return ImGuiKey_A; case GLFW_KEY_B: return ImGuiKey_B; case GLFW_KEY_C: return ImGuiKey_C; case GLFW_KEY_D: return ImGuiKey_D; case GLFW_KEY_E: return ImGuiKey_E; case GLFW_KEY_F: return ImGuiKey_F; case GLFW_KEY_G: return ImGuiKey_G; case GLFW_KEY_H: return ImGuiKey_H; case GLFW_KEY_I: return ImGuiKey_I; case GLFW_KEY_J: return ImGuiKey_J; case GLFW_KEY_K: return ImGuiKey_K; case GLFW_KEY_L: return ImGuiKey_L; case GLFW_KEY_M: return ImGuiKey_M; case GLFW_KEY_N: return ImGuiKey_N; case GLFW_KEY_O: return ImGuiKey_O; case GLFW_KEY_P: return ImGuiKey_P; case GLFW_KEY_Q: return ImGuiKey_Q; case GLFW_KEY_R: return ImGuiKey_R; case GLFW_KEY_S: return ImGuiKey_S; case GLFW_KEY_T: return ImGuiKey_T; case GLFW_KEY_U: return ImGuiKey_U; case GLFW_KEY_V: return ImGuiKey_V; case GLFW_KEY_W: return ImGuiKey_W; case GLFW_KEY_X: return ImGuiKey_X; case GLFW_KEY_Y: return ImGuiKey_Y; case GLFW_KEY_Z: return ImGuiKey_Z; case GLFW_KEY_F1: return ImGuiKey_F1; case GLFW_KEY_F2: return ImGuiKey_F2; case GLFW_KEY_F3: return ImGuiKey_F3; case GLFW_KEY_F4: return ImGuiKey_F4; case GLFW_KEY_F5: return ImGuiKey_F5; case GLFW_KEY_F6: return ImGuiKey_F6; case GLFW_KEY_F7: return ImGuiKey_F7; case GLFW_KEY_F8: return ImGuiKey_F8; case GLFW_KEY_F9: return ImGuiKey_F9; case GLFW_KEY_F10: return ImGuiKey_F10; case GLFW_KEY_F11: return ImGuiKey_F11; case GLFW_KEY_F12: return ImGuiKey_F12; case GLFW_KEY_F13: return ImGuiKey_F13; case GLFW_KEY_F14: return ImGuiKey_F14; case GLFW_KEY_F15: return ImGuiKey_F15; case GLFW_KEY_F16: return ImGuiKey_F16; case GLFW_KEY_F17: return ImGuiKey_F17; case GLFW_KEY_F18: return ImGuiKey_F18; case GLFW_KEY_F19: return ImGuiKey_F19; case GLFW_KEY_F20: return ImGuiKey_F20; case GLFW_KEY_F21: return ImGuiKey_F21; case GLFW_KEY_F22: return ImGuiKey_F22; case GLFW_KEY_F23: return ImGuiKey_F23; case GLFW_KEY_F24: return ImGuiKey_F24; default: return ImGuiKey_None; } } // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW // See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630 static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window) { ImGuiIO& io = ImGui::GetIO(); io.AddKeyEvent(ImGuiMod_Ctrl, (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)); io.AddKeyEvent(ImGuiMod_Shift, (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS)); io.AddKeyEvent(ImGuiMod_Alt, (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS)); io.AddKeyEvent(ImGuiMod_Super, (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS)); } static bool ImGui_ImplGlfw_ShouldChainCallback(GLFWwindow* window) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); return bd->CallbacksChainForAllWindows ? true : (window == bd->Window); } void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackMousebutton(window, button, action, mods); ImGui_ImplGlfw_UpdateKeyModifiers(window); ImGuiIO& io = ImGui::GetIO(); if (button >= 0 && button < ImGuiMouseButton_COUNT) io.AddMouseButtonEvent(button, action == GLFW_PRESS); } void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackScroll(window, xoffset, yoffset); #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 // Ignore GLFW events: will be processed in ImGui_ImplEmscripten_WheelCallback(). return; #endif ImGuiIO& io = ImGui::GetIO(); io.AddMouseWheelEvent((float)xoffset, (float)yoffset); } static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode) { #if GLFW_HAS_GETKEYNAME && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) // GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult. // (It had reasons to do so: namely GLFW is/was more likely to be used for WASD-type game controls rather than lettered shortcuts, but IHMO the 3.1 change could have been done differently) // See https://github.com/glfw/glfw/issues/1502 for details. // Adding a workaround to undo this (so our keys are translated->untranslated->translated, likely a lossy process). // This won't cover edge cases but this is at least going to cover common cases. if (key >= GLFW_KEY_KP_0 && key <= GLFW_KEY_KP_EQUAL) return key; GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr); const char* key_name = glfwGetKeyName(key, scancode); glfwSetErrorCallback(prev_error_callback); #if GLFW_HAS_GETERROR && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) // Eat errors (see #5908) (void)glfwGetError(nullptr); #endif if (key_name && key_name[0] != 0 && key_name[1] == 0) { const char char_names[] = "`-=[]\\,;\'./"; const int char_keys[] = { GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_BACKSLASH, GLFW_KEY_COMMA, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, 0 }; IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys)); if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); } else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); } else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); } else if (const char* p = strchr(char_names, key_name[0])) { key = char_keys[p - char_names]; } } // if (action == GLFW_PRESS) printf("key %d scancode %d name '%s'\n", key, scancode, key_name); #else IM_UNUSED(scancode); #endif return key; } void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackKey(window, keycode, scancode, action, mods); if (action != GLFW_PRESS && action != GLFW_RELEASE) return; ImGui_ImplGlfw_UpdateKeyModifiers(window); keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode); ImGuiIO& io = ImGui::GetIO(); ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode); io.AddKeyEvent(imgui_key, (action == GLFW_PRESS)); io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code) } void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackWindowFocus(window, focused); ImGuiIO& io = ImGui::GetIO(); io.AddFocusEvent(focused != 0); } void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackCursorPos(window, x, y); ImGuiIO& io = ImGui::GetIO(); io.AddMousePosEvent((float)x, (float)y); bd->LastValidMousePos = ImVec2((float)x, (float)y); } // Workaround: X11 seems to send spurious Leave/Enter events which would make us lose our position, // so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984) void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackCursorEnter(window, entered); ImGuiIO& io = ImGui::GetIO(); if (entered) { bd->MouseWindow = window; io.AddMousePosEvent(bd->LastValidMousePos.x, bd->LastValidMousePos.y); } else if (!entered && bd->MouseWindow == window) { bd->LastValidMousePos = io.MousePos; bd->MouseWindow = nullptr; io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); } } void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackChar(window, c); ImGuiIO& io = ImGui::GetIO(); io.AddInputCharacter(c); } void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int) { // Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too. } #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*) { // Mimic Emscripten_HandleWheel() in SDL. // Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096 float multiplier = 0.0f; if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step. else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step. else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps. float wheel_x = ev->deltaX * -multiplier; float wheel_y = ev->deltaY * -multiplier; ImGuiIO& io = ImGui::GetIO(); io.AddMouseWheelEvent(wheel_x, wheel_y); //IMGUI_DEBUG_LOG("[Emsc] mode %d dx: %.2f, dy: %.2f, dz: %.2f --> feed %.2f %.2f\n", (int)ev->deltaMode, ev->deltaX, ev->deltaY, ev->deltaZ, wheel_x, wheel_y); return EM_TRUE; } #endif #ifdef _WIN32 // GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen. // Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently. static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() { LPARAM extra_info = ::GetMessageExtraInfo(); if ((extra_info & 0xFFFFFF80) == 0xFF515700) return ImGuiMouseSource_Pen; if ((extra_info & 0xFFFFFF80) == 0xFF515780) return ImGuiMouseSource_TouchScreen; return ImGuiMouseSource_Mouse; } static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); switch (msg) { case WM_MOUSEMOVE: case WM_NCMOUSEMOVE: case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_LBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP: ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); break; } return ::CallWindowProcW(bd->PrevWndProc, hWnd, msg, wParam, lParam); } #endif void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!"); IM_ASSERT(bd->Window == window); bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback); bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback); bd->PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback); bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback); bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback); bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback); bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback); bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback); bd->InstalledCallbacks = true; } void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!"); IM_ASSERT(bd->Window == window); glfwSetWindowFocusCallback(window, bd->PrevUserCallbackWindowFocus); glfwSetCursorEnterCallback(window, bd->PrevUserCallbackCursorEnter); glfwSetCursorPosCallback(window, bd->PrevUserCallbackCursorPos); glfwSetMouseButtonCallback(window, bd->PrevUserCallbackMousebutton); glfwSetScrollCallback(window, bd->PrevUserCallbackScroll); glfwSetKeyCallback(window, bd->PrevUserCallbackKey); glfwSetCharCallback(window, bd->PrevUserCallbackChar); glfwSetMonitorCallback(bd->PrevUserCallbackMonitor); bd->InstalledCallbacks = false; bd->PrevUserCallbackWindowFocus = nullptr; bd->PrevUserCallbackCursorEnter = nullptr; bd->PrevUserCallbackCursorPos = nullptr; bd->PrevUserCallbackMousebutton = nullptr; bd->PrevUserCallbackScroll = nullptr; bd->PrevUserCallbackKey = nullptr; bd->PrevUserCallbackChar = nullptr; bd->PrevUserCallbackMonitor = nullptr; } // Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user. // This is 'false' by default meaning we only chain callbacks for the main viewport. // We cannot set this to 'true' by default because user callbacks code may be not testing the 'window' parameter of their callback. // If you set this to 'true' your user callback code will need to make sure you are testing the 'window' parameter. void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); bd->CallbacksChainForAllWindows = chain_for_all_windows; } #ifdef __EMSCRIPTEN__ #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 3'4'0'20240817 void ImGui_ImplGlfw_EmscriptenOpenURL(const char* url) { if (url) emscripten::glfw3::OpenURL(url); } #else EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); #endif #endif static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); //printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED); // Setup backend capabilities flags ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)(); io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = "imgui_impl_glfw"; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Window = window; bd->Time = 0.0; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(NULL, text); }; platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(NULL); }; #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; }; #endif // Create mouse cursors // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist, // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting. // Missing cursors will return nullptr and our _UpdateMouseCursor() function will use the Arrow cursor instead.) GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr); bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR); bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR); bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR); bd->MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR); #if GLFW_HAS_NEW_CURSORS bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR); bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR); bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR); #else bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); #endif glfwSetErrorCallback(prev_error_callback); #if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908) (void)glfwGetError(nullptr); #endif // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. if (install_callbacks) ImGui_ImplGlfw_InstallCallbacks(window); // Set platform dependent data in viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->PlatformHandle = (void*)bd->Window; #ifdef _WIN32 main_viewport->PlatformHandleRaw = glfwGetWin32Window(bd->Window); #elif defined(__APPLE__) main_viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(bd->Window); #else IM_UNUSED(main_viewport); #endif // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC); IM_ASSERT(bd->PrevWndProc != nullptr); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); #endif bd->ClientApi = client_api; return true; } bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks) { return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL); } bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks) { return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan); } bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks) { return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown); } void ImGui_ImplGlfw_Shutdown() { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); if (bd->InstalledCallbacks) ImGui_ImplGlfw_RestoreCallbacks(bd->Window); #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 if (bd->CanvasSelector) emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, nullptr); #endif for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) glfwDestroyCursor(bd->MouseCursors[cursor_n]); // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); bd->PrevWndProc = nullptr; #endif io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); IM_DELETE(bd); } static void ImGui_ImplGlfw_UpdateMouseData() { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); // (those braces are here to reduce diff with multi-viewports support in 'docking' branch) { GLFWwindow* window = bd->Window; #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 const bool is_window_focused = true; #else const bool is_window_focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0; #endif if (is_window_focused) { // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) if (io.WantSetMousePos) glfwSetCursorPos(window, (double)io.MousePos.x, (double)io.MousePos.y); // (Optional) Fallback to provide mouse position when focused (ImGui_ImplGlfw_CursorPosCallback already provides this when hovered or captured) if (bd->MouseWindow == nullptr) { double mouse_x, mouse_y; glfwGetCursorPos(window, &mouse_x, &mouse_y); bd->LastValidMousePos = ImVec2((float)mouse_x, (float)mouse_y); io.AddMousePosEvent((float)mouse_x, (float)mouse_y); } } } } static void ImGui_ImplGlfw_UpdateMouseCursor() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) return; ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); // (those braces are here to reduce diff with multi-viewports support in 'docking' branch) { GLFWwindow* window = bd->Window; if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); } else { // Show OS mouse cursor // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } } // Update gamepad inputs static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } static void ImGui_ImplGlfw_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; #if GLFW_HAS_GAMEPAD_API && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) GLFWgamepadstate gamepad; if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad)) return; #define MAP_BUTTON(KEY_NO, BUTTON_NO, _UNUSED) do { io.AddKeyEvent(KEY_NO, gamepad.buttons[BUTTON_NO] != 0); } while (0) #define MAP_ANALOG(KEY_NO, AXIS_NO, _UNUSED, V0, V1) do { float v = gamepad.axes[AXIS_NO]; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0) #else int axes_count = 0, buttons_count = 0; const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count); const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count); if (axes_count == 0 || buttons_count == 0) return; #define MAP_BUTTON(KEY_NO, _UNUSED, BUTTON_NO) do { io.AddKeyEvent(KEY_NO, (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS)); } while (0) #define MAP_ANALOG(KEY_NO, _UNUSED, AXIS_NO, V0, V1) do { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0) #endif io.BackendFlags |= ImGuiBackendFlags_HasGamepad; MAP_BUTTON(ImGuiKey_GamepadStart, GLFW_GAMEPAD_BUTTON_START, 7); MAP_BUTTON(ImGuiKey_GamepadBack, GLFW_GAMEPAD_BUTTON_BACK, 6); MAP_BUTTON(ImGuiKey_GamepadFaceLeft, GLFW_GAMEPAD_BUTTON_X, 2); // Xbox X, PS Square MAP_BUTTON(ImGuiKey_GamepadFaceRight, GLFW_GAMEPAD_BUTTON_B, 1); // Xbox B, PS Circle MAP_BUTTON(ImGuiKey_GamepadFaceUp, GLFW_GAMEPAD_BUTTON_Y, 3); // Xbox Y, PS Triangle MAP_BUTTON(ImGuiKey_GamepadFaceDown, GLFW_GAMEPAD_BUTTON_A, 0); // Xbox A, PS Cross MAP_BUTTON(ImGuiKey_GamepadDpadLeft, GLFW_GAMEPAD_BUTTON_DPAD_LEFT, 13); MAP_BUTTON(ImGuiKey_GamepadDpadRight, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, 11); MAP_BUTTON(ImGuiKey_GamepadDpadUp, GLFW_GAMEPAD_BUTTON_DPAD_UP, 10); MAP_BUTTON(ImGuiKey_GamepadDpadDown, GLFW_GAMEPAD_BUTTON_DPAD_DOWN, 12); MAP_BUTTON(ImGuiKey_GamepadL1, GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, 4); MAP_BUTTON(ImGuiKey_GamepadR1, GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, 5); MAP_ANALOG(ImGuiKey_GamepadL2, GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, 4, -0.75f, +1.0f); MAP_ANALOG(ImGuiKey_GamepadR2, GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, 5, -0.75f, +1.0f); MAP_BUTTON(ImGuiKey_GamepadL3, GLFW_GAMEPAD_BUTTON_LEFT_THUMB, 8); MAP_BUTTON(ImGuiKey_GamepadR3, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, 9); MAP_ANALOG(ImGuiKey_GamepadLStickLeft, GLFW_GAMEPAD_AXIS_LEFT_X, 0, -0.25f, -1.0f); MAP_ANALOG(ImGuiKey_GamepadLStickRight, GLFW_GAMEPAD_AXIS_LEFT_X, 0, +0.25f, +1.0f); MAP_ANALOG(ImGuiKey_GamepadLStickUp, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, -0.25f, -1.0f); MAP_ANALOG(ImGuiKey_GamepadLStickDown, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, +0.25f, +1.0f); MAP_ANALOG(ImGuiKey_GamepadRStickLeft, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, -0.25f, -1.0f); MAP_ANALOG(ImGuiKey_GamepadRStickRight, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, +0.25f, +1.0f); MAP_ANALOG(ImGuiKey_GamepadRStickUp, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, -0.25f, -1.0f); MAP_ANALOG(ImGuiKey_GamepadRStickDown, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, +0.25f, +1.0f); #undef MAP_BUTTON #undef MAP_ANALOG } void ImGui_ImplGlfw_NewFrame() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?"); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; glfwGetWindowSize(bd->Window, &w, &h); glfwGetFramebufferSize(bd->Window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h); // Setup time step // (Accept glfwGetTime() not returning a monotonically increasing value. Seems to happens on disconnecting peripherals and probably on VMs and Emscripten, see #6491, #6189, #6114, #3644) double current_time = glfwGetTime(); if (current_time <= bd->Time) current_time = bd->Time + 0.00001f; io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f); bd->Time = current_time; ImGui_ImplGlfw_UpdateMouseData(); ImGui_ImplGlfw_UpdateMouseCursor(); // Update game controllers (if enabled and available) ImGui_ImplGlfw_UpdateGamepads(); } // GLFW doesn't provide a portable sleep function void ImGui_ImplGlfw_Sleep(int milliseconds) { #ifdef _WIN32 ::Sleep(milliseconds); #else usleep(milliseconds * 1000); #endif } #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3 static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data) { ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data; double canvas_width, canvas_height; emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height); glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height); return true; } static EM_BOOL ImGui_ImplEmscripten_FullscreenChangeCallback(int event_type, const EmscriptenFullscreenChangeEvent* event, void* user_data) { ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data; double canvas_width, canvas_height; emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height); glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height); return true; } // 'canvas_selector' is a CSS selector. The event listener is applied to the first element that matches the query. // STRING MUST PERSIST FOR THE APPLICATION DURATION. PLEASE USE A STRING LITERAL OR ENSURE POINTER WILL STAY VALID. void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow*, const char* canvas_selector) { IM_ASSERT(canvas_selector != nullptr); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?"); bd->CanvasSelector = canvas_selector; emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, bd, false, ImGui_ImplGlfw_OnCanvasSizeChange); emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, bd, false, ImGui_ImplEmscripten_FullscreenChangeCallback); // Change the size of the GLFW window according to the size of the canvas ImGui_ImplGlfw_OnCanvasSizeChange(EMSCRIPTEN_EVENT_RESIZE, {}, bd); // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096) // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves. // FIXME: May break chaining in case user registered their own Emscripten callback? emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, ImGui_ImplEmscripten_WheelCallback); } #elif defined(EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3) // When using --use-port=contrib.glfw3 for the GLFW implementation, you can override the behavior of this call // by invoking emscripten_glfw_make_canvas_resizable afterward. // See https://github.com/pongasoft/emscripten-glfw/blob/master/docs/Usage.md#how-to-make-the-canvas-resizable-by-the-user for an explanation void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector) { GLFWwindow* w = (GLFWwindow*)(EM_ASM_INT({ return Module.glfwGetWindow(UTF8ToString($0)); }, canvas_selector)); IM_ASSERT(window == w); // Sanity check IM_UNUSED(w); emscripten_glfw_make_canvas_resizable(window, "window", nullptr); } #endif // #ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_vulkan.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_vulkan.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_vulkan.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplVulkan_Init(cimgui::ImGui_ImplVulkan_InitInfo* info) { return ::ImGui_ImplVulkan_Init(reinterpret_cast<::ImGui_ImplVulkan_InitInfo*>(info)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkan_Shutdown(void) { ::ImGui_ImplVulkan_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkan_NewFrame(void) { ::ImGui_ImplVulkan_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkan_RenderDrawData(cimgui::ImDrawData* draw_data, VkCommandBuffer command_buffer) { ::ImGui_ImplVulkan_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data), command_buffer); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkan_RenderDrawDataEx(cimgui::ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline) { ::ImGui_ImplVulkan_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data), command_buffer, pipeline); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplVulkan_CreateFontsTexture(void) { return ::ImGui_ImplVulkan_CreateFontsTexture(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkan_DestroyFontsTexture(void) { ::ImGui_ImplVulkan_DestroyFontsTexture(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) { ::ImGui_ImplVulkan_SetMinImageCount(min_image_count); } CIMGUI_IMPL_API VkDescriptorSet cimgui::cImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout) { return ::ImGui_ImplVulkan_AddTexture(sampler, image_view, image_layout); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set) { ::ImGui_ImplVulkan_RemoveTexture(descriptor_set); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction (*loader_func)(const char* function_name, void* user_data)) { return ::ImGui_ImplVulkan_LoadFunctions(loader_func); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplVulkan_LoadFunctionsEx(PFN_vkVoidFunction (*loader_func)(const char* function_name, void* user_data), void* user_data) { return ::ImGui_ImplVulkan_LoadFunctions(loader_func, user_data); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, cimgui::ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) { ::ImGui_ImplVulkanH_CreateOrResizeWindow(instance, physical_device, device, reinterpret_cast<::ImGui_ImplVulkanH_Window*>(wnd), queue_family, allocator, w, h, min_image_count); } CIMGUI_IMPL_API void cimgui::cImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, cimgui::ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator) { ::ImGui_ImplVulkanH_DestroyWindow(instance, device, reinterpret_cast<::ImGui_ImplVulkanH_Window*>(wnd), allocator); } CIMGUI_IMPL_API VkSurfaceFormatKHR cimgui::cImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space) { return ::ImGui_ImplVulkanH_SelectSurfaceFormat(physical_device, surface, request_formats, request_formats_count, request_color_space); } CIMGUI_IMPL_API VkPresentModeKHR cimgui::cImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count) { return ::ImGui_ImplVulkanH_SelectPresentMode(physical_device, surface, request_modes, request_modes_count); } CIMGUI_IMPL_API int cimgui::cImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode) { return ::ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(present_mode); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_glut.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_glut.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_glut.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplGLUT_Init(void) { return ::ImGui_ImplGLUT_Init(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_InstallFuncs(void) { ::ImGui_ImplGLUT_InstallFuncs(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_Shutdown(void) { ::ImGui_ImplGLUT_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_NewFrame(void) { ::ImGui_ImplGLUT_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_ReshapeFunc(int w, int h) { ::ImGui_ImplGLUT_ReshapeFunc(w, h); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_MotionFunc(int x, int y) { ::ImGui_ImplGLUT_MotionFunc(x, y); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y) { ::ImGui_ImplGLUT_MouseFunc(button, state, x, y); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y) { ::ImGui_ImplGLUT_MouseWheelFunc(button, dir, x, y); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) { ::ImGui_ImplGLUT_KeyboardFunc(c, x, y); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y) { ::ImGui_ImplGLUT_KeyboardUpFunc(c, x, y); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_SpecialFunc(int key, int x, int y) { ::ImGui_ImplGLUT_SpecialFunc(key, x, y); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y) { ::ImGui_ImplGLUT_SpecialUpFunc(key, x, y); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdl2.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Platform Backend for SDL2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct SDL_Window SDL_Window; typedef struct SDL_Renderer SDL_Renderer; typedef struct _SDL_GameController _SDL_GameController; typedef union SDL_Event SDL_Event; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); CIMGUI_IMPL_API bool cImGui_ImplSDL2_InitForVulkan(SDL_Window* window); CIMGUI_IMPL_API bool cImGui_ImplSDL2_InitForD3D(SDL_Window* window); CIMGUI_IMPL_API bool cImGui_ImplSDL2_InitForMetal(SDL_Window* window); CIMGUI_IMPL_API bool cImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); CIMGUI_IMPL_API bool cImGui_ImplSDL2_InitForOther(SDL_Window* window); CIMGUI_IMPL_API void cImGui_ImplSDL2_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplSDL2_NewFrame(void); CIMGUI_IMPL_API bool cImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. // When using manual mode, caller is responsible for opening/closing gamepad. typedef enum { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual, } ImGui_ImplSDL2_GamepadMode; CIMGUI_IMPL_API void cImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode); // Implied manual_gamepads_array = NULL, manual_gamepads_count = -1 CIMGUI_IMPL_API void cImGui_ImplSDL2_SetGamepadModeEx(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array /* = NULL */, int manual_gamepads_count /* = -1 */); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx11.cpp
// dear imgui: Renderer Backend for DirectX11 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer. // 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled). // 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore. // 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility. // 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions. // 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example. // 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2016-05-07: DirectX11: Disabling depth-write. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_dx11.h" // DirectX #include <stdio.h> #include <d3d11.h> #include <d3dcompiler.h> #ifdef _MSC_VER #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif // DirectX11 data struct ImGui_ImplDX11_Data { ID3D11Device* pd3dDevice; ID3D11DeviceContext* pd3dDeviceContext; IDXGIFactory* pFactory; ID3D11Buffer* pVB; ID3D11Buffer* pIB; ID3D11VertexShader* pVertexShader; ID3D11InputLayout* pInputLayout; ID3D11Buffer* pVertexConstantBuffer; ID3D11PixelShader* pPixelShader; ID3D11SamplerState* pFontSampler; ID3D11ShaderResourceView* pFontTextureView; ID3D11RasterizerState* pRasterizerState; ID3D11BlendState* pBlendState; ID3D11DepthStencilState* pDepthStencilState; int VertexBufferSize; int IndexBufferSize; ImGui_ImplDX11_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } }; struct VERTEX_CONSTANT_BUFFER_DX11 { float mvp[4][4]; }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* ctx) { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); // Setup viewport D3D11_VIEWPORT vp; memset(&vp, 0, sizeof(D3D11_VIEWPORT)); vp.Width = draw_data->DisplaySize.x; vp.Height = draw_data->DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0; ctx->RSSetViewports(1, &vp); // Setup shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; ctx->IASetInputLayout(bd->pInputLayout); ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset); ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->VSSetShader(bd->pVertexShader, nullptr, 0); ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); ctx->PSSetShader(bd->pPixelShader, nullptr, 0); ctx->PSSetSamplers(0, 1, &bd->pFontSampler); ctx->GSSetShader(nullptr, nullptr, 0); ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. // Setup blend state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff); ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0); ctx->RSSetState(bd->pRasterizerState); } // Render function void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); ID3D11DeviceContext* ctx = bd->pd3dDeviceContext; // Create and grow vertex/index buffers if needed if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert); desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0) return; } if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) { if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D11_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0) return; } // Upload vertex/index data into a single contiguous GPU buffer D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource; if (ctx->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK) return; if (ctx->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK) return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } ctx->Unmap(bd->pVB, 0); ctx->Unmap(bd->pIB, 0); // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. { D3D11_MAPPED_SUBRESOURCE mapped_resource; if (ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) return; VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData; float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; float mvp[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, { 0.0f, 0.0f, 0.5f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); ctx->Unmap(bd->pVertexConstantBuffer, 0); } // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) struct BACKUP_DX11_STATE { UINT ScissorRectsCount, ViewportsCount; D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; ID3D11RasterizerState* RS; ID3D11BlendState* BlendState; FLOAT BlendFactor[4]; UINT SampleMask; UINT StencilRef; ID3D11DepthStencilState* DepthStencilState; ID3D11ShaderResourceView* PSShaderResource; ID3D11SamplerState* PSSampler; ID3D11PixelShader* PS; ID3D11VertexShader* VS; ID3D11GeometryShader* GS; UINT PSInstancesCount, VSInstancesCount, GSInstancesCount; ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology; ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; DXGI_FORMAT IndexBufferFormat; ID3D11InputLayout* InputLayout; }; BACKUP_DX11_STATE old = {}; old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects); ctx->RSGetViewports(&old.ViewportsCount, old.Viewports); ctx->RSGetState(&old.RS); ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask); ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); ctx->PSGetShaderResources(0, 1, &old.PSShaderResource); ctx->PSGetSamplers(0, 1, &old.PSSampler); old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256; ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount); ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount); ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); ctx->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount); ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology); ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); ctx->IAGetInputLayout(&old.InputLayout); // Setup desired DX state ImGui_ImplDX11_SetupRenderState(draw_data, ctx); // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_idx_offset = 0; int global_vtx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplDX11_SetupRenderState(draw_data, ctx); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply scissor/clipping rectangle const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; ctx->RSSetScissorRects(1, &r); // Bind texture, Draw ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID(); ctx->PSSetShaderResources(0, 1, &texture_srv); ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset); } } global_idx_offset += cmd_list->IdxBuffer.Size; global_vtx_offset += cmd_list->VtxBuffer.Size; } // Restore modified DX state ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); ctx->RSSetViewports(old.ViewportsCount, old.Viewports); ctx->RSSetState(old.RS); if (old.RS) old.RS->Release(); ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release(); ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release(); ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release(); ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release(); ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release(); for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release(); ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release(); ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); ctx->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release(); for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release(); ctx->IASetPrimitiveTopology(old.PrimitiveTopology); ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release(); ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); } static void ImGui_ImplDX11_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system { D3D11_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; ID3D11Texture2D* pTexture = nullptr; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); IM_ASSERT(pTexture != nullptr); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &bd->pFontTextureView); pTexture->Release(); } // Store our identifier io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView); // Create texture sampler // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) { D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler); } } bool ImGui_ImplDX11_CreateDeviceObjects() { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); if (!bd->pd3dDevice) return false; if (bd->pFontSampler) ImGui_ImplDX11_InvalidateDeviceObjects(); // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) // If you would like to use this DX11 sample code but remove this dependency you can: // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution] // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. // Create the vertex shader { static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ float2 pos : POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ PS_INPUT output;\ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ output.col = input.col;\ output.uv = input.uv;\ return output;\ }"; ID3DBlob* vertexShaderBlob; if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK) { vertexShaderBlob->Release(); return false; } // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) { vertexShaderBlob->Release(); return false; } vertexShaderBlob->Release(); // Create the constant buffer { D3D11_BUFFER_DESC desc; desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11); desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer); } } // Create the pixel shader { static const char* pixelShader = "struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ sampler sampler0;\ Texture2D texture0;\ \ float4 main(PS_INPUT input) : SV_Target\ {\ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ return out_col; \ }"; ID3DBlob* pixelShaderBlob; if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK) { pixelShaderBlob->Release(); return false; } pixelShaderBlob->Release(); } // Create the blending setup { D3D11_BLEND_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.AlphaToCoverageEnable = false; desc.RenderTarget[0].BlendEnable = true; desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState); } // Create the rasterizer state { D3D11_RASTERIZER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.FillMode = D3D11_FILL_SOLID; desc.CullMode = D3D11_CULL_NONE; desc.ScissorEnable = true; desc.DepthClipEnable = true; bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState); } // Create depth-stencil State { D3D11_DEPTH_STENCIL_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.DepthEnable = false; desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; desc.DepthFunc = D3D11_COMPARISON_ALWAYS; desc.StencilEnable = false; desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; desc.BackFace = desc.FrontFace; bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState); } ImGui_ImplDX11_CreateFontsTexture(); return true; } void ImGui_ImplDX11_InvalidateDeviceObjects() { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); if (!bd->pd3dDevice) return; if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well. if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; } if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; } if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; } if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; } if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; } if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; } } bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx11"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device IDXGIDevice* pDXGIDevice = nullptr; IDXGIAdapter* pDXGIAdapter = nullptr; IDXGIFactory* pFactory = nullptr; if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK) if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK) if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK) { bd->pd3dDevice = device; bd->pd3dDeviceContext = device_context; bd->pFactory = pFactory; } if (pDXGIDevice) pDXGIDevice->Release(); if (pDXGIAdapter) pDXGIAdapter->Release(); bd->pd3dDevice->AddRef(); bd->pd3dDeviceContext->AddRef(); return true; } void ImGui_ImplDX11_Shutdown() { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX11_InvalidateDeviceObjects(); if (bd->pFactory) { bd->pFactory->Release(); } if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); } io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplDX11_NewFrame() { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?"); if (!bd->pFontSampler) ImGui_ImplDX11_CreateDeviceObjects(); } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_vulkan.cpp
// dear imgui: Renderer Backend for Vulkan // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // To build this on 32-bit systems and support texture changes: // - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in our .vcxproj files) // - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. // - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) // - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in our batch files) // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering backend in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().) // 2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering. // 2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure. // 2024-01-19: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236) // 2024-01-11: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size (#3957). Fixed MinAllocationSize handing (#7189). // 2024-01-03: Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous "best practice" validation layer. (#7189, #4238) // 2024-01-03: Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as we don't reset them. // 2023-11-29: Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs vkDestroyCommandPool(). (#7075) // 2023-11-10: *BREAKING CHANGE*: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own command-buffer to upload fonts. // *BREAKING CHANGE*: Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary as we create and destroy those objects in the backend. // ImGui_ImplVulkan_CreateFontsTexture() is automatically called by NewFrame() the first time. // You can call ImGui_ImplVulkan_CreateFontsTexture() again to recreate the font atlas texture. // Added ImGui_ImplVulkan_DestroyFontsTexture() but you probably never need to call this. // 2023-07-04: Vulkan: Added optional support for VK_KHR_dynamic_rendering. User needs to set init_info->UseDynamicRendering = true and init_info->ColorAttachmentFormat. // 2023-01-02: Vulkan: Fixed sampler passed to ImGui_ImplVulkan_AddTexture() not being honored + removed a bunch of duplicate code. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-10-04: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symmetry. (#914, #5738). // 2022-01-20: Vulkan: Added support for ImTextureID as VkDescriptorSet. User need to call ImGui_ImplVulkan_AddTexture(). Building for 32-bit targets requires '#define ImTextureID ImU64'. (#914). // 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-03-22: Vulkan: Fix mapped memory validation error when buffer sizes are not multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize. // 2021-02-18: Vulkan: Change blending equation to preserve alpha in output buffer. // 2021-01-27: Vulkan: Added support for custom function load and IMGUI_IMPL_VULKAN_NO_PROTOTYPES by using ImGui_ImplVulkan_LoadFunctions(). // 2020-11-11: Vulkan: Added support for specifying which subpass to reference during VkPipeline creation. // 2020-09-07: Vulkan: Added VkPipeline parameter to ImGui_ImplVulkan_RenderDrawData (default to one passed to ImGui_ImplVulkan_Init). // 2020-05-04: Vulkan: Fixed crash if initial frame has no vertices. // 2020-04-26: Vulkan: Fixed edge case where render callbacks wouldn't be called if the ImDrawData didn't have vertices. // 2019-08-01: Vulkan: Added support for specifying multisample count. Set ImGui_ImplVulkan_InitInfo::MSAASamples to one of the VkSampleCountFlagBits values to use, default is non-multisampled as before. // 2019-05-29: Vulkan: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: Vulkan: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-04-04: *BREAKING CHANGE*: Vulkan: Added ImageCount/MinImageCount fields in ImGui_ImplVulkan_InitInfo, required for initialization (was previously a hard #define IMGUI_VK_QUEUED_FRAMES 2). Added ImGui_ImplVulkan_SetMinImageCount(). // 2019-04-04: Vulkan: Added VkInstance argument to ImGui_ImplVulkanH_CreateWindow() optional helper. // 2019-04-04: Vulkan: Avoid passing negative coordinates to vkCmdSetScissor, which debug validation layers do not like. // 2019-04-01: Vulkan: Support for 32-bit index buffer (#define ImDrawIdx unsigned int). // 2019-02-16: Vulkan: Viewport and clipping rectangles correctly using draw_data->FramebufferScale to allow retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-25: Vulkan: Fixed mishandled VkSurfaceCapabilitiesKHR::maxImageCount=0 case. // 2018-06-22: Inverted the parameters to ImGui_ImplVulkan_RenderDrawData() to be consistent with other backends. // 2018-06-08: Misc: Extracted imgui_impl_vulkan.cpp/.h away from the old combined GLFW+Vulkan example. // 2018-06-08: Vulkan: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-03-03: Vulkan: Various refactor, created a couple of ImGui_ImplVulkanH_XXX helper that the example can use and that viewport support will use. // 2018-03-01: Vulkan: Renamed ImGui_ImplVulkan_Init_Info to ImGui_ImplVulkan_InitInfo and fields to match more closely Vulkan terminology. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback, ImGui_ImplVulkan_Render() calls ImGui_ImplVulkan_RenderDrawData() itself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2017-05-15: Vulkan: Fix scissor offset being negative. Fix new Vulkan validation warnings. Set required depth member for buffer image copy. // 2016-11-13: Vulkan: Fix validation layer warnings and errors and redeclare gl_PerVertex. // 2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources. // 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_vulkan.h" #include <stdio.h> #ifndef IM_MAX #define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) #endif // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #endif // Forward Declarations struct ImGui_ImplVulkan_FrameRenderBuffers; struct ImGui_ImplVulkan_WindowRenderBuffers; bool ImGui_ImplVulkan_CreateDeviceObjects(); void ImGui_ImplVulkan_DestroyDeviceObjects(); void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); // Vulkan prototypes for use with custom loaders // (see description of IMGUI_IMPL_VULKAN_NO_PROTOTYPES in imgui_impl_vulkan.h #if defined(VK_NO_PROTOTYPES) && !defined(VOLK_H_) #define IMGUI_IMPL_VULKAN_USE_LOADER static bool g_FunctionsLoaded = false; #else static bool g_FunctionsLoaded = true; #endif #ifdef IMGUI_IMPL_VULKAN_USE_LOADER #define IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_MAP_MACRO) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateCommandBuffers) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkBeginCommandBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindBufferMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindImageMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindIndexBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindPipeline) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindVertexBuffers) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdCopyBufferToImage) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdDrawIndexed) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdPipelineBarrier) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdPushConstants) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdSetScissor) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdSetViewport) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateCommandPool) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateDescriptorSetLayout) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFence) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateFramebuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateGraphicsPipelines) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateImage) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateImageView) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreatePipelineLayout) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateRenderPass) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSampler) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSemaphore) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateShaderModule) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCreateSwapchainKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyCommandPool) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyDescriptorSetLayout) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFence) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyFramebuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyImage) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyImageView) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyPipeline) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyPipelineLayout) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyRenderPass) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySampler) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySemaphore) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroyShaderModule) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySurfaceKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySwapchainKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDeviceWaitIdle) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkEndCommandBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFlushMappedMemoryRanges) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeCommandBuffers) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetBufferMemoryRequirements) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetImageMemoryRequirements) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceMemoryProperties) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfaceFormatsKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfacePresentModesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetSwapchainImagesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkMapMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueSubmit) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueWaitIdle) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkResetCommandPool) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkUnmapMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets) // Define function pointers #define IMGUI_VULKAN_FUNC_DEF(func) static PFN_##func func; IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_DEF) #undef IMGUI_VULKAN_FUNC_DEF #endif // IMGUI_IMPL_VULKAN_USE_LOADER #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING static PFN_vkCmdBeginRenderingKHR ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR; static PFN_vkCmdEndRenderingKHR ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR; #endif // Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() // [Please zero-clear before use!] struct ImGui_ImplVulkan_FrameRenderBuffers { VkDeviceMemory VertexBufferMemory; VkDeviceMemory IndexBufferMemory; VkDeviceSize VertexBufferSize; VkDeviceSize IndexBufferSize; VkBuffer VertexBuffer; VkBuffer IndexBuffer; }; // Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers // [Please zero-clear before use!] struct ImGui_ImplVulkan_WindowRenderBuffers { uint32_t Index; uint32_t Count; ImGui_ImplVulkan_FrameRenderBuffers* FrameRenderBuffers; }; // Vulkan data struct ImGui_ImplVulkan_Data { ImGui_ImplVulkan_InitInfo VulkanInitInfo; VkDeviceSize BufferMemoryAlignment; VkPipelineCreateFlags PipelineCreateFlags; VkDescriptorSetLayout DescriptorSetLayout; VkPipelineLayout PipelineLayout; VkPipeline Pipeline; VkShaderModule ShaderModuleVert; VkShaderModule ShaderModuleFrag; // Font data VkSampler FontSampler; VkDeviceMemory FontMemory; VkImage FontImage; VkImageView FontView; VkDescriptorSet FontDescriptorSet; VkCommandPool FontCommandPool; VkCommandBuffer FontCommandBuffer; // Render buffers for main window ImGui_ImplVulkan_WindowRenderBuffers MainWindowRenderBuffers; ImGui_ImplVulkan_Data() { memset((void*)this, 0, sizeof(*this)); BufferMemoryAlignment = 256; } }; //----------------------------------------------------------------------------- // SHADERS //----------------------------------------------------------------------------- // backends/vulkan/glsl_shader.vert, compiled with: // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert /* #version 450 core layout(location = 0) in vec2 aPos; layout(location = 1) in vec2 aUV; layout(location = 2) in vec4 aColor; layout(push_constant) uniform uPushConstant { vec2 uScale; vec2 uTranslate; } pc; out gl_PerVertex { vec4 gl_Position; }; layout(location = 0) out struct { vec4 Color; vec2 UV; } Out; void main() { Out.Color = aColor; Out.UV = aUV; gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1); } */ static uint32_t __glsl_shader_vert_spv[] = { 0x07230203,0x00010000,0x00080001,0x0000002e,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015, 0x0000001b,0x0000001c,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43, 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f, 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005, 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000, 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00040005,0x0000001c, 0x736f5061,0x00000000,0x00060005,0x0000001e,0x73755075,0x6e6f4368,0x6e617473,0x00000074, 0x00050006,0x0000001e,0x00000000,0x61635375,0x0000656c,0x00060006,0x0000001e,0x00000001, 0x61725475,0x616c736e,0x00006574,0x00030005,0x00000020,0x00006370,0x00040047,0x0000000b, 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015, 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047, 0x00000019,0x00000002,0x00040047,0x0000001c,0x0000001e,0x00000000,0x00050048,0x0000001e, 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000008, 0x00030047,0x0000001e,0x00000002,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002, 0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040017, 0x00000008,0x00000006,0x00000002,0x0004001e,0x00000009,0x00000007,0x00000008,0x00040020, 0x0000000a,0x00000003,0x00000009,0x0004003b,0x0000000a,0x0000000b,0x00000003,0x00040015, 0x0000000c,0x00000020,0x00000001,0x0004002b,0x0000000c,0x0000000d,0x00000000,0x00040020, 0x0000000e,0x00000001,0x00000007,0x0004003b,0x0000000e,0x0000000f,0x00000001,0x00040020, 0x00000011,0x00000003,0x00000007,0x0004002b,0x0000000c,0x00000013,0x00000001,0x00040020, 0x00000014,0x00000001,0x00000008,0x0004003b,0x00000014,0x00000015,0x00000001,0x00040020, 0x00000017,0x00000003,0x00000008,0x0003001e,0x00000019,0x00000007,0x00040020,0x0000001a, 0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004003b,0x00000014, 0x0000001c,0x00000001,0x0004001e,0x0000001e,0x00000008,0x00000008,0x00040020,0x0000001f, 0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040020,0x00000021, 0x00000009,0x00000008,0x0004002b,0x00000006,0x00000028,0x00000000,0x0004002b,0x00000006, 0x00000029,0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, 0x00000005,0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012, 0x0000000b,0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016, 0x00000015,0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018, 0x00000016,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x00050041,0x00000021,0x00000022, 0x00000020,0x0000000d,0x0004003d,0x00000008,0x00000023,0x00000022,0x00050085,0x00000008, 0x00000024,0x0000001d,0x00000023,0x00050041,0x00000021,0x00000025,0x00000020,0x00000013, 0x0004003d,0x00000008,0x00000026,0x00000025,0x00050081,0x00000008,0x00000027,0x00000024, 0x00000026,0x00050051,0x00000006,0x0000002a,0x00000027,0x00000000,0x00050051,0x00000006, 0x0000002b,0x00000027,0x00000001,0x00070050,0x00000007,0x0000002c,0x0000002a,0x0000002b, 0x00000028,0x00000029,0x00050041,0x00000011,0x0000002d,0x0000001b,0x0000000d,0x0003003e, 0x0000002d,0x0000002c,0x000100fd,0x00010038 }; // backends/vulkan/glsl_shader.frag, compiled with: // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag /* #version 450 core layout(location = 0) out vec4 fColor; layout(set=0, binding=0) uniform sampler2D sTexture; layout(location = 0) in struct { vec4 Color; vec2 UV; } In; void main() { fColor = In.Color * texture(sTexture, In.UV.st); } */ static uint32_t __glsl_shader_frag_spv[] = { 0x07230203,0x00010000,0x00080001,0x0000001e,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010, 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000, 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001, 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00050005,0x00000016,0x78655473,0x65727574, 0x00000000,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,0x0000001e, 0x00000000,0x00040047,0x00000016,0x00000022,0x00000000,0x00040047,0x00000016,0x00000021, 0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006, 0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,0x00000003, 0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,0x00000006, 0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,0x00000001, 0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,0x00000020, 0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,0x00000001, 0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000, 0x00000001,0x00000000,0x0003001b,0x00000014,0x00000013,0x00040020,0x00000015,0x00000000, 0x00000014,0x0004003b,0x00000015,0x00000016,0x00000000,0x0004002b,0x0000000e,0x00000018, 0x00000001,0x00040020,0x00000019,0x00000001,0x0000000a,0x00050036,0x00000002,0x00000004, 0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,0x00000010,0x00000011,0x0000000d, 0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,0x0004003d,0x00000014,0x00000017, 0x00000016,0x00050041,0x00000019,0x0000001a,0x0000000d,0x00000018,0x0004003d,0x0000000a, 0x0000001b,0x0000001a,0x00050057,0x00000007,0x0000001c,0x00000017,0x0000001b,0x00050085, 0x00000007,0x0000001d,0x00000012,0x0000001c,0x0003003e,0x00000009,0x0000001d,0x000100fd, 0x00010038 }; //----------------------------------------------------------------------------- // FUNCTIONS //----------------------------------------------------------------------------- // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support is not tested and probably dysfunctional in this backend. static ImGui_ImplVulkan_Data* ImGui_ImplVulkan_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplVulkan_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkPhysicalDeviceMemoryProperties prop; vkGetPhysicalDeviceMemoryProperties(v->PhysicalDevice, &prop); for (uint32_t i = 0; i < prop.memoryTypeCount; i++) if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1 << i)) return i; return 0xFFFFFFFF; // Unable to find memoryType } static void check_vk_result(VkResult err) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); if (!bd) return; ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (v->CheckVkResultFn) v->CheckVkResultFn(err); } // Same as IM_MEMALIGN(). 'alignment' must be a power of two. static inline VkDeviceSize AlignBufferSize(VkDeviceSize size, VkDeviceSize alignment) { return (size + alignment - 1) & ~(alignment - 1); } static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& buffer_size, size_t new_size, VkBufferUsageFlagBits usage) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkResult err; if (buffer != VK_NULL_HANDLE) vkDestroyBuffer(v->Device, buffer, v->Allocator); if (buffer_memory != VK_NULL_HANDLE) vkFreeMemory(v->Device, buffer_memory, v->Allocator); VkDeviceSize buffer_size_aligned = AlignBufferSize(IM_MAX(v->MinAllocationSize, new_size), bd->BufferMemoryAlignment); VkBufferCreateInfo buffer_info = {}; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.size = buffer_size_aligned; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer); check_vk_result(err); VkMemoryRequirements req; vkGetBufferMemoryRequirements(v->Device, buffer, &req); bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = req.size; alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &buffer_memory); check_vk_result(err); err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0); check_vk_result(err); buffer_size = buffer_size_aligned; } static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* rb, int fb_width, int fb_height) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); // Bind pipeline: { vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); } // Bind Vertex And Index Buffer: if (draw_data->TotalVtxCount > 0) { VkBuffer vertex_buffers[1] = { rb->VertexBuffer }; VkDeviceSize vertex_offset[1] = { 0 }; vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset); vkCmdBindIndexBuffer(command_buffer, rb->IndexBuffer, 0, sizeof(ImDrawIdx) == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); } // Setup viewport: { VkViewport viewport; viewport.x = 0; viewport.y = 0; viewport.width = (float)fb_width; viewport.height = (float)fb_height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; vkCmdSetViewport(command_buffer, 0, 1, &viewport); } // Setup scale and translation: // Our visible imgui space lies from draw_data->DisplayPps (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. { float scale[2]; scale[0] = 2.0f / draw_data->DisplaySize.x; scale[1] = 2.0f / draw_data->DisplaySize.y; float translate[2]; translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0]; translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1]; vkCmdPushConstants(command_buffer, bd->PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 0, sizeof(float) * 2, scale); vkCmdPushConstants(command_buffer, bd->PipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, sizeof(float) * 2, sizeof(float) * 2, translate); } } // Render function void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width <= 0 || fb_height <= 0) return; ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (pipeline == VK_NULL_HANDLE) pipeline = bd->Pipeline; // Allocate array to store enough vertex/index buffers ImGui_ImplVulkan_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers; if (wrb->FrameRenderBuffers == nullptr) { wrb->Index = 0; wrb->Count = v->ImageCount; wrb->FrameRenderBuffers = (ImGui_ImplVulkan_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); } IM_ASSERT(wrb->Count == v->ImageCount); wrb->Index = (wrb->Index + 1) % wrb->Count; ImGui_ImplVulkan_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; if (draw_data->TotalVtxCount > 0) { // Create or resize the vertex/index buffers size_t vertex_size = AlignBufferSize(draw_data->TotalVtxCount * sizeof(ImDrawVert), bd->BufferMemoryAlignment); size_t index_size = AlignBufferSize(draw_data->TotalIdxCount * sizeof(ImDrawIdx), bd->BufferMemoryAlignment); if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size) CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size) CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); // Upload vertex/index data into a single contiguous GPU buffer ImDrawVert* vtx_dst = nullptr; ImDrawIdx* idx_dst = nullptr; VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)&vtx_dst); check_vk_result(err); err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)&idx_dst); check_vk_result(err); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } VkMappedMemoryRange range[2] = {}; range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range[0].memory = rb->VertexBufferMemory; range[0].size = VK_WHOLE_SIZE; range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range[1].memory = rb->IndexBufferMemory; range[1].size = VK_WHOLE_SIZE; err = vkFlushMappedMemoryRanges(v->Device, 2, range); check_vk_result(err); vkUnmapMemory(v->Device, rb->VertexBufferMemory); vkUnmapMemory(v->Device, rb->IndexBufferMemory); } // Setup desired Vulkan state ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplVulkan_SetupRenderState(draw_data, pipeline, command_buffer, rb, fb_width, fb_height); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); // Clamp to viewport as vkCmdSetScissor() won't accept values that are off bounds if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply scissor/clipping rectangle VkRect2D scissor; scissor.offset.x = (int32_t)(clip_min.x); scissor.offset.y = (int32_t)(clip_min.y); scissor.extent.width = (uint32_t)(clip_max.x - clip_min.x); scissor.extent.height = (uint32_t)(clip_max.y - clip_min.y); vkCmdSetScissor(command_buffer, 0, 1, &scissor); // Bind DescriptorSet with font or user texture VkDescriptorSet desc_set[1] = { (VkDescriptorSet)pcmd->TextureId }; if (sizeof(ImTextureID) < sizeof(ImU64)) { // We don't support texture switches if ImTextureID hasn't been redefined to be 64-bit. Do a flaky check that other textures haven't been used. IM_ASSERT(pcmd->TextureId == (ImTextureID)bd->FontDescriptorSet); desc_set[0] = bd->FontDescriptorSet; } vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, desc_set, 0, nullptr); // Draw vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } } global_idx_offset += cmd_list->IdxBuffer.Size; global_vtx_offset += cmd_list->VtxBuffer.Size; } // Note: at this point both vkCmdSetViewport() and vkCmdSetScissor() have been called. // Our last values will leak into user/application rendering IF: // - Your app uses a pipeline with VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR dynamic state // - And you forgot to call vkCmdSetViewport() and vkCmdSetScissor() yourself to explicitly set that state. // If you use VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR you are responsible for setting the values before rendering. // In theory we should aim to backup/restore those values but I am not sure this is possible. // We perform a call to vkCmdSetScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644) VkRect2D scissor = { { 0, 0 }, { (uint32_t)fb_width, (uint32_t)fb_height } }; vkCmdSetScissor(command_buffer, 0, 1, &scissor); } bool ImGui_ImplVulkan_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkResult err; // Destroy existing texture (if any) if (bd->FontView || bd->FontImage || bd->FontMemory || bd->FontDescriptorSet) { vkQueueWaitIdle(v->Queue); ImGui_ImplVulkan_DestroyFontsTexture(); } // Create command pool/buffer if (bd->FontCommandPool == VK_NULL_HANDLE) { VkCommandPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; info.flags = 0; info.queueFamilyIndex = v->QueueFamily; vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->FontCommandPool); } if (bd->FontCommandBuffer == VK_NULL_HANDLE) { VkCommandBufferAllocateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; info.commandPool = bd->FontCommandPool; info.commandBufferCount = 1; err = vkAllocateCommandBuffers(v->Device, &info, &bd->FontCommandBuffer); check_vk_result(err); } // Start command buffer { err = vkResetCommandPool(v->Device, bd->FontCommandPool, 0); check_vk_result(err); VkCommandBufferBeginInfo begin_info = {}; begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; err = vkBeginCommandBuffer(bd->FontCommandBuffer, &begin_info); check_vk_result(err); } unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); size_t upload_size = width * height * 4 * sizeof(char); // Create the Image: { VkImageCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; info.imageType = VK_IMAGE_TYPE_2D; info.format = VK_FORMAT_R8G8B8A8_UNORM; info.extent.width = width; info.extent.height = height; info.extent.depth = 1; info.mipLevels = 1; info.arrayLayers = 1; info.samples = VK_SAMPLE_COUNT_1_BIT; info.tiling = VK_IMAGE_TILING_OPTIMAL; info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; err = vkCreateImage(v->Device, &info, v->Allocator, &bd->FontImage); check_vk_result(err); VkMemoryRequirements req; vkGetImageMemoryRequirements(v->Device, bd->FontImage, &req); VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits); err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->FontMemory); check_vk_result(err); err = vkBindImageMemory(v->Device, bd->FontImage, bd->FontMemory, 0); check_vk_result(err); } // Create the Image View: { VkImageViewCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; info.image = bd->FontImage; info.viewType = VK_IMAGE_VIEW_TYPE_2D; info.format = VK_FORMAT_R8G8B8A8_UNORM; info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; info.subresourceRange.levelCount = 1; info.subresourceRange.layerCount = 1; err = vkCreateImageView(v->Device, &info, v->Allocator, &bd->FontView); check_vk_result(err); } // Create the Descriptor Set: bd->FontDescriptorSet = (VkDescriptorSet)ImGui_ImplVulkan_AddTexture(bd->FontSampler, bd->FontView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // Create the Upload Buffer: VkDeviceMemory upload_buffer_memory; VkBuffer upload_buffer; { VkBufferCreateInfo buffer_info = {}; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.size = upload_size; buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &upload_buffer); check_vk_result(err); VkMemoryRequirements req; vkGetBufferMemoryRequirements(v->Device, upload_buffer, &req); bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &upload_buffer_memory); check_vk_result(err); err = vkBindBufferMemory(v->Device, upload_buffer, upload_buffer_memory, 0); check_vk_result(err); } // Upload to Buffer: { char* map = nullptr; err = vkMapMemory(v->Device, upload_buffer_memory, 0, upload_size, 0, (void**)(&map)); check_vk_result(err); memcpy(map, pixels, upload_size); VkMappedMemoryRange range[1] = {}; range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range[0].memory = upload_buffer_memory; range[0].size = upload_size; err = vkFlushMappedMemoryRanges(v->Device, 1, range); check_vk_result(err); vkUnmapMemory(v->Device, upload_buffer_memory); } // Copy to Image: { VkImageMemoryBarrier copy_barrier[1] = {}; copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; copy_barrier[0].image = bd->FontImage; copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_barrier[0].subresourceRange.levelCount = 1; copy_barrier[0].subresourceRange.layerCount = 1; vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.layerCount = 1; region.imageExtent.width = width; region.imageExtent.height = height; region.imageExtent.depth = 1; vkCmdCopyBufferToImage(bd->FontCommandBuffer, upload_buffer, bd->FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region); VkImageMemoryBarrier use_barrier[1] = {}; use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; use_barrier[0].image = bd->FontImage; use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; use_barrier[0].subresourceRange.levelCount = 1; use_barrier[0].subresourceRange.layerCount = 1; vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier); } // Store our identifier io.Fonts->SetTexID((ImTextureID)bd->FontDescriptorSet); // End command buffer VkSubmitInfo end_info = {}; end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; end_info.commandBufferCount = 1; end_info.pCommandBuffers = &bd->FontCommandBuffer; err = vkEndCommandBuffer(bd->FontCommandBuffer); check_vk_result(err); err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE); check_vk_result(err); err = vkQueueWaitIdle(v->Queue); check_vk_result(err); vkDestroyBuffer(v->Device, upload_buffer, v->Allocator); vkFreeMemory(v->Device, upload_buffer_memory, v->Allocator); return true; } // You probably never need to call this, as it is called by ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_Shutdown(). void ImGui_ImplVulkan_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; if (bd->FontDescriptorSet) { ImGui_ImplVulkan_RemoveTexture(bd->FontDescriptorSet); bd->FontDescriptorSet = VK_NULL_HANDLE; io.Fonts->SetTexID(0); } if (bd->FontView) { vkDestroyImageView(v->Device, bd->FontView, v->Allocator); bd->FontView = VK_NULL_HANDLE; } if (bd->FontImage) { vkDestroyImage(v->Device, bd->FontImage, v->Allocator); bd->FontImage = VK_NULL_HANDLE; } if (bd->FontMemory) { vkFreeMemory(v->Device, bd->FontMemory, v->Allocator); bd->FontMemory = VK_NULL_HANDLE; } } static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator) { // Create the shader modules ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); if (bd->ShaderModuleVert == VK_NULL_HANDLE) { VkShaderModuleCreateInfo vert_info = {}; vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; vert_info.codeSize = sizeof(__glsl_shader_vert_spv); vert_info.pCode = (uint32_t*)__glsl_shader_vert_spv; VkResult err = vkCreateShaderModule(device, &vert_info, allocator, &bd->ShaderModuleVert); check_vk_result(err); } if (bd->ShaderModuleFrag == VK_NULL_HANDLE) { VkShaderModuleCreateInfo frag_info = {}; frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; frag_info.codeSize = sizeof(__glsl_shader_frag_spv); frag_info.pCode = (uint32_t*)__glsl_shader_frag_spv; VkResult err = vkCreateShaderModule(device, &frag_info, allocator, &bd->ShaderModuleFrag); check_vk_result(err); } } static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline, uint32_t subpass) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_CreateShaderModules(device, allocator); VkPipelineShaderStageCreateInfo stage[2] = {}; stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT; stage[0].module = bd->ShaderModuleVert; stage[0].pName = "main"; stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; stage[1].module = bd->ShaderModuleFrag; stage[1].pName = "main"; VkVertexInputBindingDescription binding_desc[1] = {}; binding_desc[0].stride = sizeof(ImDrawVert); binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; VkVertexInputAttributeDescription attribute_desc[3] = {}; attribute_desc[0].location = 0; attribute_desc[0].binding = binding_desc[0].binding; attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT; attribute_desc[0].offset = offsetof(ImDrawVert, pos); attribute_desc[1].location = 1; attribute_desc[1].binding = binding_desc[0].binding; attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT; attribute_desc[1].offset = offsetof(ImDrawVert, uv); attribute_desc[2].location = 2; attribute_desc[2].binding = binding_desc[0].binding; attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM; attribute_desc[2].offset = offsetof(ImDrawVert, col); VkPipelineVertexInputStateCreateInfo vertex_info = {}; vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertex_info.vertexBindingDescriptionCount = 1; vertex_info.pVertexBindingDescriptions = binding_desc; vertex_info.vertexAttributeDescriptionCount = 3; vertex_info.pVertexAttributeDescriptions = attribute_desc; VkPipelineInputAssemblyStateCreateInfo ia_info = {}; ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; VkPipelineViewportStateCreateInfo viewport_info = {}; viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewport_info.viewportCount = 1; viewport_info.scissorCount = 1; VkPipelineRasterizationStateCreateInfo raster_info = {}; raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; raster_info.polygonMode = VK_POLYGON_MODE_FILL; raster_info.cullMode = VK_CULL_MODE_NONE; raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; raster_info.lineWidth = 1.0f; VkPipelineMultisampleStateCreateInfo ms_info = {}; ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; ms_info.rasterizationSamples = (MSAASamples != 0) ? MSAASamples : VK_SAMPLE_COUNT_1_BIT; VkPipelineColorBlendAttachmentState color_attachment[1] = {}; color_attachment[0].blendEnable = VK_TRUE; color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD; color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD; color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; VkPipelineDepthStencilStateCreateInfo depth_info = {}; depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; VkPipelineColorBlendStateCreateInfo blend_info = {}; blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; blend_info.attachmentCount = 1; blend_info.pAttachments = color_attachment; VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamic_state = {}; dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states); dynamic_state.pDynamicStates = dynamic_states; VkGraphicsPipelineCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; info.flags = bd->PipelineCreateFlags; info.stageCount = 2; info.pStages = stage; info.pVertexInputState = &vertex_info; info.pInputAssemblyState = &ia_info; info.pViewportState = &viewport_info; info.pRasterizationState = &raster_info; info.pMultisampleState = &ms_info; info.pDepthStencilState = &depth_info; info.pColorBlendState = &blend_info; info.pDynamicState = &dynamic_state; info.layout = bd->PipelineLayout; info.renderPass = renderPass; info.subpass = subpass; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING if (bd->VulkanInitInfo.UseDynamicRendering) { IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be NULL"); info.pNext = &bd->VulkanInitInfo.PipelineRenderingCreateInfo; info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. } #endif VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline); check_vk_result(err); } bool ImGui_ImplVulkan_CreateDeviceObjects() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkResult err; if (!bd->FontSampler) { // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. VkSamplerCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; info.magFilter = VK_FILTER_LINEAR; info.minFilter = VK_FILTER_LINEAR; info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; info.minLod = -1000; info.maxLod = 1000; info.maxAnisotropy = 1.0f; err = vkCreateSampler(v->Device, &info, v->Allocator, &bd->FontSampler); check_vk_result(err); } if (!bd->DescriptorSetLayout) { VkDescriptorSetLayoutBinding binding[1] = {}; binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; binding[0].descriptorCount = 1; binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; VkDescriptorSetLayoutCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; info.bindingCount = 1; info.pBindings = binding; err = vkCreateDescriptorSetLayout(v->Device, &info, v->Allocator, &bd->DescriptorSetLayout); check_vk_result(err); } if (!bd->PipelineLayout) { // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix VkPushConstantRange push_constants[1] = {}; push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; push_constants[0].offset = sizeof(float) * 0; push_constants[0].size = sizeof(float) * 4; VkDescriptorSetLayout set_layout[1] = { bd->DescriptorSetLayout }; VkPipelineLayoutCreateInfo layout_info = {}; layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; layout_info.setLayoutCount = 1; layout_info.pSetLayouts = set_layout; layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = push_constants; err = vkCreatePipelineLayout(v->Device, &layout_info, v->Allocator, &bd->PipelineLayout); check_vk_result(err); } ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, &bd->Pipeline, v->Subpass); return true; } void ImGui_ImplVulkan_DestroyDeviceObjects() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); ImGui_ImplVulkan_DestroyFontsTexture(); if (bd->FontCommandBuffer) { vkFreeCommandBuffers(v->Device, bd->FontCommandPool, 1, &bd->FontCommandBuffer); bd->FontCommandBuffer = VK_NULL_HANDLE; } if (bd->FontCommandPool) { vkDestroyCommandPool(v->Device, bd->FontCommandPool, v->Allocator); bd->FontCommandPool = VK_NULL_HANDLE; } if (bd->ShaderModuleVert) { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; } if (bd->ShaderModuleFrag) { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; } if (bd->FontSampler) { vkDestroySampler(v->Device, bd->FontSampler, v->Allocator); bd->FontSampler = VK_NULL_HANDLE; } if (bd->DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; } if (bd->PipelineLayout) { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; } if (bd->Pipeline) { vkDestroyPipeline(v->Device, bd->Pipeline, v->Allocator); bd->Pipeline = VK_NULL_HANDLE; } } bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data) { // Load function pointers // You can use the default Vulkan loader using: // ImGui_ImplVulkan_LoadFunctions([](const char* function_name, void*) { return vkGetInstanceProcAddr(your_vk_isntance, function_name); }); // But this would be roughly equivalent to not setting VK_NO_PROTOTYPES. #ifdef IMGUI_IMPL_VULKAN_USE_LOADER #define IMGUI_VULKAN_FUNC_LOAD(func) \ func = reinterpret_cast<decltype(func)>(loader_func(#func, user_data)); \ if (func == nullptr) \ return false; IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_LOAD) #undef IMGUI_VULKAN_FUNC_LOAD #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING // Manually load those two (see #5446) ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(loader_func("vkCmdBeginRenderingKHR", user_data)); ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(loader_func("vkCmdEndRenderingKHR", user_data)); #endif #else IM_UNUSED(loader_func); IM_UNUSED(user_data); #endif g_FunctionsLoaded = true; return true; } bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); if (info->UseDynamicRendering) { #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #ifndef IMGUI_IMPL_VULKAN_USE_LOADER ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdBeginRenderingKHR")); ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdEndRenderingKHR")); #endif IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR != nullptr); IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR != nullptr); #else IM_ASSERT(0 && "Can't use dynamic rendering when neither VK_VERSION_1_3 or VK_KHR_dynamic_rendering is defined."); #endif } ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplVulkan_Data* bd = IM_NEW(ImGui_ImplVulkan_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_vulkan"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. IM_ASSERT(info->Instance != VK_NULL_HANDLE); IM_ASSERT(info->PhysicalDevice != VK_NULL_HANDLE); IM_ASSERT(info->Device != VK_NULL_HANDLE); IM_ASSERT(info->Queue != VK_NULL_HANDLE); IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE); IM_ASSERT(info->MinImageCount >= 2); IM_ASSERT(info->ImageCount >= info->MinImageCount); if (info->UseDynamicRendering == false) IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); bd->VulkanInitInfo = *info; ImGui_ImplVulkan_CreateDeviceObjects(); return true; } void ImGui_ImplVulkan_Shutdown() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplVulkan_NewFrame() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?"); if (!bd->FontDescriptorSet) ImGui_ImplVulkan_CreateFontsTexture(); } void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); IM_ASSERT(min_image_count >= 2); if (bd->VulkanInitInfo.MinImageCount == min_image_count) return; ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkResult err = vkDeviceWaitIdle(v->Device); check_vk_result(err); ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); bd->VulkanInitInfo.MinImageCount = min_image_count; } // Register a texture // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem, please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; // Create Descriptor Set: VkDescriptorSet descriptor_set; { VkDescriptorSetAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc_info.descriptorPool = v->DescriptorPool; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = &bd->DescriptorSetLayout; VkResult err = vkAllocateDescriptorSets(v->Device, &alloc_info, &descriptor_set); check_vk_result(err); } // Update the Descriptor Set: { VkDescriptorImageInfo desc_image[1] = {}; desc_image[0].sampler = sampler; desc_image[0].imageView = image_view; desc_image[0].imageLayout = image_layout; VkWriteDescriptorSet write_desc[1] = {}; write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_desc[0].dstSet = descriptor_set; write_desc[0].descriptorCount = 1; write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; write_desc[0].pImageInfo = desc_image; vkUpdateDescriptorSets(v->Device, 1, write_desc, 0, nullptr); } return descriptor_set; } void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; vkFreeDescriptorSets(v->Device, v->DescriptorPool, 1, &descriptor_set); } void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) { if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; } buffers->VertexBufferSize = 0; buffers->IndexBufferSize = 0; } void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) { for (uint32_t n = 0; n < buffers->Count; n++) ImGui_ImplVulkan_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator); IM_FREE(buffers->FrameRenderBuffers); buffers->FrameRenderBuffers = nullptr; buffers->Index = 0; buffers->Count = 0; } //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. // 2) the upcoming multi-viewport feature will need them internally. // Generally we avoid exposing any kind of superfluous high-level helpers in the backends, // but it is too much code to duplicate everywhere so we exceptionally expose them. // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); IM_ASSERT(request_formats != nullptr); IM_ASSERT(request_formats_count > 0); // 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 Swapchain 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 avail_count; vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, nullptr); ImVector<VkSurfaceFormatKHR> avail_format; avail_format.resize((int)avail_count); vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data); // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available if (avail_count == 1) { if (avail_format[0].format == VK_FORMAT_UNDEFINED) { VkSurfaceFormatKHR ret; ret.format = request_formats[0]; ret.colorSpace = request_color_space; return ret; } else { // No point in searching another format return avail_format[0]; } } else { // Request several formats, the first found will be used for (int request_i = 0; request_i < request_formats_count; request_i++) for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space) return avail_format[avail_i]; // If none of the requested image formats could be found, use the first available return avail_format[0]; } } VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); IM_ASSERT(request_modes != nullptr); IM_ASSERT(request_modes_count > 0); // Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory uint32_t avail_count = 0; vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, nullptr); ImVector<VkPresentModeKHR> avail_modes; avail_modes.resize((int)avail_count); vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, avail_modes.Data); //for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) // printf("[vulkan] avail_modes[%d] = %d\n", avail_i, avail_modes[avail_i]); for (int request_i = 0; request_i < request_modes_count; request_i++) for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) if (request_modes[request_i] == avail_modes[avail_i]) return request_modes[request_i]; return VK_PRESENT_MODE_FIFO_KHR; // Always available } void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) { IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); IM_UNUSED(physical_device); // Create Command Buffers VkResult err; for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; { VkCommandPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; info.flags = 0; info.queueFamilyIndex = queue_family; err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool); check_vk_result(err); } { VkCommandBufferAllocateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; info.commandPool = fd->CommandPool; info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; info.commandBufferCount = 1; err = vkAllocateCommandBuffers(device, &info, &fd->CommandBuffer); check_vk_result(err); } { VkFenceCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; info.flags = VK_FENCE_CREATE_SIGNALED_BIT; err = vkCreateFence(device, &info, allocator, &fd->Fence); check_vk_result(err); } } for (uint32_t i = 0; i < wd->SemaphoreCount; i++) { ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i]; { VkSemaphoreCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; err = vkCreateSemaphore(device, &info, allocator, &fsd->ImageAcquiredSemaphore); check_vk_result(err); err = vkCreateSemaphore(device, &info, allocator, &fsd->RenderCompleteSemaphore); check_vk_result(err); } } } int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode) { if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR) return 3; if (present_mode == VK_PRESENT_MODE_FIFO_KHR || present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) return 2; if (present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR) return 1; IM_ASSERT(0); return 1; } // Also destroy old swap chain and in-flight frames data, if any. void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count) { VkResult err; VkSwapchainKHR old_swapchain = wd->Swapchain; wd->Swapchain = VK_NULL_HANDLE; err = vkDeviceWaitIdle(device); check_vk_result(err); // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. // Destroy old Framebuffer for (uint32_t i = 0; i < wd->ImageCount; i++) ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); for (uint32_t i = 0; i < wd->SemaphoreCount; i++) ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); IM_FREE(wd->Frames); IM_FREE(wd->FrameSemaphores); wd->Frames = nullptr; wd->FrameSemaphores = nullptr; wd->ImageCount = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); if (wd->Pipeline) vkDestroyPipeline(device, wd->Pipeline, allocator); // If min image count was not specified, request different count of images dependent on selected present mode if (min_image_count == 0) min_image_count = ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(wd->PresentMode); // Create Swapchain { VkSwapchainCreateInfoKHR info = {}; info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; info.surface = wd->Surface; info.minImageCount = min_image_count; info.imageFormat = wd->SurfaceFormat.format; info.imageColorSpace = wd->SurfaceFormat.colorSpace; info.imageArrayLayers = 1; info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // Assume that graphics family == present family info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; info.presentMode = wd->PresentMode; info.clipped = VK_TRUE; info.oldSwapchain = old_swapchain; VkSurfaceCapabilitiesKHR cap; err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, wd->Surface, &cap); check_vk_result(err); if (info.minImageCount < cap.minImageCount) info.minImageCount = cap.minImageCount; else if (cap.maxImageCount != 0 && info.minImageCount > cap.maxImageCount) info.minImageCount = cap.maxImageCount; if (cap.currentExtent.width == 0xffffffff) { info.imageExtent.width = wd->Width = w; info.imageExtent.height = wd->Height = h; } else { info.imageExtent.width = wd->Width = cap.currentExtent.width; info.imageExtent.height = wd->Height = cap.currentExtent.height; } err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain); check_vk_result(err); err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, nullptr); check_vk_result(err); VkImage backbuffers[16] = {}; IM_ASSERT(wd->ImageCount >= min_image_count); IM_ASSERT(wd->ImageCount < IM_ARRAYSIZE(backbuffers)); err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers); check_vk_result(err); IM_ASSERT(wd->Frames == nullptr && wd->FrameSemaphores == nullptr); wd->SemaphoreCount = wd->ImageCount + 1; wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount); wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->SemaphoreCount); memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount); memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount); for (uint32_t i = 0; i < wd->ImageCount; i++) wd->Frames[i].Backbuffer = backbuffers[i]; } if (old_swapchain) vkDestroySwapchainKHR(device, old_swapchain, allocator); // Create the Render Pass if (wd->UseDynamicRendering == false) { VkAttachmentDescription attachment = {}; attachment.format = wd->SurfaceFormat.format; attachment.samples = VK_SAMPLE_COUNT_1_BIT; attachment.loadOp = wd->ClearEnable ? VK_ATTACHMENT_LOAD_OP_CLEAR : VK_ATTACHMENT_LOAD_OP_DONT_CARE; 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_PRESENT_SRC_KHR; VkAttachmentReference color_attachment = {}; color_attachment.attachment = 0; color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass = {}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &color_attachment; VkSubpassDependency dependency = {}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; VkRenderPassCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; info.attachmentCount = 1; info.pAttachments = &attachment; info.subpassCount = 1; info.pSubpasses = &subpass; info.dependencyCount = 1; info.pDependencies = &dependency; err = vkCreateRenderPass(device, &info, allocator, &wd->RenderPass); check_vk_result(err); // We do not create a pipeline by default as this is also used by examples' main.cpp, // but secondary viewport in multi-viewport mode may want to create one with: //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, v->Subpass); } // Create The Image Views { VkImageViewCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; info.viewType = VK_IMAGE_VIEW_TYPE_2D; info.format = wd->SurfaceFormat.format; info.components.r = VK_COMPONENT_SWIZZLE_R; info.components.g = VK_COMPONENT_SWIZZLE_G; info.components.b = VK_COMPONENT_SWIZZLE_B; info.components.a = VK_COMPONENT_SWIZZLE_A; VkImageSubresourceRange image_range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; info.subresourceRange = image_range; for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; info.image = fd->Backbuffer; err = vkCreateImageView(device, &info, allocator, &fd->BackbufferView); check_vk_result(err); } } // Create Framebuffer if (wd->UseDynamicRendering == false) { VkImageView attachment[1]; VkFramebufferCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; info.renderPass = wd->RenderPass; info.attachmentCount = 1; info.pAttachments = attachment; info.width = wd->Width; info.height = wd->Height; info.layers = 1; for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; attachment[0] = fd->BackbufferView; err = vkCreateFramebuffer(device, &info, allocator, &fd->Framebuffer); check_vk_result(err); } } } // Create or resize window void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); (void)instance; ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count); ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); } void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) { vkDeviceWaitIdle(device); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals) //vkQueueWaitIdle(bd->Queue); for (uint32_t i = 0; i < wd->ImageCount; i++) ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); for (uint32_t i = 0; i < wd->SemaphoreCount; i++) ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); IM_FREE(wd->Frames); IM_FREE(wd->FrameSemaphores); wd->Frames = nullptr; wd->FrameSemaphores = nullptr; vkDestroyPipeline(device, wd->Pipeline, allocator); vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); vkDestroySurfaceKHR(instance, wd->Surface, allocator); *wd = ImGui_ImplVulkanH_Window(); } void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator) { vkDestroyFence(device, fd->Fence, allocator); vkFreeCommandBuffers(device, fd->CommandPool, 1, &fd->CommandBuffer); vkDestroyCommandPool(device, fd->CommandPool, allocator); fd->Fence = VK_NULL_HANDLE; fd->CommandBuffer = VK_NULL_HANDLE; fd->CommandPool = VK_NULL_HANDLE; vkDestroyImageView(device, fd->BackbufferView, allocator); vkDestroyFramebuffer(device, fd->Framebuffer, allocator); } void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator) { vkDestroySemaphore(device, fsd->ImageAcquiredSemaphore, allocator); vkDestroySemaphore(device, fsd->RenderCompleteSemaphore, allocator); fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_win32.h
// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(); // Win32 message handler your application need to call. // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h> from this helper. // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. // - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. #if 0 extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); #endif // DPI-related helpers (optional) // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor // Transparency related helpers (optional) [experimental] // - Use to enable alpha compositing transparency with the desktop. // - Use together with e.g. clearing your framebuffer with zero-alpha. IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_glfw.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_glfw.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_glfw.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplGlfw_InitForOpenGL(cimgui::GLFWwindow* window, bool install_callbacks) { return ::ImGui_ImplGlfw_InitForOpenGL(reinterpret_cast<::GLFWwindow*>(window), install_callbacks); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplGlfw_InitForVulkan(cimgui::GLFWwindow* window, bool install_callbacks) { return ::ImGui_ImplGlfw_InitForVulkan(reinterpret_cast<::GLFWwindow*>(window), install_callbacks); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplGlfw_InitForOther(cimgui::GLFWwindow* window, bool install_callbacks) { return ::ImGui_ImplGlfw_InitForOther(reinterpret_cast<::GLFWwindow*>(window), install_callbacks); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_Shutdown(void) { ::ImGui_ImplGlfw_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_NewFrame(void) { ::ImGui_ImplGlfw_NewFrame(); } #ifdef __EMSCRIPTEN__ CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_InstallEmscriptenCallbacks(cimgui::GLFWwindow* window, const char* canvas_selector) { ::ImGui_ImplGlfw_InstallEmscriptenCallbacks(reinterpret_cast<::GLFWwindow*>(window), canvas_selector); } #endif // #ifdef __EMSCRIPTEN__ CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_InstallCallbacks(cimgui::GLFWwindow* window) { ::ImGui_ImplGlfw_InstallCallbacks(reinterpret_cast<::GLFWwindow*>(window)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_RestoreCallbacks(cimgui::GLFWwindow* window) { ::ImGui_ImplGlfw_RestoreCallbacks(reinterpret_cast<::GLFWwindow*>(window)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) { ::ImGui_ImplGlfw_SetCallbacksChainForAllWindows(chain_for_all_windows); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_WindowFocusCallback(cimgui::GLFWwindow* window, int focused) { ::ImGui_ImplGlfw_WindowFocusCallback(reinterpret_cast<::GLFWwindow*>(window), focused); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_CursorEnterCallback(cimgui::GLFWwindow* window, int entered) { ::ImGui_ImplGlfw_CursorEnterCallback(reinterpret_cast<::GLFWwindow*>(window), entered); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_CursorPosCallback(cimgui::GLFWwindow* window, double x, double y) { ::ImGui_ImplGlfw_CursorPosCallback(reinterpret_cast<::GLFWwindow*>(window), x, y); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_MouseButtonCallback(cimgui::GLFWwindow* window, int button, int action, int mods) { ::ImGui_ImplGlfw_MouseButtonCallback(reinterpret_cast<::GLFWwindow*>(window), button, action, mods); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_ScrollCallback(cimgui::GLFWwindow* window, double xoffset, double yoffset) { ::ImGui_ImplGlfw_ScrollCallback(reinterpret_cast<::GLFWwindow*>(window), xoffset, yoffset); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_KeyCallback(cimgui::GLFWwindow* window, int key, int scancode, int action, int mods) { ::ImGui_ImplGlfw_KeyCallback(reinterpret_cast<::GLFWwindow*>(window), key, scancode, action, mods); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_CharCallback(cimgui::GLFWwindow* window, unsigned int c) { ::ImGui_ImplGlfw_CharCallback(reinterpret_cast<::GLFWwindow*>(window), c); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_MonitorCallback(cimgui::GLFWmonitor* monitor, int event) { ::ImGui_ImplGlfw_MonitorCallback(reinterpret_cast<::GLFWmonitor*>(monitor), event); } CIMGUI_IMPL_API void cimgui::cImGui_ImplGlfw_Sleep(int milliseconds) { ::ImGui_ImplGlfw_Sleep(milliseconds); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_opengl3_loader.h
//----------------------------------------------------------------------------- // About imgui_impl_opengl3_loader.h: // // We embed our own OpenGL loader to not require user to provide their own or to have to use ours, // which proved to be endless problems for users. // Our loader is custom-generated, based on gl3w but automatically filtered to only include // enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small. // // YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY. // THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE. // // IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions): // IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCLUDING 'imgui_impl_opengl3_loader.h' // IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER. // (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS) // YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT. // BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp // WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT. // // Regenerate with: // python3 gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt // // More info: // https://github.com/dearimgui/gl3w_stripped // https://github.com/ocornut/imgui/issues/4445 //----------------------------------------------------------------------------- /* * This file was generated with gl3w_gen.py, part of imgl3w * (hosted at https://github.com/dearimgui/gl3w_stripped) * * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __gl3w_h_ #define __gl3w_h_ // Adapted from KHR/khrplatform.h to avoid including entire file. #ifndef __khrplatform_h_ typedef float khronos_float_t; typedef signed char khronos_int8_t; typedef unsigned char khronos_uint8_t; typedef signed short int khronos_int16_t; typedef unsigned short int khronos_uint16_t; #ifdef _WIN64 typedef signed long long int khronos_intptr_t; typedef signed long long int khronos_ssize_t; #else typedef signed long int khronos_intptr_t; typedef signed long int khronos_ssize_t; #endif #if defined(_MSC_VER) && !defined(__clang__) typedef signed __int64 khronos_int64_t; typedef unsigned __int64 khronos_uint64_t; #elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100) #include <stdint.h> typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; #else typedef signed long long khronos_int64_t; typedef unsigned long long khronos_uint64_t; #endif #endif // __khrplatform_h_ #ifndef __gl_glcorearb_h_ #define __gl_glcorearb_h_ 1 #ifdef __cplusplus extern "C" { #endif /* ** Copyright 2013-2020 The Khronos Group Inc. ** SPDX-License-Identifier: MIT ** ** This header is generated from the Khronos OpenGL / OpenGL ES XML ** API Registry. The current version of the Registry, generator scripts ** used to make the header, and the header can be found at ** https://github.com/KhronosGroup/OpenGL-Registry */ #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include <windows.h> #endif #ifndef APIENTRY #define APIENTRY #endif #ifndef APIENTRYP #define APIENTRYP APIENTRY * #endif #ifndef GLAPI #define GLAPI extern #endif /* glcorearb.h is for use with OpenGL core profile implementations. ** It should should be placed in the same directory as gl.h and ** included as <GL/glcorearb.h>. ** ** glcorearb.h includes only APIs in the latest OpenGL core profile ** implementation together with APIs in newer ARB extensions which ** can be supported by the core profile. It does not, and never will ** include functionality removed from the core profile, such as ** fixed-function vertex and fragment processing. ** ** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or ** <GL/glext.h> in the same source file. */ /* Generated C header for: * API: gl * Profile: core * Versions considered: .* * Versions emitted: .* * Default extensions included: glcore * Additional extensions included: _nomatch_^ * Extensions removed: _nomatch_^ */ #ifndef GL_VERSION_1_0 typedef void GLvoid; typedef unsigned int GLenum; typedef khronos_float_t GLfloat; typedef int GLint; typedef int GLsizei; typedef unsigned int GLbitfield; typedef double GLdouble; typedef unsigned int GLuint; typedef unsigned char GLboolean; typedef khronos_uint8_t GLubyte; #define GL_COLOR_BUFFER_BIT 0x00004000 #define GL_FALSE 0 #define GL_TRUE 1 #define GL_TRIANGLES 0x0004 #define GL_ONE 1 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 #define GL_FRONT 0x0404 #define GL_BACK 0x0405 #define GL_FRONT_AND_BACK 0x0408 #define GL_POLYGON_MODE 0x0B40 #define GL_CULL_FACE 0x0B44 #define GL_DEPTH_TEST 0x0B71 #define GL_STENCIL_TEST 0x0B90 #define GL_VIEWPORT 0x0BA2 #define GL_BLEND 0x0BE2 #define GL_SCISSOR_BOX 0x0C10 #define GL_SCISSOR_TEST 0x0C11 #define GL_UNPACK_ROW_LENGTH 0x0CF2 #define GL_PACK_ALIGNMENT 0x0D05 #define GL_TEXTURE_2D 0x0DE1 #define GL_UNSIGNED_BYTE 0x1401 #define GL_UNSIGNED_SHORT 0x1403 #define GL_UNSIGNED_INT 0x1405 #define GL_FLOAT 0x1406 #define GL_RGBA 0x1908 #define GL_FILL 0x1B02 #define GL_VENDOR 0x1F00 #define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 #define GL_LINEAR 0x2601 #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode); typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height); typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask); typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap); typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap); typedef void (APIENTRYP PFNGLFLUSHPROC) (void); typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void); typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data); typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name); typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap); typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode); GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height); GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param); GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI void APIENTRY glClear (GLbitfield mask); GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI void APIENTRY glDisable (GLenum cap); GLAPI void APIENTRY glEnable (GLenum cap); GLAPI void APIENTRY glFlush (void); GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param); GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); GLAPI GLenum APIENTRY glGetError (void); GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data); GLAPI const GLubyte *APIENTRY glGetString (GLenum name); GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap); GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height); #endif #endif /* GL_VERSION_1_0 */ #ifndef GL_VERSION_1_1 typedef khronos_float_t GLclampf; typedef double GLclampd; #define GL_TEXTURE_BINDING_2D 0x8069 typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices); typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices); GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture); GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures); #endif #endif /* GL_VERSION_1_1 */ #ifndef GL_VERSION_1_3 #define GL_TEXTURE0 0x84C0 #define GL_ACTIVE_TEXTURE 0x84E0 typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glActiveTexture (GLenum texture); #endif #endif /* GL_VERSION_1_3 */ #ifndef GL_VERSION_1_4 #define GL_BLEND_DST_RGB 0x80C8 #define GL_BLEND_SRC_RGB 0x80C9 #define GL_BLEND_DST_ALPHA 0x80CA #define GL_BLEND_SRC_ALPHA 0x80CB #define GL_FUNC_ADD 0x8006 typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); GLAPI void APIENTRY glBlendEquation (GLenum mode); #endif #endif /* GL_VERSION_1_4 */ #ifndef GL_VERSION_1_5 typedef khronos_ssize_t GLsizeiptr; typedef khronos_intptr_t GLintptr; #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_STREAM_DRAW 0x88E0 typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer); GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); #endif #endif /* GL_VERSION_1_5 */ #ifndef GL_VERSION_2_0 typedef char GLchar; typedef khronos_int16_t GLshort; typedef khronos_int8_t GLbyte; typedef khronos_uint16_t GLushort; #define GL_BLEND_EQUATION_RGB 0x8009 #define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 #define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 #define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 #define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_BLEND_EQUATION_ALPHA 0x883D #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_COMPILE_STATUS 0x8B81 #define GL_LINK_STATUS 0x8B82 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_CURRENT_PROGRAM 0x8B8D #define GL_UPPER_LEFT 0x8CA2 typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader); GLAPI void APIENTRY glCompileShader (GLuint shader); GLAPI GLuint APIENTRY glCreateProgram (void); GLAPI GLuint APIENTRY glCreateShader (GLenum type); GLAPI void APIENTRY glDeleteProgram (GLuint program); GLAPI void APIENTRY glDeleteShader (GLuint shader); GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader); GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index); GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index); GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); GLAPI GLboolean APIENTRY glIsProgram (GLuint program); GLAPI void APIENTRY glLinkProgram (GLuint program); GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); GLAPI void APIENTRY glUseProgram (GLuint program); GLAPI void APIENTRY glUniform1i (GLint location, GLint v0); GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); #endif #endif /* GL_VERSION_2_0 */ #ifndef GL_VERSION_2_1 #define GL_PIXEL_UNPACK_BUFFER 0x88EC #define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF #endif /* GL_VERSION_2_1 */ #ifndef GL_VERSION_3_0 typedef khronos_uint16_t GLhalf; #define GL_MAJOR_VERSION 0x821B #define GL_MINOR_VERSION 0x821C #define GL_NUM_EXTENSIONS 0x821D #define GL_FRAMEBUFFER_SRGB 0x8DB9 #define GL_VERTEX_ARRAY_BINDING 0x85B5 typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data); typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); #ifdef GL_GLEXT_PROTOTYPES GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index); GLAPI void APIENTRY glBindVertexArray (GLuint array); GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); #endif #endif /* GL_VERSION_3_0 */ #ifndef GL_VERSION_3_1 #define GL_VERSION_3_1 1 #define GL_PRIMITIVE_RESTART 0x8F9D #endif /* GL_VERSION_3_1 */ #ifndef GL_VERSION_3_2 #define GL_VERSION_3_2 1 typedef struct __GLsync *GLsync; typedef khronos_uint64_t GLuint64; typedef khronos_int64_t GLint64; #define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 #define GL_CONTEXT_PROFILE_MASK 0x9126 typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); #endif #endif /* GL_VERSION_3_2 */ #ifndef GL_VERSION_3_3 #define GL_VERSION_3_3 1 #define GL_SAMPLER_BINDING 0x8919 typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler); #endif #endif /* GL_VERSION_3_3 */ #ifndef GL_VERSION_4_1 typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data); typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data); #endif /* GL_VERSION_4_1 */ #ifndef GL_VERSION_4_3 typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); #endif /* GL_VERSION_4_3 */ #ifndef GL_VERSION_4_5 #define GL_CLIP_ORIGIN 0x935C typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param); typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); #endif /* GL_VERSION_4_5 */ #ifndef GL_ARB_bindless_texture typedef khronos_uint64_t GLuint64EXT; #endif /* GL_ARB_bindless_texture */ #ifndef GL_ARB_cl_event struct _cl_context; struct _cl_event; #endif /* GL_ARB_cl_event */ #ifndef GL_ARB_clip_control #define GL_ARB_clip_control 1 #endif /* GL_ARB_clip_control */ #ifndef GL_ARB_debug_output typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); #endif /* GL_ARB_debug_output */ #ifndef GL_EXT_EGL_image_storage typedef void *GLeglImageOES; #endif /* GL_EXT_EGL_image_storage */ #ifndef GL_EXT_direct_state_access typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params); typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params); typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params); typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param); #endif /* GL_EXT_direct_state_access */ #ifndef GL_NV_draw_vulkan_image typedef void (APIENTRY *GLVULKANPROCNV)(void); #endif /* GL_NV_draw_vulkan_image */ #ifndef GL_NV_gpu_shader5 typedef khronos_int64_t GLint64EXT; #endif /* GL_NV_gpu_shader5 */ #ifndef GL_NV_vertex_buffer_unified_memory typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result); #endif /* GL_NV_vertex_buffer_unified_memory */ #ifdef __cplusplus } #endif #endif #ifndef GL3W_API #define GL3W_API #endif #ifndef __gl_h_ #define __gl_h_ #endif #ifdef __cplusplus extern "C" { #endif #define GL3W_OK 0 #define GL3W_ERROR_INIT -1 #define GL3W_ERROR_LIBRARY_OPEN -2 #define GL3W_ERROR_OPENGL_VERSION -3 typedef void (*GL3WglProc)(void); typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc); /* gl3w api */ GL3W_API int imgl3wInit(void); GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc); GL3W_API int imgl3wIsSupported(int major, int minor); GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc); /* gl3w internal state */ union ImGL3WProcs { GL3WglProc ptr[59]; struct { PFNGLACTIVETEXTUREPROC ActiveTexture; PFNGLATTACHSHADERPROC AttachShader; PFNGLBINDBUFFERPROC BindBuffer; PFNGLBINDSAMPLERPROC BindSampler; PFNGLBINDTEXTUREPROC BindTexture; PFNGLBINDVERTEXARRAYPROC BindVertexArray; PFNGLBLENDEQUATIONPROC BlendEquation; PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate; PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate; PFNGLBUFFERDATAPROC BufferData; PFNGLBUFFERSUBDATAPROC BufferSubData; PFNGLCLEARPROC Clear; PFNGLCLEARCOLORPROC ClearColor; PFNGLCOMPILESHADERPROC CompileShader; PFNGLCREATEPROGRAMPROC CreateProgram; PFNGLCREATESHADERPROC CreateShader; PFNGLDELETEBUFFERSPROC DeleteBuffers; PFNGLDELETEPROGRAMPROC DeleteProgram; PFNGLDELETESHADERPROC DeleteShader; PFNGLDELETETEXTURESPROC DeleteTextures; PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays; PFNGLDETACHSHADERPROC DetachShader; PFNGLDISABLEPROC Disable; PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray; PFNGLDRAWELEMENTSPROC DrawElements; PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex; PFNGLENABLEPROC Enable; PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray; PFNGLFLUSHPROC Flush; PFNGLGENBUFFERSPROC GenBuffers; PFNGLGENTEXTURESPROC GenTextures; PFNGLGENVERTEXARRAYSPROC GenVertexArrays; PFNGLGETATTRIBLOCATIONPROC GetAttribLocation; PFNGLGETERRORPROC GetError; PFNGLGETINTEGERVPROC GetIntegerv; PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog; PFNGLGETPROGRAMIVPROC GetProgramiv; PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog; PFNGLGETSHADERIVPROC GetShaderiv; PFNGLGETSTRINGPROC GetString; PFNGLGETSTRINGIPROC GetStringi; PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation; PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv; PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv; PFNGLISENABLEDPROC IsEnabled; PFNGLISPROGRAMPROC IsProgram; PFNGLLINKPROGRAMPROC LinkProgram; PFNGLPIXELSTOREIPROC PixelStorei; PFNGLPOLYGONMODEPROC PolygonMode; PFNGLREADPIXELSPROC ReadPixels; PFNGLSCISSORPROC Scissor; PFNGLSHADERSOURCEPROC ShaderSource; PFNGLTEXIMAGE2DPROC TexImage2D; PFNGLTEXPARAMETERIPROC TexParameteri; PFNGLUNIFORM1IPROC Uniform1i; PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv; PFNGLUSEPROGRAMPROC UseProgram; PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer; PFNGLVIEWPORTPROC Viewport; } gl; }; GL3W_API extern union ImGL3WProcs imgl3wProcs; /* OpenGL functions */ #define glActiveTexture imgl3wProcs.gl.ActiveTexture #define glAttachShader imgl3wProcs.gl.AttachShader #define glBindBuffer imgl3wProcs.gl.BindBuffer #define glBindSampler imgl3wProcs.gl.BindSampler #define glBindTexture imgl3wProcs.gl.BindTexture #define glBindVertexArray imgl3wProcs.gl.BindVertexArray #define glBlendEquation imgl3wProcs.gl.BlendEquation #define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate #define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate #define glBufferData imgl3wProcs.gl.BufferData #define glBufferSubData imgl3wProcs.gl.BufferSubData #define glClear imgl3wProcs.gl.Clear #define glClearColor imgl3wProcs.gl.ClearColor #define glCompileShader imgl3wProcs.gl.CompileShader #define glCreateProgram imgl3wProcs.gl.CreateProgram #define glCreateShader imgl3wProcs.gl.CreateShader #define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers #define glDeleteProgram imgl3wProcs.gl.DeleteProgram #define glDeleteShader imgl3wProcs.gl.DeleteShader #define glDeleteTextures imgl3wProcs.gl.DeleteTextures #define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays #define glDetachShader imgl3wProcs.gl.DetachShader #define glDisable imgl3wProcs.gl.Disable #define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray #define glDrawElements imgl3wProcs.gl.DrawElements #define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex #define glEnable imgl3wProcs.gl.Enable #define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray #define glFlush imgl3wProcs.gl.Flush #define glGenBuffers imgl3wProcs.gl.GenBuffers #define glGenTextures imgl3wProcs.gl.GenTextures #define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays #define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation #define glGetError imgl3wProcs.gl.GetError #define glGetIntegerv imgl3wProcs.gl.GetIntegerv #define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog #define glGetProgramiv imgl3wProcs.gl.GetProgramiv #define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog #define glGetShaderiv imgl3wProcs.gl.GetShaderiv #define glGetString imgl3wProcs.gl.GetString #define glGetStringi imgl3wProcs.gl.GetStringi #define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation #define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv #define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv #define glIsEnabled imgl3wProcs.gl.IsEnabled #define glIsProgram imgl3wProcs.gl.IsProgram #define glLinkProgram imgl3wProcs.gl.LinkProgram #define glPixelStorei imgl3wProcs.gl.PixelStorei #define glPolygonMode imgl3wProcs.gl.PolygonMode #define glReadPixels imgl3wProcs.gl.ReadPixels #define glScissor imgl3wProcs.gl.Scissor #define glShaderSource imgl3wProcs.gl.ShaderSource #define glTexImage2D imgl3wProcs.gl.TexImage2D #define glTexParameteri imgl3wProcs.gl.TexParameteri #define glUniform1i imgl3wProcs.gl.Uniform1i #define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv #define glUseProgram imgl3wProcs.gl.UseProgram #define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer #define glViewport imgl3wProcs.gl.Viewport #ifdef __cplusplus } #endif #endif #ifdef IMGL3W_IMPL #ifdef __cplusplus extern "C" { #endif #include <stdlib.h> #define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #if defined(_WIN32) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include <windows.h> static HMODULE libgl; typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR); static GL3WglGetProcAddr wgl_get_proc_address; static int open_libgl(void) { libgl = LoadLibraryA("opengl32.dll"); if (!libgl) return GL3W_ERROR_LIBRARY_OPEN; wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress"); return GL3W_OK; } static void close_libgl(void) { FreeLibrary(libgl); } static GL3WglProc get_proc(const char *proc) { GL3WglProc res; res = (GL3WglProc)wgl_get_proc_address(proc); if (!res) res = (GL3WglProc)GetProcAddress(libgl, proc); return res; } #elif defined(__APPLE__) #include <dlfcn.h> static void *libgl; static int open_libgl(void) { libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL); if (!libgl) return GL3W_ERROR_LIBRARY_OPEN; return GL3W_OK; } static void close_libgl(void) { dlclose(libgl); } static GL3WglProc get_proc(const char *proc) { GL3WglProc res; *(void **)(&res) = dlsym(libgl, proc); return res; } #else #include <dlfcn.h> static void* libgl; // OpenGL library static void* libglx; // GLX library static void* libegl; // EGL library static GL3WGetProcAddressProc gl_get_proc_address; static void close_libgl(void) { if (libgl) { dlclose(libgl); libgl = NULL; } if (libegl) { dlclose(libegl); libegl = NULL; } if (libglx) { dlclose(libglx); libglx = NULL; } } static int is_library_loaded(const char* name, void** lib) { *lib = dlopen(name, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); return *lib != NULL; } static int open_libs(void) { // On Linux we have two APIs to get process addresses: EGL and GLX. // EGL is supported under both X11 and Wayland, whereas GLX is X11-specific. libgl = NULL; libegl = NULL; libglx = NULL; // First check what's already loaded, the windowing library might have // already loaded either EGL or GLX and we want to use the same one. if (is_library_loaded("libEGL.so.1", &libegl) || is_library_loaded("libGLX.so.0", &libglx)) { libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL); if (libgl) return GL3W_OK; else close_libgl(); } if (is_library_loaded("libGL.so", &libgl)) return GL3W_OK; if (is_library_loaded("libGL.so.1", &libgl)) return GL3W_OK; if (is_library_loaded("libGL.so.3", &libgl)) return GL3W_OK; // Neither is already loaded, so we have to load one. Try EGL first // because it is supported under both X11 and Wayland. // Load OpenGL + EGL libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL); libegl = dlopen("libEGL.so.1", RTLD_LAZY | RTLD_LOCAL); if (libgl && libegl) return GL3W_OK; else close_libgl(); // Fall back to legacy libGL, which includes GLX // While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983 libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL); if (!libgl) libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL); if (!libgl) libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL); if (libgl) return GL3W_OK; return GL3W_ERROR_LIBRARY_OPEN; } static int open_libgl(void) { int res = open_libs(); if (res) return res; if (libegl) *(void**)(&gl_get_proc_address) = dlsym(libegl, "eglGetProcAddress"); else if (libglx) *(void**)(&gl_get_proc_address) = dlsym(libglx, "glXGetProcAddressARB"); else *(void**)(&gl_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB"); if (!gl_get_proc_address) { close_libgl(); return GL3W_ERROR_LIBRARY_OPEN; } return GL3W_OK; } static GL3WglProc get_proc(const char* proc) { GL3WglProc res = NULL; // Before EGL version 1.5, eglGetProcAddress doesn't support querying core // functions and may return a dummy function if we try, so try to load the // function from the GL library directly first. if (libegl) *(void**)(&res) = dlsym(libgl, proc); if (!res) res = gl_get_proc_address(proc); if (!libegl && !res) *(void**)(&res) = dlsym(libgl, proc); return res; } #endif static struct { int major, minor; } version; static int parse_version(void) { if (!glGetIntegerv) return GL3W_ERROR_INIT; glGetIntegerv(GL_MAJOR_VERSION, &version.major); glGetIntegerv(GL_MINOR_VERSION, &version.minor); if (version.major == 0 && version.minor == 0) { // Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>" if (const char* gl_version = (const char*)glGetString(GL_VERSION)) sscanf(gl_version, "%d.%d", &version.major, &version.minor); } if (version.major < 2) return GL3W_ERROR_OPENGL_VERSION; return GL3W_OK; } static void load_procs(GL3WGetProcAddressProc proc); int imgl3wInit(void) { int res = open_libgl(); if (res) return res; atexit(close_libgl); return imgl3wInit2(get_proc); } int imgl3wInit2(GL3WGetProcAddressProc proc) { load_procs(proc); return parse_version(); } int imgl3wIsSupported(int major, int minor) { if (major < 2) return 0; if (version.major == major) return version.minor >= minor; return version.major >= major; } GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); } static const char *proc_names[] = { "glActiveTexture", "glAttachShader", "glBindBuffer", "glBindSampler", "glBindTexture", "glBindVertexArray", "glBlendEquation", "glBlendEquationSeparate", "glBlendFuncSeparate", "glBufferData", "glBufferSubData", "glClear", "glClearColor", "glCompileShader", "glCreateProgram", "glCreateShader", "glDeleteBuffers", "glDeleteProgram", "glDeleteShader", "glDeleteTextures", "glDeleteVertexArrays", "glDetachShader", "glDisable", "glDisableVertexAttribArray", "glDrawElements", "glDrawElementsBaseVertex", "glEnable", "glEnableVertexAttribArray", "glFlush", "glGenBuffers", "glGenTextures", "glGenVertexArrays", "glGetAttribLocation", "glGetError", "glGetIntegerv", "glGetProgramInfoLog", "glGetProgramiv", "glGetShaderInfoLog", "glGetShaderiv", "glGetString", "glGetStringi", "glGetUniformLocation", "glGetVertexAttribPointerv", "glGetVertexAttribiv", "glIsEnabled", "glIsProgram", "glLinkProgram", "glPixelStorei", "glPolygonMode", "glReadPixels", "glScissor", "glShaderSource", "glTexImage2D", "glTexParameteri", "glUniform1i", "glUniformMatrix4fv", "glUseProgram", "glVertexAttribPointer", "glViewport", }; GL3W_API union ImGL3WProcs imgl3wProcs; static void load_procs(GL3WGetProcAddressProc proc) { size_t i; for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++) imgl3wProcs.ptr[i] = proc(proc_names[i]); } #ifdef __cplusplus } #endif #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_vulkan.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for Vulkan // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. // See imgui_impl_vulkan.cpp file for details. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering backend in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. #pragma once #ifdef __cplusplus extern "C" { #endif #ifndef IMGUI_DISABLE #include "cimgui.h" // [Configuration] in order to use a custom Vulkan function loader: // (1) You'll need to disable default Vulkan function prototypes. // We provide a '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' convenience configuration flag. // In order to make sure this is visible from the imgui_impl_vulkan.cpp compilation unit: // - Add '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' in your imconfig.h file // - Or as a compilation flag in your build system // - Or uncomment here (not recommended because you'd be modifying imgui sources!) // - Do not simply add it in a .cpp file! // (2) Call ImGui_ImplVulkan_LoadFunctions() before ImGui_ImplVulkan_Init() with your custom function. // If you have no idea what this is, leave it alone! //#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES // Convenience support for Volk // (you can also technically use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().) //#define IMGUI_IMPL_VULKAN_USE_VOLK #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES)&&!defined(VK_NO_PROTOTYPES) #define VK_NO_PROTOTYPES #endif // #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES)&&!defined(VK_NO_PROTOTYPES) #if defined(VK_USE_PLATFORM_WIN32_KHR)&&!defined(NOMINMAX) #define NOMINMAX #endif // #if defined(VK_USE_PLATFORM_WIN32_KHR)&&!defined(NOMINMAX) // Vulkan includes #ifdef IMGUI_IMPL_VULKAN_USE_VOLK #include <volk.h> #else #include <vulkan/vulkan.h> #endif // #ifdef IMGUI_IMPL_VULKAN_USE_VOLK #if defined(VK_VERSION_1_3)|| defined(VK_KHR_dynamic_rendering) #define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #endif // #if defined(VK_VERSION_1_3)|| defined(VK_KHR_dynamic_rendering) // Initialization data, for ImGui_ImplVulkan_Init() // - VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, // and must contain a pool size large enough to hold an ImGui VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptor. // - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. // [Please zero-clear before use!] typedef struct ImGui_ImplVulkan_InitInfo_t { VkInstance Instance; VkPhysicalDevice PhysicalDevice; VkDevice Device; uint32_t QueueFamily; VkQueue Queue; VkDescriptorPool DescriptorPool; // See requirements in note above VkRenderPass RenderPass; // Ignored if using dynamic rendering uint32_t MinImageCount; // >= 2 uint32_t ImageCount; // >= MinImageCount VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT // (Optional) VkPipelineCache PipelineCache; uint32_t Subpass; // (Optional) Dynamic Rendering // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. bool UseDynamicRendering; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; #endif // #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING // (Optional) Allocation, Debugging const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. } ImGui_ImplVulkan_InitInfo; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); CIMGUI_IMPL_API void cImGui_ImplVulkan_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplVulkan_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer); // Implied pipeline = VK_NULL_HANDLE CIMGUI_IMPL_API void cImGui_ImplVulkan_RenderDrawDataEx(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline /* = VK_NULL_HANDLE */); CIMGUI_IMPL_API bool cImGui_ImplVulkan_CreateFontsTexture(void); CIMGUI_IMPL_API void cImGui_ImplVulkan_DestroyFontsTexture(void); CIMGUI_IMPL_API void cImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) // Register a texture (VkDescriptorSet == ImTextureID) // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem // Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. CIMGUI_IMPL_API VkDescriptorSet cImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout); CIMGUI_IMPL_API void cImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set); // Optional: load Vulkan functions with a custom function loader // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES CIMGUI_IMPL_API bool cImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction (*loader_func)(const char* function_name, void* user_data)); // Implied user_data = nullptr CIMGUI_IMPL_API bool cImGui_ImplVulkan_LoadFunctionsEx(PFN_vkVoidFunction (*loader_func)(const char* function_name, void* user_data), void* user_data /* = nullptr */); //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. // 2) the multi-viewport / platform window implementation needs them internally. // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, // but it is too much code to duplicate everywhere so we exceptionally expose them. // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- typedef struct ImGui_ImplVulkanH_Frame_t ImGui_ImplVulkanH_Frame; typedef struct ImGui_ImplVulkanH_Window_t ImGui_ImplVulkanH_Window; // Helpers CIMGUI_IMPL_API void cImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); CIMGUI_IMPL_API void cImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); CIMGUI_IMPL_API VkSurfaceFormatKHR cImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); CIMGUI_IMPL_API VkPresentModeKHR cImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); CIMGUI_IMPL_API int cImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); // Helper structure to hold the data needed by one rendering frame // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) // [Please zero-clear before use!] typedef struct ImGui_ImplVulkanH_Frame_t { VkCommandPool CommandPool; VkCommandBuffer CommandBuffer; VkFence Fence; VkImage Backbuffer; VkImageView BackbufferView; VkFramebuffer Framebuffer; } ImGui_ImplVulkanH_Frame; typedef struct ImGui_ImplVulkanH_FrameSemaphores_t { VkSemaphore ImageAcquiredSemaphore; VkSemaphore RenderCompleteSemaphore; } ImGui_ImplVulkanH_FrameSemaphores; // Helper structure to hold the data needed by one rendering context into one OS window // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) typedef struct ImGui_ImplVulkanH_Window_t { int Width; int Height; VkSwapchainKHR Swapchain; VkSurfaceKHR Surface; VkSurfaceFormatKHR SurfaceFormat; VkPresentModeKHR PresentMode; VkRenderPass RenderPass; VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo bool UseDynamicRendering; bool ClearEnable; VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) ImGui_ImplVulkanH_Frame* Frames; ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; } ImGui_ImplVulkanH_Window; #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_opengl2.h
// dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline) // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in imgui_impl_opengl3.cpp** // 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. #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_NewFrame(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data); // Called by Init/NewFrame/Shutdown IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateFontsTexture(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_win32.cpp
// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // Configuration flags to add in your imconfig file: //#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant. // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. // 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL). // 2023-09-07: Inputs: Added support for keyboard codepage conversion for when application is compiled in MBCS mode and using a non-Unicode window. // 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702) // 2023-02-15: Inputs: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse position over non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162) // 2023-02-02: Inputs: Flipping WM_MOUSEHWHEEL (horizontal mouse-wheel) value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-09-28: Inputs: Convert WM_CHAR values with MultiByteToWideChar() when window class was registered as MBCS (not Unicode). // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). // 2022-01-17: Inputs: always update key mods next and before a key event (not in NewFrame) to fix input queue with very low framerates. // 2022-01-12: Inputs: Update mouse inputs using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API. // 2022-01-12: Inputs: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2021-12-16: Inputs: Fill VK_LCONTROL/VK_RCONTROL/VK_LSHIFT/VK_RSHIFT/VK_LMENU/VK_RMENU for completeness. // 2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages. // 2021-08-02: Inputs: Fixed keyboard modifiers being reported when host window doesn't have focus. // 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using TrackMouseEvent() to receive WM_MOUSELEAVE events). // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-06-08: Fixed ImGui_ImplWin32_EnableDpiAwareness() and ImGui_ImplWin32_GetDpiScaleForMonitor() to handle Windows 8.1/10 features without a manifest (per-monitor DPI, and properly calls SetProcessDpiAwareness() on 8.1). // 2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS). // 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi). // 2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1. // 2021-01-25: Inputs: Dynamically loading XInput DLL. // 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed. // 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs) // 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. // 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT. // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter(). // 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. // 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. // 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application). // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. // 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads). // 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read. // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging. // 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_win32.h" #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <windowsx.h> // GET_X_LPARAM(), GET_Y_LPARAM() #include <tchar.h> #include <dwmapi.h> // Using XInput for gamepad (will load DLL dynamically) #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD #include <xinput.h> typedef DWORD(WINAPI* PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*); typedef DWORD(WINAPI* PFN_XInputGetState)(DWORD, XINPUT_STATE*); #endif // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) #endif #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) #endif struct ImGui_ImplWin32_Data { HWND hWnd; HWND MouseHwnd; int MouseTrackedArea; // 0: not tracked, 1: client are, 2: non-client area int MouseButtonsDown; INT64 Time; INT64 TicksPerSecond; ImGuiMouseCursor LastMouseCursor; UINT32 KeyboardCodePage; #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD bool HasGamepad; bool WantUpdateHasGamepad; HMODULE XInputDLL; PFN_XInputGetCapabilities XInputGetCapabilities; PFN_XInputGetState XInputGetState; #endif ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } // Functions static void ImGui_ImplWin32_UpdateKeyboardCodePage() { // Retrieve keyboard code page, required for handling of non-Unicode Windows. ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); HKL keyboard_layout = ::GetKeyboardLayout(0); LCID keyboard_lcid = MAKELCID(HIWORD(keyboard_layout), SORT_DEFAULT); if (::GetLocaleInfoA(keyboard_lcid, (LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE), (LPSTR)&bd->KeyboardCodePage, sizeof(bd->KeyboardCodePage)) == 0) bd->KeyboardCodePage = CP_ACP; // Fallback to default ANSI code page when fails. } static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); INT64 perf_frequency, perf_counter; if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency)) return false; if (!::QueryPerformanceCounter((LARGE_INTEGER*)&perf_counter)) return false; // Setup backend capabilities flags ImGui_ImplWin32_Data* bd = IM_NEW(ImGui_ImplWin32_Data)(); io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = "imgui_impl_win32"; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->hWnd = (HWND)hwnd; bd->TicksPerSecond = perf_frequency; bd->Time = perf_counter; bd->LastMouseCursor = ImGuiMouseCursor_COUNT; ImGui_ImplWin32_UpdateKeyboardCodePage(); // Set platform dependent data in viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)bd->hWnd; IM_UNUSED(platform_has_own_dc); // Used in 'docking' branch // Dynamically load XInput library #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD bd->WantUpdateHasGamepad = true; const char* xinput_dll_names[] = { "xinput1_4.dll", // Windows 8+ "xinput1_3.dll", // DirectX SDK "xinput9_1_0.dll", // Windows Vista, Windows 7 "xinput1_2.dll", // DirectX SDK "xinput1_1.dll" // DirectX SDK }; for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++) if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n])) { bd->XInputDLL = dll; bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities"); bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState"); break; } #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD return true; } IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd) { return ImGui_ImplWin32_InitEx(hwnd, false); } IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd) { // OpenGL needs CS_OWNDC return ImGui_ImplWin32_InitEx(hwnd, true); } void ImGui_ImplWin32_Shutdown() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); // Unload XInput library #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD if (bd->XInputDLL) ::FreeLibrary(bd->XInputDLL); #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); IM_DELETE(bd); } static bool ImGui_ImplWin32_UpdateMouseCursor() { ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return false; ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor ::SetCursor(nullptr); } else { // Show OS mouse cursor LPTSTR win32_cursor = IDC_ARROW; switch (imgui_cursor) { case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break; case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break; case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break; case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break; case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break; case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break; case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; } ::SetCursor(::LoadCursor(nullptr, win32_cursor)); } return true; } static bool IsVkDown(int vk) { return (::GetKeyState(vk) & 0x8000) != 0; } static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1) { ImGuiIO& io = ImGui::GetIO(); io.AddKeyEvent(key, down); io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code) IM_UNUSED(native_scancode); } static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds() { // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one. if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT)) ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT); if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT)) ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT); // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW). if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN)) ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN); if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN)) ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN); } static void ImGui_ImplWin32_UpdateKeyModifiers() { ImGuiIO& io = ImGui::GetIO(); io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL)); io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT)); io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU)); io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_LWIN) || IsVkDown(VK_RWIN)); } static void ImGui_ImplWin32_UpdateMouseData() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(bd->hWnd != 0); HWND focused_window = ::GetForegroundWindow(); const bool is_app_focused = (focused_window == bd->hWnd); if (is_app_focused) { // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) if (io.WantSetMousePos) { POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y }; if (::ClientToScreen(bd->hWnd, &pos)) ::SetCursorPos(pos.x, pos.y); } // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured) // This also fills a short gap when clicking non-client area: WM_NCMOUSELEAVE -> modal OS move -> gap -> WM_NCMOUSEMOVE if (!io.WantSetMousePos && bd->MouseTrackedArea == 0) { POINT pos; if (::GetCursorPos(&pos) && ::ScreenToClient(bd->hWnd, &pos)) io.AddMousePosEvent((float)pos.x, (float)pos.y); } } } // Gamepad navigation mapping static void ImGui_ImplWin32_UpdateGamepads() { #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD ImGuiIO& io = ImGui::GetIO(); ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); //if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. // return; // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow. // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE. if (bd->WantUpdateHasGamepad) { XINPUT_CAPABILITIES caps = {}; bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false; bd->WantUpdateHasGamepad = false; } io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; XINPUT_STATE xinput_state; XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad; if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) return; io.BackendFlags |= ImGuiBackendFlags_HasGamepad; #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); } #define MAP_ANALOG(KEY_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); io.AddKeyAnalogEvent(KEY_NO, vn > 0.10f, IM_SATURATE(vn)); } MAP_BUTTON(ImGuiKey_GamepadStart, XINPUT_GAMEPAD_START); MAP_BUTTON(ImGuiKey_GamepadBack, XINPUT_GAMEPAD_BACK); MAP_BUTTON(ImGuiKey_GamepadFaceLeft, XINPUT_GAMEPAD_X); MAP_BUTTON(ImGuiKey_GamepadFaceRight, XINPUT_GAMEPAD_B); MAP_BUTTON(ImGuiKey_GamepadFaceUp, XINPUT_GAMEPAD_Y); MAP_BUTTON(ImGuiKey_GamepadFaceDown, XINPUT_GAMEPAD_A); MAP_BUTTON(ImGuiKey_GamepadDpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); MAP_BUTTON(ImGuiKey_GamepadDpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); MAP_BUTTON(ImGuiKey_GamepadDpadUp, XINPUT_GAMEPAD_DPAD_UP); MAP_BUTTON(ImGuiKey_GamepadDpadDown, XINPUT_GAMEPAD_DPAD_DOWN); MAP_BUTTON(ImGuiKey_GamepadL1, XINPUT_GAMEPAD_LEFT_SHOULDER); MAP_BUTTON(ImGuiKey_GamepadR1, XINPUT_GAMEPAD_RIGHT_SHOULDER); MAP_ANALOG(ImGuiKey_GamepadL2, gamepad.bLeftTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); MAP_ANALOG(ImGuiKey_GamepadR2, gamepad.bRightTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); MAP_BUTTON(ImGuiKey_GamepadL3, XINPUT_GAMEPAD_LEFT_THUMB); MAP_BUTTON(ImGuiKey_GamepadR3, XINPUT_GAMEPAD_RIGHT_THUMB); MAP_ANALOG(ImGuiKey_GamepadLStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); MAP_ANALOG(ImGuiKey_GamepadLStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); MAP_ANALOG(ImGuiKey_GamepadLStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); MAP_ANALOG(ImGuiKey_GamepadLStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); MAP_ANALOG(ImGuiKey_GamepadRStickLeft, gamepad.sThumbRX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); MAP_ANALOG(ImGuiKey_GamepadRStickRight, gamepad.sThumbRX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); MAP_ANALOG(ImGuiKey_GamepadRStickUp, gamepad.sThumbRY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); MAP_ANALOG(ImGuiKey_GamepadRStickDown, gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); #undef MAP_BUTTON #undef MAP_ANALOG #endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD } void ImGui_ImplWin32_NewFrame() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized? Did you call ImGui_ImplWin32_Init()?"); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) RECT rect = { 0, 0, 0, 0 }; ::GetClientRect(bd->hWnd, &rect); io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Setup time step INT64 current_time = 0; ::QueryPerformanceCounter((LARGE_INTEGER*)&current_time); io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond; bd->Time = current_time; // Update OS mouse position ImGui_ImplWin32_UpdateMouseData(); // Process workarounds for known Windows key handling issues ImGui_ImplWin32_ProcessKeyEventsWorkarounds(); // Update OS mouse cursor with the cursor requested by imgui ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); if (bd->LastMouseCursor != mouse_cursor) { bd->LastMouseCursor = mouse_cursor; ImGui_ImplWin32_UpdateMouseCursor(); } // Update game controllers (if enabled and available) ImGui_ImplWin32_UpdateGamepads(); } // There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED, we assign it an arbitrary value to make code more readable (VK_ codes go up to 255) #define IM_VK_KEYPAD_ENTER (VK_RETURN + 256) // Map VK_xxx to ImGuiKey_xxx. static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam) { switch (wParam) { case VK_TAB: return ImGuiKey_Tab; case VK_LEFT: return ImGuiKey_LeftArrow; case VK_RIGHT: return ImGuiKey_RightArrow; case VK_UP: return ImGuiKey_UpArrow; case VK_DOWN: return ImGuiKey_DownArrow; case VK_PRIOR: return ImGuiKey_PageUp; case VK_NEXT: return ImGuiKey_PageDown; case VK_HOME: return ImGuiKey_Home; case VK_END: return ImGuiKey_End; case VK_INSERT: return ImGuiKey_Insert; case VK_DELETE: return ImGuiKey_Delete; case VK_BACK: return ImGuiKey_Backspace; case VK_SPACE: return ImGuiKey_Space; case VK_RETURN: return ImGuiKey_Enter; case VK_ESCAPE: return ImGuiKey_Escape; case VK_OEM_7: return ImGuiKey_Apostrophe; case VK_OEM_COMMA: return ImGuiKey_Comma; case VK_OEM_MINUS: return ImGuiKey_Minus; case VK_OEM_PERIOD: return ImGuiKey_Period; case VK_OEM_2: return ImGuiKey_Slash; case VK_OEM_1: return ImGuiKey_Semicolon; case VK_OEM_PLUS: return ImGuiKey_Equal; case VK_OEM_4: return ImGuiKey_LeftBracket; case VK_OEM_5: return ImGuiKey_Backslash; case VK_OEM_6: return ImGuiKey_RightBracket; case VK_OEM_3: return ImGuiKey_GraveAccent; case VK_CAPITAL: return ImGuiKey_CapsLock; case VK_SCROLL: return ImGuiKey_ScrollLock; case VK_NUMLOCK: return ImGuiKey_NumLock; case VK_SNAPSHOT: return ImGuiKey_PrintScreen; case VK_PAUSE: return ImGuiKey_Pause; case VK_NUMPAD0: return ImGuiKey_Keypad0; case VK_NUMPAD1: return ImGuiKey_Keypad1; case VK_NUMPAD2: return ImGuiKey_Keypad2; case VK_NUMPAD3: return ImGuiKey_Keypad3; case VK_NUMPAD4: return ImGuiKey_Keypad4; case VK_NUMPAD5: return ImGuiKey_Keypad5; case VK_NUMPAD6: return ImGuiKey_Keypad6; case VK_NUMPAD7: return ImGuiKey_Keypad7; case VK_NUMPAD8: return ImGuiKey_Keypad8; case VK_NUMPAD9: return ImGuiKey_Keypad9; case VK_DECIMAL: return ImGuiKey_KeypadDecimal; case VK_DIVIDE: return ImGuiKey_KeypadDivide; case VK_MULTIPLY: return ImGuiKey_KeypadMultiply; case VK_SUBTRACT: return ImGuiKey_KeypadSubtract; case VK_ADD: return ImGuiKey_KeypadAdd; case IM_VK_KEYPAD_ENTER: return ImGuiKey_KeypadEnter; case VK_LSHIFT: return ImGuiKey_LeftShift; case VK_LCONTROL: return ImGuiKey_LeftCtrl; case VK_LMENU: return ImGuiKey_LeftAlt; case VK_LWIN: return ImGuiKey_LeftSuper; case VK_RSHIFT: return ImGuiKey_RightShift; case VK_RCONTROL: return ImGuiKey_RightCtrl; case VK_RMENU: return ImGuiKey_RightAlt; case VK_RWIN: return ImGuiKey_RightSuper; case VK_APPS: return ImGuiKey_Menu; case '0': return ImGuiKey_0; case '1': return ImGuiKey_1; case '2': return ImGuiKey_2; case '3': return ImGuiKey_3; case '4': return ImGuiKey_4; case '5': return ImGuiKey_5; case '6': return ImGuiKey_6; case '7': return ImGuiKey_7; case '8': return ImGuiKey_8; case '9': return ImGuiKey_9; case 'A': return ImGuiKey_A; case 'B': return ImGuiKey_B; case 'C': return ImGuiKey_C; case 'D': return ImGuiKey_D; case 'E': return ImGuiKey_E; case 'F': return ImGuiKey_F; case 'G': return ImGuiKey_G; case 'H': return ImGuiKey_H; case 'I': return ImGuiKey_I; case 'J': return ImGuiKey_J; case 'K': return ImGuiKey_K; case 'L': return ImGuiKey_L; case 'M': return ImGuiKey_M; case 'N': return ImGuiKey_N; case 'O': return ImGuiKey_O; case 'P': return ImGuiKey_P; case 'Q': return ImGuiKey_Q; case 'R': return ImGuiKey_R; case 'S': return ImGuiKey_S; case 'T': return ImGuiKey_T; case 'U': return ImGuiKey_U; case 'V': return ImGuiKey_V; case 'W': return ImGuiKey_W; case 'X': return ImGuiKey_X; case 'Y': return ImGuiKey_Y; case 'Z': return ImGuiKey_Z; case VK_F1: return ImGuiKey_F1; case VK_F2: return ImGuiKey_F2; case VK_F3: return ImGuiKey_F3; case VK_F4: return ImGuiKey_F4; case VK_F5: return ImGuiKey_F5; case VK_F6: return ImGuiKey_F6; case VK_F7: return ImGuiKey_F7; case VK_F8: return ImGuiKey_F8; case VK_F9: return ImGuiKey_F9; case VK_F10: return ImGuiKey_F10; case VK_F11: return ImGuiKey_F11; case VK_F12: return ImGuiKey_F12; case VK_F13: return ImGuiKey_F13; case VK_F14: return ImGuiKey_F14; case VK_F15: return ImGuiKey_F15; case VK_F16: return ImGuiKey_F16; case VK_F17: return ImGuiKey_F17; case VK_F18: return ImGuiKey_F18; case VK_F19: return ImGuiKey_F19; case VK_F20: return ImGuiKey_F20; case VK_F21: return ImGuiKey_F21; case VK_F22: return ImGuiKey_F22; case VK_F23: return ImGuiKey_F23; case VK_F24: return ImGuiKey_F24; case VK_BROWSER_BACK: return ImGuiKey_AppBack; case VK_BROWSER_FORWARD: return ImGuiKey_AppForward; default: return ImGuiKey_None; } } // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. #ifndef WM_MOUSEHWHEEL #define WM_MOUSEHWHEEL 0x020E #endif #ifndef DBT_DEVNODES_CHANGED #define DBT_DEVNODES_CHANGED 0x0007 #endif // Win32 message handler (process Win32 mouse/keyboard inputs, etc.) // Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. // When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates 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. #if 0 // Copy this line into your .cpp file to forward declare the function. extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); #endif // See https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages // Prefer to call this at the top of the message handler to avoid the possibility of other Win32 calls interfering with this. static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() { LPARAM extra_info = ::GetMessageExtraInfo(); if ((extra_info & 0xFFFFFF80) == 0xFF515700) return ImGuiMouseSource_Pen; if ((extra_info & 0xFFFFFF80) == 0xFF515780) return ImGuiMouseSource_TouchScreen; return ImGuiMouseSource_Mouse; } IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { // Most backends don't have silent checks like this one, but we need it because WndProc are called early in CreateWindow(). // We silently allow both context or just only backend data to be nullptr. ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); if (bd == nullptr) return 0; ImGuiIO& io = ImGui::GetIO(); switch (msg) { case WM_MOUSEMOVE: case WM_NCMOUSEMOVE: { // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); const int area = (msg == WM_MOUSEMOVE) ? 1 : 2; bd->MouseHwnd = hwnd; if (bd->MouseTrackedArea != area) { TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 }; TRACKMOUSEEVENT tme_track = { sizeof(tme_track), (DWORD)((area == 2) ? (TME_LEAVE | TME_NONCLIENT) : TME_LEAVE), hwnd, 0 }; if (bd->MouseTrackedArea != 0) ::TrackMouseEvent(&tme_cancel); ::TrackMouseEvent(&tme_track); bd->MouseTrackedArea = area; } POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) }; if (msg == WM_NCMOUSEMOVE && ::ScreenToClient(hwnd, &mouse_pos) == FALSE) // WM_NCMOUSEMOVE are provided in absolute coordinates. return 0; io.AddMouseSourceEvent(mouse_source); io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); return 0; } case WM_MOUSELEAVE: case WM_NCMOUSELEAVE: { const int area = (msg == WM_MOUSELEAVE) ? 1 : 2; if (bd->MouseTrackedArea == area) { if (bd->MouseHwnd == hwnd) bd->MouseHwnd = nullptr; bd->MouseTrackedArea = 0; io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); } return 0; } case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: { ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); 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 (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr) ::SetCapture(hwnd); bd->MouseButtonsDown |= 1 << button; io.AddMouseSourceEvent(mouse_source); io.AddMouseButtonEvent(button, true); return 0; } case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_XBUTTONUP: { ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); int button = 0; if (msg == WM_LBUTTONUP) { button = 0; } if (msg == WM_RBUTTONUP) { button = 1; } if (msg == WM_MBUTTONUP) { button = 2; } if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } bd->MouseButtonsDown &= ~(1 << button); if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd) ::ReleaseCapture(); io.AddMouseSourceEvent(mouse_source); io.AddMouseButtonEvent(button, false); return 0; } case WM_MOUSEWHEEL: io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA); return 0; case WM_MOUSEHWHEEL: io.AddMouseWheelEvent(-(float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f); return 0; case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: { const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); if (wParam < 256) { // Submit modifiers ImGui_ImplWin32_UpdateKeyModifiers(); // Obtain virtual key code // (keypad enter doesn't have its own... VK_RETURN with KF_EXTENDED flag means keypad enter, see IM_VK_KEYPAD_ENTER definition for details, it is mapped to ImGuiKey_KeyPadEnter.) int vk = (int)wParam; if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) vk = IM_VK_KEYPAD_ENTER; const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk); const int scancode = (int)LOBYTE(HIWORD(lParam)); // Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event. if (key == ImGuiKey_PrintScreen && !is_key_down) ImGui_ImplWin32_AddKeyEvent(key, true, vk, scancode); // Submit key event if (key != ImGuiKey_None) ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode); // Submit individual left/right modifier events if (vk == VK_SHIFT) { // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds() if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); } if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); } } else if (vk == VK_CONTROL) { if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); } if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); } } else if (vk == VK_MENU) { if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); } if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); } } } return 0; } case WM_SETFOCUS: case WM_KILLFOCUS: io.AddFocusEvent(msg == WM_SETFOCUS); return 0; case WM_INPUTLANGCHANGE: ImGui_ImplWin32_UpdateKeyboardCodePage(); return 0; case WM_CHAR: if (::IsWindowUnicode(hwnd)) { // You can also use ToAscii()+GetKeyboardState() to retrieve characters. if (wParam > 0 && wParam < 0x10000) io.AddInputCharacterUTF16((unsigned short)wParam); } else { wchar_t wch = 0; ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1); io.AddInputCharacter(wch); } return 0; case WM_SETCURSOR: // This is required to restore cursor when transitioning from e.g resize borders to client area. if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) return 1; return 0; case WM_DEVICECHANGE: #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD if ((UINT)wParam == DBT_DEVNODES_CHANGED) bd->WantUpdateHasGamepad = true; #endif return 0; } return 0; } //-------------------------------------------------------------------------------------------------------- // DPI-related helpers (optional) //-------------------------------------------------------------------------------------------------------- // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. //--------------------------------------------------------------------------------------------------------- // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable. // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically. // If you are trying to implement your own backend for your own engine, you may ignore that noise. //--------------------------------------------------------------------------------------------------------- // Perform our own check with RtlVerifyVersionInfo() instead of using functions from <VersionHelpers.h> as they // require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200 static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) { typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG); static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr; if (RtlVerifyVersionInfoFn == nullptr) if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll")) RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); if (RtlVerifyVersionInfoFn == nullptr) return FALSE; RTL_OSVERSIONINFOEXW versionInfo = { }; ULONGLONG conditionMask = 0; versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); versionInfo.dwMajorVersion = major; versionInfo.dwMinorVersion = minor; VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE; } #define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA #define _IsWindows8OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8 #define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE #define _IsWindows10OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10 #ifndef DPI_ENUMS_DECLARED typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS; typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE; #endif #ifndef _DPI_AWARENESS_CONTEXTS_ DECLARE_HANDLE(DPI_AWARENESS_CONTEXT); #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3 #endif #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4 #endif typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+ typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+ typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update) // Helper function to enable DPI awareness without setting up a manifest void ImGui_ImplWin32_EnableDpiAwareness() { if (_IsWindows10OrGreater()) { static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext")) { SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); return; } } if (_IsWindows8Point1OrGreater()) { static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness")) { SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE); return; } } #if _WIN32_WINNT >= 0x0600 ::SetProcessDPIAware(); #endif } #if defined(_MSC_VER) && !defined(NOGDI) #pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32' #endif float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { UINT xdpi = 96, ydpi = 96; if (_IsWindows8Point1OrGreater()) { static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr; if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr) GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"); if (GetDpiForMonitorFn != nullptr) { GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! return xdpi / 96.0f; } } #ifndef NOGDI const HDC dc = ::GetDC(nullptr); xdpi = ::GetDeviceCaps(dc, LOGPIXELSX); ydpi = ::GetDeviceCaps(dc, LOGPIXELSY); IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! ::ReleaseDC(nullptr, dc); #endif return xdpi / 96.0f; } float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) { HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST); return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); } //--------------------------------------------------------------------------------------------------------- // Transparency related helpers (optional) //-------------------------------------------------------------------------------------------------------- #if defined(_MSC_VER) #pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi' #endif // [experimental] // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW) void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) { if (!_IsWindowsVistaOrGreater()) return; BOOL composition; if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition) return; BOOL opaque; DWORD color; if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque)) { HRGN region = ::CreateRectRgn(0, 0, -1, -1); DWM_BLURBEHIND bb = {}; bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION; bb.hRgnBlur = region; bb.fEnable = TRUE; ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); ::DeleteObject(region); } else { DWM_BLURBEHIND bb = {}; bb.dwFlags = DWM_BB_ENABLE; ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); } } //--------------------------------------------------------------------------------------------------------- #if defined(__GNUC__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdl3.cpp
// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807) // 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801) // 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794) // 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762). // 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea(). // 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures. // 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents. // 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames. // 2024-05-15: Update for SDL3 api changes: SDLK_ renames. // 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME. // 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode(). // 2023-11-13: Updated for recent SDL3 API changes. // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. // 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391) // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) // 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) // 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_sdl3.h" // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif // SDL #include <SDL3/SDL.h> #if defined(__APPLE__) #include <TargetConditionals.h> #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #endif #if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 #else #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 #endif // FIXME-LEGACY: remove when SDL 3.1.3 preview is released. #ifndef SDLK_APOSTROPHE #define SDLK_APOSTROPHE SDLK_QUOTE #endif #ifndef SDLK_GRAVE #define SDLK_GRAVE SDLK_BACKQUOTE #endif // SDL Data struct ImGui_ImplSDL3_Data { SDL_Window* Window; SDL_WindowID WindowID; SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; // IME handling SDL_Window* ImeWindow; // Mouse handling Uint32 MouseWindowID; int MouseButtonsDown; SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; SDL_Cursor* MouseLastCursor; int MousePendingLeaveFrame; bool MouseCanUseGlobalState; // Gamepad handling ImVector<SDL_Gamepad*> Gamepads; ImGui_ImplSDL3_GamepadMode GamepadMode; bool WantUpdateGamepadsList; ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } // Functions static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); const char* sdl_clipboard_text = SDL_GetClipboardText(); bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : NULL; return bd->ClipboardTextData; } static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text) { SDL_SetClipboardText(text); } static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle; SDL_Window* window = SDL_GetWindowFromID(window_id); if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != NULL) { SDL_StopTextInput(bd->ImeWindow); bd->ImeWindow = nullptr; } if (data->WantVisible) { SDL_Rect r; r.x = (int)data->InputPos.x; r.y = (int)data->InputPos.y; r.w = 1; r.h = (int)data->InputLineHeight; SDL_SetTextInputArea(window, &r, 0); SDL_StartTextInput(window); bd->ImeWindow = window; } } static ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) { // Keypad doesn't have individual key values in SDL3 switch (scancode) { case SDL_SCANCODE_KP_0: return ImGuiKey_Keypad0; case SDL_SCANCODE_KP_1: return ImGuiKey_Keypad1; case SDL_SCANCODE_KP_2: return ImGuiKey_Keypad2; case SDL_SCANCODE_KP_3: return ImGuiKey_Keypad3; case SDL_SCANCODE_KP_4: return ImGuiKey_Keypad4; case SDL_SCANCODE_KP_5: return ImGuiKey_Keypad5; case SDL_SCANCODE_KP_6: return ImGuiKey_Keypad6; case SDL_SCANCODE_KP_7: return ImGuiKey_Keypad7; case SDL_SCANCODE_KP_8: return ImGuiKey_Keypad8; case SDL_SCANCODE_KP_9: return ImGuiKey_Keypad9; case SDL_SCANCODE_KP_PERIOD: return ImGuiKey_KeypadDecimal; case SDL_SCANCODE_KP_DIVIDE: return ImGuiKey_KeypadDivide; case SDL_SCANCODE_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; case SDL_SCANCODE_KP_MINUS: return ImGuiKey_KeypadSubtract; case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd; case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter; case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual; default: break; } switch (keycode) { case SDLK_TAB: return ImGuiKey_Tab; case SDLK_LEFT: return ImGuiKey_LeftArrow; case SDLK_RIGHT: return ImGuiKey_RightArrow; case SDLK_UP: return ImGuiKey_UpArrow; case SDLK_DOWN: return ImGuiKey_DownArrow; case SDLK_PAGEUP: return ImGuiKey_PageUp; case SDLK_PAGEDOWN: return ImGuiKey_PageDown; case SDLK_HOME: return ImGuiKey_Home; case SDLK_END: return ImGuiKey_End; case SDLK_INSERT: return ImGuiKey_Insert; case SDLK_DELETE: return ImGuiKey_Delete; case SDLK_BACKSPACE: return ImGuiKey_Backspace; case SDLK_SPACE: return ImGuiKey_Space; case SDLK_RETURN: return ImGuiKey_Enter; case SDLK_ESCAPE: return ImGuiKey_Escape; case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe; case SDLK_COMMA: return ImGuiKey_Comma; case SDLK_MINUS: return ImGuiKey_Minus; case SDLK_PERIOD: return ImGuiKey_Period; case SDLK_SLASH: return ImGuiKey_Slash; case SDLK_SEMICOLON: return ImGuiKey_Semicolon; case SDLK_EQUALS: return ImGuiKey_Equal; case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; case SDLK_BACKSLASH: return ImGuiKey_Backslash; case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; case SDLK_GRAVE: return ImGuiKey_GraveAccent; case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; case SDLK_PAUSE: return ImGuiKey_Pause; case SDLK_LCTRL: return ImGuiKey_LeftCtrl; case SDLK_LSHIFT: return ImGuiKey_LeftShift; case SDLK_LALT: return ImGuiKey_LeftAlt; case SDLK_LGUI: return ImGuiKey_LeftSuper; case SDLK_RCTRL: return ImGuiKey_RightCtrl; case SDLK_RSHIFT: return ImGuiKey_RightShift; case SDLK_RALT: return ImGuiKey_RightAlt; case SDLK_RGUI: return ImGuiKey_RightSuper; case SDLK_APPLICATION: return ImGuiKey_Menu; case SDLK_0: return ImGuiKey_0; case SDLK_1: return ImGuiKey_1; case SDLK_2: return ImGuiKey_2; case SDLK_3: return ImGuiKey_3; case SDLK_4: return ImGuiKey_4; case SDLK_5: return ImGuiKey_5; case SDLK_6: return ImGuiKey_6; case SDLK_7: return ImGuiKey_7; case SDLK_8: return ImGuiKey_8; case SDLK_9: return ImGuiKey_9; case SDLK_A: return ImGuiKey_A; case SDLK_B: return ImGuiKey_B; case SDLK_C: return ImGuiKey_C; case SDLK_D: return ImGuiKey_D; case SDLK_E: return ImGuiKey_E; case SDLK_F: return ImGuiKey_F; case SDLK_G: return ImGuiKey_G; case SDLK_H: return ImGuiKey_H; case SDLK_I: return ImGuiKey_I; case SDLK_J: return ImGuiKey_J; case SDLK_K: return ImGuiKey_K; case SDLK_L: return ImGuiKey_L; case SDLK_M: return ImGuiKey_M; case SDLK_N: return ImGuiKey_N; case SDLK_O: return ImGuiKey_O; case SDLK_P: return ImGuiKey_P; case SDLK_Q: return ImGuiKey_Q; case SDLK_R: return ImGuiKey_R; case SDLK_S: return ImGuiKey_S; case SDLK_T: return ImGuiKey_T; case SDLK_U: return ImGuiKey_U; case SDLK_V: return ImGuiKey_V; case SDLK_W: return ImGuiKey_W; case SDLK_X: return ImGuiKey_X; case SDLK_Y: return ImGuiKey_Y; case SDLK_Z: return ImGuiKey_Z; case SDLK_F1: return ImGuiKey_F1; case SDLK_F2: return ImGuiKey_F2; case SDLK_F3: return ImGuiKey_F3; case SDLK_F4: return ImGuiKey_F4; case SDLK_F5: return ImGuiKey_F5; case SDLK_F6: return ImGuiKey_F6; case SDLK_F7: return ImGuiKey_F7; case SDLK_F8: return ImGuiKey_F8; case SDLK_F9: return ImGuiKey_F9; case SDLK_F10: return ImGuiKey_F10; case SDLK_F11: return ImGuiKey_F11; case SDLK_F12: return ImGuiKey_F12; case SDLK_F13: return ImGuiKey_F13; case SDLK_F14: return ImGuiKey_F14; case SDLK_F15: return ImGuiKey_F15; case SDLK_F16: return ImGuiKey_F16; case SDLK_F17: return ImGuiKey_F17; case SDLK_F18: return ImGuiKey_F18; case SDLK_F19: return ImGuiKey_F19; case SDLK_F20: return ImGuiKey_F20; case SDLK_F21: return ImGuiKey_F21; case SDLK_F22: return ImGuiKey_F22; case SDLK_F23: return ImGuiKey_F23; case SDLK_F24: return ImGuiKey_F24; case SDLK_AC_BACK: return ImGuiKey_AppBack; case SDLK_AC_FORWARD: return ImGuiKey_AppForward; default: break; } return ImGuiKey_None; } static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) { ImGuiIO& io = ImGui::GetIO(); io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & SDL_KMOD_CTRL) != 0); io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & SDL_KMOD_SHIFT) != 0); io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & SDL_KMOD_ALT) != 0); io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0); } static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL; } // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. // If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?"); ImGuiIO& io = ImGui::GetIO(); switch (event->type) { case SDL_EVENT_MOUSE_MOTION: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == NULL) return false; ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); return true; } case SDL_EVENT_MOUSE_WHEEL: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == NULL) return false; //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); float wheel_x = -event->wheel.x; float wheel_y = event->wheel.y; #ifdef __EMSCRIPTEN__ wheel_x /= 100.0f; #endif io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMouseWheelEvent(wheel_x, wheel_y); return true; } case SDL_EVENT_MOUSE_BUTTON_DOWN: case SDL_EVENT_MOUSE_BUTTON_UP: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == NULL) return false; int mouse_button = -1; if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; } if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; } if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; } if (mouse_button == -1) break; io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMouseButtonEvent(mouse_button, (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN)); bd->MouseButtonsDown = (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button)); return true; } case SDL_EVENT_TEXT_INPUT: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == NULL) return false; io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == NULL) return false; //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod); ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod); ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode); io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. return true; } case SDL_EVENT_WINDOW_MOUSE_ENTER: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) return false; bd->MouseWindowID = event->window.windowID; bd->MousePendingLeaveFrame = 0; return true; } // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details. // FIXME: Unconfirmed whether this is still needed with SDL3. case SDL_EVENT_WINDOW_MOUSE_LEAVE: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) return false; bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1; return true; } case SDL_EVENT_WINDOW_FOCUS_GAINED: case SDL_EVENT_WINDOW_FOCUS_LOST: { if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == NULL) return false; io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED); return true; } case SDL_EVENT_GAMEPAD_ADDED: case SDL_EVENT_GAMEPAD_REMOVED: { bd->WantUpdateGamepadsList = true; return true; } } return false; } static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window) { viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(window); viewport->PlatformHandleRaw = nullptr; #if defined(_WIN32) && !defined(__WINRT__) viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr); #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr); #endif } static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_UNUSED(sdl_gl_context); // Unused in this branch // Check and store if we are on a SDL backend that supports global mouse position // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) bool mouse_can_use_global_state = false; #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE const char* sdl_backend = SDL_GetCurrentVideoDriver(); const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) mouse_can_use_global_state = true; #endif // Setup backend capabilities flags ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)(); io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = "imgui_impl_sdl3"; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Window = window; bd->WindowID = SDL_GetWindowID(window); bd->Renderer = renderer; bd->MouseCanUseGlobalState = mouse_can_use_global_state; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData; // Gamepad handling bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; bd->WantUpdateGamepadsList = true; // Load mouse cursors bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT); bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE); bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE); bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE); bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE); bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE); bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED); // Set platform dependent data in viewport // Our mouse update function expect PlatformHandle to be filled for the main viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window); // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: // you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED) #ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); #endif // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710) #ifdef SDL_HINT_MOUSE_AUTO_CAPTURE SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); #endif return true; } bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) { IM_UNUSED(sdl_gl_context); // Viewport branch will need this. return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context); } bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window) { return ImGui_ImplSDL3_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window) { #if !defined(_WIN32) IM_ASSERT(0 && "Unsupported"); #endif return ImGui_ImplSDL3_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window) { return ImGui_ImplSDL3_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) { return ImGui_ImplSDL3_Init(window, renderer, nullptr); } bool ImGui_ImplSDL3_InitForOther(SDL_Window* window) { return ImGui_ImplSDL3_Init(window, nullptr, nullptr); } static void ImGui_ImplSDL3_CloseGamepads(); void ImGui_ImplSDL3_Shutdown() { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) SDL_DestroyCursor(bd->MouseCursors[cursor_n]); ImGui_ImplSDL3_CloseGamepads(); io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); IM_DELETE(bd); } static void ImGui_ImplSDL3_UpdateMouseData() { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE); SDL_Window* focused_window = SDL_GetKeyboardFocus(); const bool is_app_focused = (bd->Window == focused_window); #else SDL_Window* focused_window = bd->Window; const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only #endif if (is_app_focused) { // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) if (io.WantSetMousePos) SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); // (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) { // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) float mouse_x_global, mouse_y_global; int window_x, window_y; SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); SDL_GetWindowPosition(focused_window, &window_x, &window_y); io.AddMousePosEvent(mouse_x_global - window_x, mouse_y_global - window_y); } } } static void ImGui_ImplSDL3_UpdateMouseCursor() { ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return; ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor SDL_HideCursor(); } else { // Show OS mouse cursor SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; if (bd->MouseLastCursor != expected_cursor) { SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) bd->MouseLastCursor = expected_cursor; } SDL_ShowCursor(); } } static void ImGui_ImplSDL3_CloseGamepads() { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) for (SDL_Gamepad* gamepad : bd->Gamepads) SDL_CloseGamepad(gamepad); bd->Gamepads.resize(0); } void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count) { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); ImGui_ImplSDL3_CloseGamepads(); if (mode == ImGui_ImplSDL3_GamepadMode_Manual) { IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0); for (int n = 0; n < manual_gamepads_count; n++) bd->Gamepads.push_back(manual_gamepads_array[n]); } else { IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0); bd->WantUpdateGamepadsList = true; } bd->GamepadMode = mode; } static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no) { bool merged_value = false; for (SDL_Gamepad* gamepad : bd->Gamepads) merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0; io.AddKeyEvent(key, merged_value); } static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1) { float merged_value = 0.0f; for (SDL_Gamepad* gamepad : bd->Gamepads) { float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0)); if (merged_value < vn) merged_value = vn; } io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value); } static void ImGui_ImplSDL3_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); // Update list of gamepads to use if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) { ImGui_ImplSDL3_CloseGamepads(); int sdl_gamepads_count = 0; SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); for (int n = 0; n < sdl_gamepads_count; n++) if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n])) { bd->Gamepads.push_back(gamepad); if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst) break; } bd->WantUpdateGamepadsList = false; SDL_free(sdl_gamepads); } // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; if (bd->Gamepads.Size == 0) return; io.BackendFlags |= ImGuiBackendFlags_HasGamepad; // Update gamepad inputs const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value. ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767); } void ImGui_ImplSDL3_NewFrame() { ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?"); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(bd->Window, &w, &h); if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) w = h = 0; SDL_GetWindowSizeInPixels(bd->Window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); if (current_time <= bd->Time) current_time = bd->Time + 1; io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); bd->Time = current_time; if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) { bd->MouseWindowID = 0; bd->MousePendingLeaveFrame = 0; io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); } ImGui_ImplSDL3_UpdateMouseData(); ImGui_ImplSDL3_UpdateMouseCursor(); // Update game controllers (if enabled and available) ImGui_ImplSDL3_UpdateGamepads(); } //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx9.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_dx9.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_dx9.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX9_Init(cimgui::IDirect3DDevice9* device) { return ::ImGui_ImplDX9_Init(reinterpret_cast<::IDirect3DDevice9*>(device)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX9_Shutdown(void) { ::ImGui_ImplDX9_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX9_NewFrame(void) { ::ImGui_ImplDX9_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX9_RenderDrawData(cimgui::ImDrawData* draw_data) { ::ImGui_ImplDX9_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX9_CreateDeviceObjects(void) { return ::ImGui_ImplDX9_CreateDeviceObjects(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX9_InvalidateDeviceObjects(void) { ::ImGui_ImplDX9_InvalidateDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_opengl2.cpp
// dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline) // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in imgui_impl_opengl3.cpp** // 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. // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-06-28: OpenGL: ImGui_ImplOpenGL2_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL2_DestroyFontsTexture(). (#7748) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-12-08: OpenGL: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-01-03: OpenGL: Backup, setup and restore GL_SHADE_MODEL state, disable GL_STENCIL_TEST and disable GL_NORMAL_ARRAY client state to increase compatibility with legacy OpenGL applications. // 2020-01-23: OpenGL: Backup, setup and restore GL_TEXTURE_ENV to increase compatibility with legacy OpenGL applications. // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications. // 2018-06-08: Misc: Extracted imgui_impl_opengl2.cpp/.h away from the old combined GLFW/SDL+OpenGL2 examples. // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplOpenGL2_RenderDrawData() in the .h file so you can call it yourself. // 2017-09-01: OpenGL: Save and restore current polygon mode. // 2016-09-10: OpenGL: Uploading font texture as RGBA32 to increase compatibility with users shaders (not ideal). // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_opengl2.h" #include <stdint.h> // intptr_t // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used #pragma clang diagnostic ignored "-Wnonportable-system-include-path" #endif // Include OpenGL header (without an OpenGL loader) requires a bit of fiddling #if defined(_WIN32) && !defined(APIENTRY) #define APIENTRY __stdcall // It is customary to use APIENTRY for OpenGL function pointer declarations on all platforms. Additionally, the Windows OpenGL header needs APIENTRY. #endif #if defined(_WIN32) && !defined(WINGDIAPI) #define WINGDIAPI __declspec(dllimport) // Some Windows OpenGL headers need this #endif #if defined(__APPLE__) #define GL_SILENCE_DEPRECATION #include <OpenGL/gl.h> #else #include <GL/gl.h> #endif struct ImGui_ImplOpenGL2_Data { GLuint FontTexture; ImGui_ImplOpenGL2_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplOpenGL2_Data* ImGui_ImplOpenGL2_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions bool ImGui_ImplOpenGL2_Init() { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplOpenGL2_Data* bd = IM_NEW(ImGui_ImplOpenGL2_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_opengl2"; return true; } void ImGui_ImplOpenGL2_Shutdown() { ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL2_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; IM_DELETE(bd); } void ImGui_ImplOpenGL2_NewFrame() { ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL2_Init()?"); if (!bd->FontTexture) ImGui_ImplOpenGL2_CreateDeviceObjects(); if (!bd->FontTexture) ImGui_ImplOpenGL2_CreateFontsTexture(); } static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height) { // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill. glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // In order to composite our output buffer we need to preserve alpha glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_STENCIL_TEST); glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); glEnable(GL_SCISSOR_TEST); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glEnable(GL_TEXTURE_2D); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glShadeModel(GL_SMOOTH); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); // If you are using this code with non-legacy OpenGL header/contexts (which you should not, prefer using imgui_impl_opengl3.cpp!!), // you may need to backup/reset/restore other state, e.g. for current shader using the commented lines below. // (DO NOT MODIFY THIS FILE! Add the code in your calling function) // GLint last_program; // glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); // glUseProgram(0); // ImGui_ImplOpenGL2_RenderDrawData(...); // glUseProgram(last_program) // There are potentially many more states you could need to clear/setup that we can't access from default headers. // e.g. glBindBuffer(GL_ARRAY_BUFFER, 0), glDisable(GL_TEXTURE_CUBE_MAP). // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(draw_data->DisplayPos.x, draw_data->DisplayPos.x + draw_data->DisplaySize.x, draw_data->DisplayPos.y + draw_data->DisplaySize.y, draw_data->DisplayPos.y, -1.0f, +1.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); } // OpenGL2 Render function. // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. // This is in order to be able to run within an OpenGL engine that doesn't do so. void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; // Backup GL state 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); GLint last_shade_model; glGetIntegerv(GL_SHADE_MODEL, &last_shade_model); GLint last_tex_env_mode; glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &last_tex_env_mode); glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT); // Setup desired GL state ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists 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))); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply scissor/clipping rectangle (Y is inverted in OpenGL) glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)); // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset); } } } // Restore modified GL state glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)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]); glShadeModel(last_shade_model); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, last_tex_env_mode); } bool ImGui_ImplOpenGL2_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGenTextures(1, &bd->FontTexture); glBindTexture(GL_TEXTURE_2D, bd->FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); // Restore state glBindTexture(GL_TEXTURE_2D, last_texture); return true; } void ImGui_ImplOpenGL2_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); if (bd->FontTexture) { glDeleteTextures(1, &bd->FontTexture); io.Fonts->SetTexID(0); bd->FontTexture = 0; } } bool ImGui_ImplOpenGL2_CreateDeviceObjects() { return ImGui_ImplOpenGL2_CreateFontsTexture(); } void ImGui_ImplOpenGL2_DestroyDeviceObjects() { ImGui_ImplOpenGL2_DestroyFontsTexture(); } //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdlrenderer2.h
// dear imgui: Renderer Backend for SDL_Renderer for SDL2 // (Requires: SDL 2.0.17+) // Note how SDL_Renderer is an _optional_ component of SDL2. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and // it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifndef IMGUI_DISABLE #include "imgui.h" // IMGUI_IMPL_API struct SDL_Renderer; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer); // Called by Init/NewFrame/Shutdown IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_android.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Platform Binding for Android native app // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3) // Implemented features: // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // Missing features: // [ ] Platform: Clipboard support. // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. // Important: // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446) // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446) // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct ANativeWindow_t ANativeWindow; typedef struct AInputEvent_t AInputEvent; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplAndroid_Init(ANativeWindow* window); CIMGUI_IMPL_API int32_t cImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event); CIMGUI_IMPL_API void cImGui_ImplAndroid_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplAndroid_NewFrame(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_allegro5.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer + Platform Backend for Allegro 5 // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) // Implemented features: // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Clipboard support (from Allegro 5.1.12) // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Issues: // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct ALLEGRO_DISPLAY_t ALLEGRO_DISPLAY; typedef union ALLEGRO_EVENT_t ALLEGRO_EVENT; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display); CIMGUI_IMPL_API void cImGui_ImplAllegro5_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplAllegro5_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data); CIMGUI_IMPL_API bool cImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event); // Use if you want to reset your rendering device without losing Dear ImGui state. CIMGUI_IMPL_API bool cImGui_ImplAllegro5_CreateDeviceObjects(void); CIMGUI_IMPL_API void cImGui_ImplAllegro5_InvalidateDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdlrenderer3.cpp
// dear imgui: Renderer Backend for SDL_Renderer for SDL3 // (Requires: SDL 3.0.0+) // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Note how SDL_Renderer is an _optional_ component of SDL3. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and // it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // 2024-07-01: Update for SDL3 api changes: SDL_RenderGeometryRaw() uint32 version was removed (SDL#9009). // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter. // 2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly. // 2023-05-30: Initial version. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_sdlrenderer3.h" #include <stdint.h> // intptr_t // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #endif // SDL #include <SDL3/SDL.h> #if !SDL_VERSION_ATLEAST(3,0,0) #error This backend requires SDL 3.0.0+ #endif // SDL_Renderer data struct ImGui_ImplSDLRenderer3_Data { SDL_Renderer* Renderer; // Main viewport's renderer SDL_Texture* FontTexture; ImVector<SDL_FColor> ColorBuffer; ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplSDLRenderer3_Data* ImGui_ImplSDLRenderer3_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); // Setup backend capabilities flags ImGui_ImplSDLRenderer3_Data* bd = IM_NEW(ImGui_ImplSDLRenderer3_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_sdlrenderer3"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. bd->Renderer = renderer; return true; } void ImGui_ImplSDLRenderer3_Shutdown() { ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } static void ImGui_ImplSDLRenderer3_SetupRenderState(SDL_Renderer* renderer) { // Clear out any viewports and cliprect set by the user // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. SDL_SetRenderViewport(renderer, nullptr); SDL_SetRenderClipRect(renderer, nullptr); } void ImGui_ImplSDLRenderer3_NewFrame() { ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer3_Init()?"); if (!bd->FontTexture) ImGui_ImplSDLRenderer3_CreateDeviceObjects(); } // https://github.com/libsdl-org/SDL/issues/9009 static int SDL_RenderGeometryRaw8BitColor(SDL_Renderer* renderer, ImVector<SDL_FColor>& colors_out, SDL_Texture* texture, const float* xy, int xy_stride, const SDL_Color* color, int color_stride, const float* uv, int uv_stride, int num_vertices, const void* indices, int num_indices, int size_indices) { const Uint8* color2 = (const Uint8*)color; colors_out.resize(num_vertices); SDL_FColor* color3 = colors_out.Data; for (int i = 0; i < num_vertices; i++) { color3[i].r = color->r / 255.0f; color3[i].g = color->g / 255.0f; color3[i].b = color->b / 255.0f; color3[i].a = color->a / 255.0f; color2 += color_stride; color = (const SDL_Color*)color2; } return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, color3, sizeof(*color3), uv, uv_stride, num_vertices, indices, num_indices, size_indices); } void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer) { ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); // If there's a scale factor set by the user, use that instead // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. float rsx = 1.0f; float rsy = 1.0f; SDL_GetRenderScale(renderer, &rsx, &rsy); ImVec2 render_scale; render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); if (fb_width == 0 || fb_height == 0) return; // Backup SDL_Renderer state that will be modified to restore it afterwards struct BackupSDLRendererState { SDL_Rect Viewport; bool ViewportEnabled; bool ClipEnabled; SDL_Rect ClipRect; }; BackupSDLRendererState old = {}; old.ViewportEnabled = SDL_RenderViewportSet(renderer) == SDL_TRUE; old.ClipEnabled = SDL_RenderClipEnabled(renderer) == SDL_TRUE; SDL_GetRenderViewport(renderer, &old.Viewport); SDL_GetRenderClipRect(renderer, &old.ClipRect); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_scale = render_scale; // Render command lists ImGui_ImplSDLRenderer3_SetupRenderState(renderer); 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; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplSDLRenderer3_SetupRenderState(renderer); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; } if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; } if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) }; SDL_SetRenderClipRect(renderer, &r); const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos)); const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv)); const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+ // Bind texture, Draw SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); SDL_RenderGeometryRaw8BitColor(renderer, bd->ColorBuffer, tex, xy, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert), uv, (int)sizeof(ImDrawVert), cmd_list->VtxBuffer.Size - pcmd->VtxOffset, idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx)); } } } // Restore modified SDL_Renderer state SDL_SetRenderViewport(renderer, old.ViewportEnabled ? &old.Viewport : nullptr); SDL_SetRenderClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr); } // Called by Init/NewFrame/Shutdown bool ImGui_ImplSDLRenderer3_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); // Build texture atlas unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); if (bd->FontTexture == nullptr) { SDL_Log("error creating texture"); return false; } SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); SDL_SetTextureScaleMode(bd->FontTexture, SDL_SCALEMODE_LINEAR); // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); return true; } void ImGui_ImplSDLRenderer3_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); if (bd->FontTexture) { io.Fonts->SetTexID(0); SDL_DestroyTexture(bd->FontTexture); bd->FontTexture = nullptr; } } bool ImGui_ImplSDLRenderer3_CreateDeviceObjects() { return ImGui_ImplSDLRenderer3_CreateFontsTexture(); } void ImGui_ImplSDLRenderer3_DestroyDeviceObjects() { ImGui_ImplSDLRenderer3_DestroyFontsTexture(); } //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_opengl2.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline) // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in imgui_impl_opengl3.cpp** // 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. #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplOpenGL2_Init(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL2_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL2_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data); // Called by Init/NewFrame/Shutdown CIMGUI_IMPL_API bool cImGui_ImplOpenGL2_CreateFontsTexture(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL2_DestroyFontsTexture(void); CIMGUI_IMPL_API bool cImGui_ImplOpenGL2_CreateDeviceObjects(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL2_DestroyDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_android.cpp
// dear imgui: Platform Binding for Android native app // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3) // Implemented features: // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // Missing features: // [ ] Platform: Clipboard support. // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. // Important: // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446) // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446) // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2021-03-04: Initial version. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_android.h" #include <time.h> #include <android/native_window.h> #include <android/input.h> #include <android/keycodes.h> #include <android/log.h> // Android data static double g_Time = 0.0; static ANativeWindow* g_Window; static char g_LogTag[] = "ImGuiExample"; static ImGuiKey ImGui_ImplAndroid_KeyCodeToImGuiKey(int32_t key_code) { switch (key_code) { case AKEYCODE_TAB: return ImGuiKey_Tab; case AKEYCODE_DPAD_LEFT: return ImGuiKey_LeftArrow; case AKEYCODE_DPAD_RIGHT: return ImGuiKey_RightArrow; case AKEYCODE_DPAD_UP: return ImGuiKey_UpArrow; case AKEYCODE_DPAD_DOWN: return ImGuiKey_DownArrow; case AKEYCODE_PAGE_UP: return ImGuiKey_PageUp; case AKEYCODE_PAGE_DOWN: return ImGuiKey_PageDown; case AKEYCODE_MOVE_HOME: return ImGuiKey_Home; case AKEYCODE_MOVE_END: return ImGuiKey_End; case AKEYCODE_INSERT: return ImGuiKey_Insert; case AKEYCODE_FORWARD_DEL: return ImGuiKey_Delete; case AKEYCODE_DEL: return ImGuiKey_Backspace; case AKEYCODE_SPACE: return ImGuiKey_Space; case AKEYCODE_ENTER: return ImGuiKey_Enter; case AKEYCODE_ESCAPE: return ImGuiKey_Escape; case AKEYCODE_APOSTROPHE: return ImGuiKey_Apostrophe; case AKEYCODE_COMMA: return ImGuiKey_Comma; case AKEYCODE_MINUS: return ImGuiKey_Minus; case AKEYCODE_PERIOD: return ImGuiKey_Period; case AKEYCODE_SLASH: return ImGuiKey_Slash; case AKEYCODE_SEMICOLON: return ImGuiKey_Semicolon; case AKEYCODE_EQUALS: return ImGuiKey_Equal; case AKEYCODE_LEFT_BRACKET: return ImGuiKey_LeftBracket; case AKEYCODE_BACKSLASH: return ImGuiKey_Backslash; case AKEYCODE_RIGHT_BRACKET: return ImGuiKey_RightBracket; case AKEYCODE_GRAVE: return ImGuiKey_GraveAccent; case AKEYCODE_CAPS_LOCK: return ImGuiKey_CapsLock; case AKEYCODE_SCROLL_LOCK: return ImGuiKey_ScrollLock; case AKEYCODE_NUM_LOCK: return ImGuiKey_NumLock; case AKEYCODE_SYSRQ: return ImGuiKey_PrintScreen; case AKEYCODE_BREAK: return ImGuiKey_Pause; case AKEYCODE_NUMPAD_0: return ImGuiKey_Keypad0; case AKEYCODE_NUMPAD_1: return ImGuiKey_Keypad1; case AKEYCODE_NUMPAD_2: return ImGuiKey_Keypad2; case AKEYCODE_NUMPAD_3: return ImGuiKey_Keypad3; case AKEYCODE_NUMPAD_4: return ImGuiKey_Keypad4; case AKEYCODE_NUMPAD_5: return ImGuiKey_Keypad5; case AKEYCODE_NUMPAD_6: return ImGuiKey_Keypad6; case AKEYCODE_NUMPAD_7: return ImGuiKey_Keypad7; case AKEYCODE_NUMPAD_8: return ImGuiKey_Keypad8; case AKEYCODE_NUMPAD_9: return ImGuiKey_Keypad9; case AKEYCODE_NUMPAD_DOT: return ImGuiKey_KeypadDecimal; case AKEYCODE_NUMPAD_DIVIDE: return ImGuiKey_KeypadDivide; case AKEYCODE_NUMPAD_MULTIPLY: return ImGuiKey_KeypadMultiply; case AKEYCODE_NUMPAD_SUBTRACT: return ImGuiKey_KeypadSubtract; case AKEYCODE_NUMPAD_ADD: return ImGuiKey_KeypadAdd; case AKEYCODE_NUMPAD_ENTER: return ImGuiKey_KeypadEnter; case AKEYCODE_NUMPAD_EQUALS: return ImGuiKey_KeypadEqual; case AKEYCODE_CTRL_LEFT: return ImGuiKey_LeftCtrl; case AKEYCODE_SHIFT_LEFT: return ImGuiKey_LeftShift; case AKEYCODE_ALT_LEFT: return ImGuiKey_LeftAlt; case AKEYCODE_META_LEFT: return ImGuiKey_LeftSuper; case AKEYCODE_CTRL_RIGHT: return ImGuiKey_RightCtrl; case AKEYCODE_SHIFT_RIGHT: return ImGuiKey_RightShift; case AKEYCODE_ALT_RIGHT: return ImGuiKey_RightAlt; case AKEYCODE_META_RIGHT: return ImGuiKey_RightSuper; case AKEYCODE_MENU: return ImGuiKey_Menu; case AKEYCODE_0: return ImGuiKey_0; case AKEYCODE_1: return ImGuiKey_1; case AKEYCODE_2: return ImGuiKey_2; case AKEYCODE_3: return ImGuiKey_3; case AKEYCODE_4: return ImGuiKey_4; case AKEYCODE_5: return ImGuiKey_5; case AKEYCODE_6: return ImGuiKey_6; case AKEYCODE_7: return ImGuiKey_7; case AKEYCODE_8: return ImGuiKey_8; case AKEYCODE_9: return ImGuiKey_9; case AKEYCODE_A: return ImGuiKey_A; case AKEYCODE_B: return ImGuiKey_B; case AKEYCODE_C: return ImGuiKey_C; case AKEYCODE_D: return ImGuiKey_D; case AKEYCODE_E: return ImGuiKey_E; case AKEYCODE_F: return ImGuiKey_F; case AKEYCODE_G: return ImGuiKey_G; case AKEYCODE_H: return ImGuiKey_H; case AKEYCODE_I: return ImGuiKey_I; case AKEYCODE_J: return ImGuiKey_J; case AKEYCODE_K: return ImGuiKey_K; case AKEYCODE_L: return ImGuiKey_L; case AKEYCODE_M: return ImGuiKey_M; case AKEYCODE_N: return ImGuiKey_N; case AKEYCODE_O: return ImGuiKey_O; case AKEYCODE_P: return ImGuiKey_P; case AKEYCODE_Q: return ImGuiKey_Q; case AKEYCODE_R: return ImGuiKey_R; case AKEYCODE_S: return ImGuiKey_S; case AKEYCODE_T: return ImGuiKey_T; case AKEYCODE_U: return ImGuiKey_U; case AKEYCODE_V: return ImGuiKey_V; case AKEYCODE_W: return ImGuiKey_W; case AKEYCODE_X: return ImGuiKey_X; case AKEYCODE_Y: return ImGuiKey_Y; case AKEYCODE_Z: return ImGuiKey_Z; case AKEYCODE_F1: return ImGuiKey_F1; case AKEYCODE_F2: return ImGuiKey_F2; case AKEYCODE_F3: return ImGuiKey_F3; case AKEYCODE_F4: return ImGuiKey_F4; case AKEYCODE_F5: return ImGuiKey_F5; case AKEYCODE_F6: return ImGuiKey_F6; case AKEYCODE_F7: return ImGuiKey_F7; case AKEYCODE_F8: return ImGuiKey_F8; case AKEYCODE_F9: return ImGuiKey_F9; case AKEYCODE_F10: return ImGuiKey_F10; case AKEYCODE_F11: return ImGuiKey_F11; case AKEYCODE_F12: return ImGuiKey_F12; default: return ImGuiKey_None; } } int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event) { ImGuiIO& io = ImGui::GetIO(); int32_t event_type = AInputEvent_getType(input_event); switch (event_type) { case AINPUT_EVENT_TYPE_KEY: { int32_t event_key_code = AKeyEvent_getKeyCode(input_event); int32_t event_scan_code = AKeyEvent_getScanCode(input_event); int32_t event_action = AKeyEvent_getAction(input_event); int32_t event_meta_state = AKeyEvent_getMetaState(input_event); io.AddKeyEvent(ImGuiMod_Ctrl, (event_meta_state & AMETA_CTRL_ON) != 0); io.AddKeyEvent(ImGuiMod_Shift, (event_meta_state & AMETA_SHIFT_ON) != 0); io.AddKeyEvent(ImGuiMod_Alt, (event_meta_state & AMETA_ALT_ON) != 0); io.AddKeyEvent(ImGuiMod_Super, (event_meta_state & AMETA_META_ON) != 0); switch (event_action) { // FIXME: AKEY_EVENT_ACTION_DOWN and AKEY_EVENT_ACTION_UP occur at once as soon as a touch pointer // goes up from a key. We use a simple key event queue/ and process one event per key per frame in // ImGui_ImplAndroid_NewFrame()...or consider using IO queue, if suitable: https://github.com/ocornut/imgui/issues/2787 case AKEY_EVENT_ACTION_DOWN: case AKEY_EVENT_ACTION_UP: { ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code); if (key != ImGuiKey_None) { io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN); io.SetKeyEventNativeData(key, event_key_code, event_scan_code); } break; } default: break; } break; } case AINPUT_EVENT_TYPE_MOTION: { int32_t event_action = AMotionEvent_getAction(input_event); int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; event_action &= AMOTION_EVENT_ACTION_MASK; switch (AMotionEvent_getToolType(input_event, event_pointer_index)) { case AMOTION_EVENT_TOOL_TYPE_MOUSE: io.AddMouseSourceEvent(ImGuiMouseSource_Mouse); break; case AMOTION_EVENT_TOOL_TYPE_STYLUS: case AMOTION_EVENT_TOOL_TYPE_ERASER: io.AddMouseSourceEvent(ImGuiMouseSource_Pen); break; case AMOTION_EVENT_TOOL_TYPE_FINGER: default: io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen); break; } switch (event_action) { case AMOTION_EVENT_ACTION_DOWN: case AMOTION_EVENT_ACTION_UP: { // Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP, // but we have to process them separately to identify the actual button pressed. This is done below via // AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback). int tool_type = AMotionEvent_getToolType(input_event, event_pointer_index); if (tool_type == AMOTION_EVENT_TOOL_TYPE_FINGER || tool_type == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); io.AddMouseButtonEvent(0, event_action == AMOTION_EVENT_ACTION_DOWN); } break; } case AMOTION_EVENT_ACTION_BUTTON_PRESS: case AMOTION_EVENT_ACTION_BUTTON_RELEASE: { int32_t button_state = AMotionEvent_getButtonState(input_event); io.AddMouseButtonEvent(0, (button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0); io.AddMouseButtonEvent(1, (button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0); io.AddMouseButtonEvent(2, (button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0); break; } case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse) case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); break; case AMOTION_EVENT_ACTION_SCROLL: io.AddMouseWheelEvent(AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_HSCROLL, event_pointer_index), AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_VSCROLL, event_pointer_index)); break; default: break; } } return 1; default: break; } return 0; } bool ImGui_ImplAndroid_Init(ANativeWindow* window) { IMGUI_CHECKVERSION(); g_Window = window; g_Time = 0.0; // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendPlatformName = "imgui_impl_android"; return true; } void ImGui_ImplAndroid_Shutdown() { ImGuiIO& io = ImGui::GetIO(); io.BackendPlatformName = nullptr; } void ImGui_ImplAndroid_NewFrame() { ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int32_t window_width = ANativeWindow_getWidth(g_Window); int32_t window_height = ANativeWindow_getHeight(g_Window); int display_width = window_width; int display_height = window_height; io.DisplaySize = ImVec2((float)window_width, (float)window_height); if (window_width > 0 && window_height > 0) io.DisplayFramebufferScale = ImVec2((float)display_width / window_width, (float)display_height / window_height); // Setup time step struct timespec current_timespec; clock_gettime(CLOCK_MONOTONIC, &current_timespec); double current_time = (double)(current_timespec.tv_sec) + (current_timespec.tv_nsec / 1000000000.0); io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_opengl3.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline // - Desktop GL: 2.x 3.x 4.x // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). // About WebGL/ES: // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. // - This is done automatically on iOS, Android and Emscripten targets. // - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // About GLSL version: // The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string. // On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" // Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplOpenGL3_Init(void); // Implied glsl_version = nullptr CIMGUI_IMPL_API bool cImGui_ImplOpenGL3_InitEx(const char* glsl_version /* = nullptr */); CIMGUI_IMPL_API void cImGui_ImplOpenGL3_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL3_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); // (Optional) Called by Init/NewFrame/Shutdown CIMGUI_IMPL_API bool cImGui_ImplOpenGL3_CreateFontsTexture(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL3_DestroyFontsTexture(void); CIMGUI_IMPL_API bool cImGui_ImplOpenGL3_CreateDeviceObjects(void); CIMGUI_IMPL_API void cImGui_ImplOpenGL3_DestroyDeviceObjects(void); // Configuration flags to add in your imconfig file: //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten) //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android) // You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. #if !defined(IMGUI_IMPL_OPENGL_ES2)\ &&!defined(IMGUI_IMPL_OPENGL_ES3) // Try to detect GLES on matching platforms #if defined(__APPLE__) #include <TargetConditionals.h> #endif // #if defined(__APPLE__) #if (defined(__APPLE__)&&(TARGET_OS_IOS || TARGET_OS_TV))||(defined(__ANDROID__)) #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" #else #if defined(__EMSCRIPTEN__)|| defined(__amigaos4__) #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" #else // Otherwise imgui_impl_opengl3_loader.h will be used. #endif // #if defined(__EMSCRIPTEN__)|| defined(__amigaos4__) #endif // #if (defined(__APPLE__)&&(TARGET_OS_IOS || TARGET_OS_TV))||(defined(__ANDROID__)) #endif // #if !defined(IMGUI_IMPL_OPENGL_ES2) &&!defined(IMGUI_IMPL_OPENGL_ES3) #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_osx.h
// dear imgui: Platform Backend for OSX / Cocoa // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) // - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. // - Requires linking with the GameController framework ("-framework GameController"). // Implemented features: // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Mouse support. Can discriminate Mouse/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend). // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: IME support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE #ifdef __OBJC__ @class NSEvent; @class NSView; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOSX_Init(NSView* _Nonnull view); IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view); #endif //----------------------------------------------------------------------------- // C++ API //----------------------------------------------------------------------------- #ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS // #include <AppKit/AppKit.hpp> #ifndef __OBJC__ // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view); IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view); #endif #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx9.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for DirectX9 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct IDirect3DDevice9 IDirect3DDevice9; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplDX9_Init(IDirect3DDevice9* device); CIMGUI_IMPL_API void cImGui_ImplDX9_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplDX9_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. CIMGUI_IMPL_API bool cImGui_ImplDX9_CreateDeviceObjects(void); CIMGUI_IMPL_API void cImGui_ImplDX9_InvalidateDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_wgpu.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer for WebGPU // This needs to be used along with a Platform Binding (e.g. GLFW) // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.) // Implemented features: // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE #include <webgpu/webgpu.h> // Initialization data, for ImGui_ImplWGPU_Init() typedef struct ImGui_ImplWGPU_InitInfo_ImDrawData_t ImGui_ImplWGPU_InitInfo_ImDrawData; typedef struct ImGui_ImplWGPU_InitInfo_t { WGPUDevice Device; int NumFramesInFlight /* = 3 */; WGPUTextureFormat RenderTargetFormat /* = WGPUTextureFormat_Undefined */; WGPUTextureFormat DepthStencilFormat /* = WGPUTextureFormat_Undefined */; WGPUMultisampleState PipelineMultisampleState /* = {} */; } ImGui_ImplWGPU_InitInfo; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info); CIMGUI_IMPL_API void cImGui_ImplWGPU_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplWGPU_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder); // Use if you want to reset your rendering device without losing Dear ImGui state. CIMGUI_IMPL_API void cImGui_ImplWGPU_InvalidateDeviceObjects(void); CIMGUI_IMPL_API bool cImGui_ImplWGPU_CreateDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdlrenderer2.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for SDL_Renderer for SDL2 // (Requires: SDL 2.0.17+) // Note how SDL_Renderer is an _optional_ component of SDL2. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and // it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #ifndef IMGUI_DISABLE #include "cimgui.h" typedef struct SDL_Renderer SDL_Renderer; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer2_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer2_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer); // Called by Init/NewFrame/Shutdown CIMGUI_IMPL_API bool cImGui_ImplSDLRenderer2_CreateFontsTexture(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer2_DestroyFontsTexture(void); CIMGUI_IMPL_API bool cImGui_ImplSDLRenderer2_CreateDeviceObjects(void); CIMGUI_IMPL_API void cImGui_ImplSDLRenderer2_DestroyDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx10.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_dx10.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_dx10.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX10_Init(cimgui::ID3D10Device* device) { return ::ImGui_ImplDX10_Init(reinterpret_cast<::ID3D10Device*>(device)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX10_Shutdown(void) { ::ImGui_ImplDX10_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX10_NewFrame(void) { ::ImGui_ImplDX10_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX10_RenderDrawData(cimgui::ImDrawData* draw_data) { ::ImGui_ImplDX10_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX10_InvalidateDeviceObjects(void) { ::ImGui_ImplDX10_InvalidateDeviceObjects(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX10_CreateDeviceObjects(void) { return ::ImGui_ImplDX10_CreateDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdlrenderer3.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_sdlrenderer3.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_sdlrenderer3.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDLRenderer3_Init(cimgui::SDL_Renderer* renderer) { return ::ImGui_ImplSDLRenderer3_Init(reinterpret_cast<::SDL_Renderer*>(renderer)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer3_Shutdown(void) { ::ImGui_ImplSDLRenderer3_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer3_NewFrame(void) { ::ImGui_ImplSDLRenderer3_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer3_RenderDrawData(cimgui::ImDrawData* draw_data, cimgui::SDL_Renderer* renderer) { ::ImGui_ImplSDLRenderer3_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data), reinterpret_cast<::SDL_Renderer*>(renderer)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDLRenderer3_CreateFontsTexture(void) { return ::ImGui_ImplSDLRenderer3_CreateFontsTexture(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer3_DestroyFontsTexture(void) { ::ImGui_ImplSDLRenderer3_DestroyFontsTexture(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDLRenderer3_CreateDeviceObjects(void) { return ::ImGui_ImplSDLRenderer3_CreateDeviceObjects(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer3_DestroyDeviceObjects(void) { ::ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx11.h
// dear imgui: Renderer Backend for DirectX11 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct ID3D11Device; struct ID3D11DeviceContext; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context); IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_wgpu.cpp
// dear imgui: Renderer for WebGPU // This needs to be used along with a Platform Binding (e.g. GLFW) // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.) // Implemented features: // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240) // 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes. // 2024-01-22: Fixed pipeline layout leak. (#7245) // 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults. // 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602) // 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V. // 2023-04-11: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470) // 2022-11-24: Fixed validation error with default depth buffer settings. // 2022-11-10: Fixed rendering when a depth buffer is enabled. Added 'WGPUTextureFormat depth_format' parameter to ImGui_ImplWGPU_Init(). // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer(). // 2021-08-24: Fixed for latest specs. // 2021-05-24: Add support for draw_data->FramebufferScale. // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92). // 2021-02-18: Change blending equation to preserve alpha in output buffer. // 2021-01-28: Initial version. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_wgpu.h" #include <limits.h> #include <webgpu/webgpu.h> // Dear ImGui prototypes from imgui_internal.h extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0); #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro). // WebGPU data struct RenderResources { WGPUTexture FontTexture = nullptr; // Font texture WGPUTextureView FontTextureView = nullptr; // Texture view for font texture WGPUSampler Sampler = nullptr; // Sampler for the font texture WGPUBuffer Uniforms = nullptr; // Shader uniforms WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map) WGPUBindGroup ImageBindGroup = nullptr; // Default font-resource of Dear ImGui WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM }; struct FrameResources { WGPUBuffer IndexBuffer; WGPUBuffer VertexBuffer; ImDrawIdx* IndexBufferHost; ImDrawVert* VertexBufferHost; int IndexBufferSize; int VertexBufferSize; }; struct Uniforms { float MVP[4][4]; float Gamma; }; struct ImGui_ImplWGPU_Data { ImGui_ImplWGPU_InitInfo initInfo; WGPUDevice wgpuDevice = nullptr; WGPUQueue defaultQueue = nullptr; WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined; WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined; WGPURenderPipeline pipelineState = nullptr; RenderResources renderResources; FrameResources* pFrameResources = nullptr; unsigned int numFramesInFlight = 0; unsigned int frameIndex = UINT_MAX; }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } //----------------------------------------------------------------------------- // SHADERS //----------------------------------------------------------------------------- static const char __shader_vert_wgsl[] = R"( struct VertexInput { @location(0) position: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>, }; struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) color: vec4<f32>, @location(1) uv: vec2<f32>, }; struct Uniforms { mvp: mat4x4<f32>, gamma: f32, }; @group(0) @binding(0) var<uniform> uniforms: Uniforms; @vertex fn main(in: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = uniforms.mvp * vec4<f32>(in.position, 0.0, 1.0); out.color = in.color; out.uv = in.uv; return out; } )"; static const char __shader_frag_wgsl[] = R"( struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) color: vec4<f32>, @location(1) uv: vec2<f32>, }; struct Uniforms { mvp: mat4x4<f32>, gamma: f32, }; @group(0) @binding(0) var<uniform> uniforms: Uniforms; @group(0) @binding(1) var s: sampler; @group(1) @binding(0) var t: texture_2d<f32>; @fragment fn main(in: VertexOutput) -> @location(0) vec4<f32> { let color = in.color * textureSample(t, s, in.uv); let corrected_color = pow(color.rgb, vec3<f32>(uniforms.gamma)); return vec4<f32>(corrected_color, color.a); } )"; static void SafeRelease(ImDrawIdx*& res) { if (res) delete[] res; res = nullptr; } static void SafeRelease(ImDrawVert*& res) { if (res) delete[] res; res = nullptr; } static void SafeRelease(WGPUBindGroupLayout& res) { if (res) wgpuBindGroupLayoutRelease(res); res = nullptr; } static void SafeRelease(WGPUBindGroup& res) { if (res) wgpuBindGroupRelease(res); res = nullptr; } static void SafeRelease(WGPUBuffer& res) { if (res) wgpuBufferRelease(res); res = nullptr; } static void SafeRelease(WGPUPipelineLayout& res) { if (res) wgpuPipelineLayoutRelease(res); res = nullptr; } static void SafeRelease(WGPURenderPipeline& res) { if (res) wgpuRenderPipelineRelease(res); res = nullptr; } static void SafeRelease(WGPUSampler& res) { if (res) wgpuSamplerRelease(res); res = nullptr; } static void SafeRelease(WGPUShaderModule& res) { if (res) wgpuShaderModuleRelease(res); res = nullptr; } static void SafeRelease(WGPUTextureView& res) { if (res) wgpuTextureViewRelease(res); res = nullptr; } static void SafeRelease(WGPUTexture& res) { if (res) wgpuTextureRelease(res); res = nullptr; } static void SafeRelease(RenderResources& res) { SafeRelease(res.FontTexture); SafeRelease(res.FontTextureView); SafeRelease(res.Sampler); SafeRelease(res.Uniforms); SafeRelease(res.CommonBindGroup); SafeRelease(res.ImageBindGroup); SafeRelease(res.ImageBindGroupLayout); }; static void SafeRelease(FrameResources& res) { SafeRelease(res.IndexBuffer); SafeRelease(res.VertexBuffer); SafeRelease(res.IndexBufferHost); SafeRelease(res.VertexBufferHost); } static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const char* wgsl_source) { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); WGPUShaderModuleWGSLDescriptor wgsl_desc = {}; wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor; wgsl_desc.code = wgsl_source; WGPUShaderModuleDescriptor desc = {}; desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgsl_desc); WGPUProgrammableStageDescriptor stage_desc = {}; stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc); stage_desc.entryPoint = "main"; return stage_desc; } static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture) { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } }; WGPUBindGroupDescriptor image_bg_descriptor = {}; image_bg_descriptor.layout = layout; image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry); image_bg_descriptor.entries = image_bg_entries; return wgpuDeviceCreateBindGroup(bd->wgpuDevice, &image_bg_descriptor); } static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr) { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). { float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; float mvp[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, { 0.0f, 0.0f, 0.5f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, MVP), mvp, sizeof(Uniforms::MVP)); float gamma; switch (bd->renderTargetFormat) { case WGPUTextureFormat_ASTC10x10UnormSrgb: case WGPUTextureFormat_ASTC10x5UnormSrgb: case WGPUTextureFormat_ASTC10x6UnormSrgb: case WGPUTextureFormat_ASTC10x8UnormSrgb: case WGPUTextureFormat_ASTC12x10UnormSrgb: case WGPUTextureFormat_ASTC12x12UnormSrgb: case WGPUTextureFormat_ASTC4x4UnormSrgb: case WGPUTextureFormat_ASTC5x5UnormSrgb: case WGPUTextureFormat_ASTC6x5UnormSrgb: case WGPUTextureFormat_ASTC6x6UnormSrgb: case WGPUTextureFormat_ASTC8x5UnormSrgb: case WGPUTextureFormat_ASTC8x6UnormSrgb: case WGPUTextureFormat_ASTC8x8UnormSrgb: case WGPUTextureFormat_BC1RGBAUnormSrgb: case WGPUTextureFormat_BC2RGBAUnormSrgb: case WGPUTextureFormat_BC3RGBAUnormSrgb: case WGPUTextureFormat_BC7RGBAUnormSrgb: case WGPUTextureFormat_BGRA8UnormSrgb: case WGPUTextureFormat_ETC2RGB8A1UnormSrgb: case WGPUTextureFormat_ETC2RGB8UnormSrgb: case WGPUTextureFormat_ETC2RGBA8UnormSrgb: case WGPUTextureFormat_RGBA8UnormSrgb: gamma = 2.2f; break; default: gamma = 1.0f; } wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, Gamma), &gamma, sizeof(Uniforms::Gamma)); } // Setup viewport wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1); // Bind shader and vertex buffers wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert)); wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx)); wgpuRenderPassEncoderSetPipeline(ctx, bd->pipelineState); wgpuRenderPassEncoderSetBindGroup(ctx, 0, bd->renderResources.CommonBindGroup, 0, nullptr); // Setup blend factor WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f }; wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color); } // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder) { // Avoid rendering when minimized int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0) return; // FIXME: Assuming that this only gets called once per frame! // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); bd->frameIndex = bd->frameIndex + 1; FrameResources* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight]; // Create and grow vertex/index buffers if needed if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount) { if (fr->VertexBuffer) { wgpuBufferDestroy(fr->VertexBuffer); wgpuBufferRelease(fr->VertexBuffer); } SafeRelease(fr->VertexBufferHost); fr->VertexBufferSize = draw_data->TotalVtxCount + 5000; WGPUBufferDescriptor vb_desc = { nullptr, "Dear ImGui Vertex buffer", WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex, MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4), false }; fr->VertexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &vb_desc); if (!fr->VertexBuffer) return; fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize]; } if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount) { if (fr->IndexBuffer) { wgpuBufferDestroy(fr->IndexBuffer); wgpuBufferRelease(fr->IndexBuffer); } SafeRelease(fr->IndexBufferHost); fr->IndexBufferSize = draw_data->TotalIdxCount + 10000; WGPUBufferDescriptor ib_desc = { nullptr, "Dear ImGui Index buffer", WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index, MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4), false }; fr->IndexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ib_desc); if (!fr->IndexBuffer) return; fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize]; } // Upload vertex/index data into a single contiguous GPU buffer ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost; ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4); int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4); wgpuQueueWriteBuffer(bd->defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size); wgpuQueueWriteBuffer(bd->defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size); // Setup desired render state ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr); // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_scale = draw_data->FramebufferScale; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr); else pcmd->UserCallback(cmd_list, pcmd); } else { // Bind custom texture ImTextureID tex_id = pcmd->GetTexID(); ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id)); auto bind_group = bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash); if (bind_group) { wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr); } else { WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id); bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group); wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, nullptr); } // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); // Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply scissor/clipping rectangle, Draw wgpuRenderPassEncoderSetScissorRect(pass_encoder, (uint32_t)clip_min.x, (uint32_t)clip_min.y, (uint32_t)(clip_max.x - clip_min.x), (uint32_t)(clip_max.y - clip_min.y)); wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } } global_idx_offset += cmd_list->IdxBuffer.Size; global_vtx_offset += cmd_list->VtxBuffer.Size; } } static void ImGui_ImplWGPU_CreateFontsTexture() { // Build texture atlas ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height, size_pp; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp); // Upload texture to graphics system { WGPUTextureDescriptor tex_desc = {}; tex_desc.label = "Dear ImGui Font Texture"; tex_desc.dimension = WGPUTextureDimension_2D; tex_desc.size.width = width; tex_desc.size.height = height; tex_desc.size.depthOrArrayLayers = 1; tex_desc.sampleCount = 1; tex_desc.format = WGPUTextureFormat_RGBA8Unorm; tex_desc.mipLevelCount = 1; tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding; bd->renderResources.FontTexture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc); WGPUTextureViewDescriptor tex_view_desc = {}; tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm; tex_view_desc.dimension = WGPUTextureViewDimension_2D; tex_view_desc.baseMipLevel = 0; tex_view_desc.mipLevelCount = 1; tex_view_desc.baseArrayLayer = 0; tex_view_desc.arrayLayerCount = 1; tex_view_desc.aspect = WGPUTextureAspect_All; bd->renderResources.FontTextureView = wgpuTextureCreateView(bd->renderResources.FontTexture, &tex_view_desc); } // Upload texture data { WGPUImageCopyTexture dst_view = {}; dst_view.texture = bd->renderResources.FontTexture; dst_view.mipLevel = 0; dst_view.origin = { 0, 0, 0 }; dst_view.aspect = WGPUTextureAspect_All; WGPUTextureDataLayout layout = {}; layout.offset = 0; layout.bytesPerRow = width * size_pp; layout.rowsPerImage = height; WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 }; wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size); } // Create the associated sampler // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) { WGPUSamplerDescriptor sampler_desc = {}; sampler_desc.minFilter = WGPUFilterMode_Linear; sampler_desc.magFilter = WGPUFilterMode_Linear; sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear; sampler_desc.addressModeU = WGPUAddressMode_Repeat; sampler_desc.addressModeV = WGPUAddressMode_Repeat; sampler_desc.addressModeW = WGPUAddressMode_Repeat; sampler_desc.maxAnisotropy = 1; bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc); } // Store our identifier static_assert(sizeof(ImTextureID) >= sizeof(bd->renderResources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); io.Fonts->SetTexID((ImTextureID)bd->renderResources.FontTextureView); } static void ImGui_ImplWGPU_CreateUniformBuffer() { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); WGPUBufferDescriptor ub_desc = { nullptr, "Dear ImGui Uniform buffer", WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform, MEMALIGN(sizeof(Uniforms), 16), false }; bd->renderResources.Uniforms = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ub_desc); } bool ImGui_ImplWGPU_CreateDeviceObjects() { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); if (!bd->wgpuDevice) return false; if (bd->pipelineState) ImGui_ImplWGPU_InvalidateDeviceObjects(); // Create render pipeline WGPURenderPipelineDescriptor graphics_pipeline_desc = {}; graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList; graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined; graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW; graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None; graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState; // Bind group layouts WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {}; common_bg_layout_entries[0].binding = 0; common_bg_layout_entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment; common_bg_layout_entries[0].buffer.type = WGPUBufferBindingType_Uniform; common_bg_layout_entries[1].binding = 1; common_bg_layout_entries[1].visibility = WGPUShaderStage_Fragment; common_bg_layout_entries[1].sampler.type = WGPUSamplerBindingType_Filtering; WGPUBindGroupLayoutEntry image_bg_layout_entries[1] = {}; image_bg_layout_entries[0].binding = 0; image_bg_layout_entries[0].visibility = WGPUShaderStage_Fragment; image_bg_layout_entries[0].texture.sampleType = WGPUTextureSampleType_Float; image_bg_layout_entries[0].texture.viewDimension = WGPUTextureViewDimension_2D; WGPUBindGroupLayoutDescriptor common_bg_layout_desc = {}; common_bg_layout_desc.entryCount = 2; common_bg_layout_desc.entries = common_bg_layout_entries; WGPUBindGroupLayoutDescriptor image_bg_layout_desc = {}; image_bg_layout_desc.entryCount = 1; image_bg_layout_desc.entries = image_bg_layout_entries; WGPUBindGroupLayout bg_layouts[2]; bg_layouts[0] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &common_bg_layout_desc); bg_layouts[1] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &image_bg_layout_desc); WGPUPipelineLayoutDescriptor layout_desc = {}; layout_desc.bindGroupLayoutCount = 2; layout_desc.bindGroupLayouts = bg_layouts; graphics_pipeline_desc.layout = wgpuDeviceCreatePipelineLayout(bd->wgpuDevice, &layout_desc); // Create the vertex shader WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_vert_wgsl); graphics_pipeline_desc.vertex.module = vertex_shader_desc.module; graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint; // Vertex input configuration WGPUVertexAttribute attribute_desc[] = { { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 }, { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 }, { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 }, }; WGPUVertexBufferLayout buffer_layouts[1]; buffer_layouts[0].arrayStride = sizeof(ImDrawVert); buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex; buffer_layouts[0].attributeCount = 3; buffer_layouts[0].attributes = attribute_desc; graphics_pipeline_desc.vertex.bufferCount = 1; graphics_pipeline_desc.vertex.buffers = buffer_layouts; // Create the pixel shader WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_frag_wgsl); // Create the blending setup WGPUBlendState blend_state = {}; blend_state.alpha.operation = WGPUBlendOperation_Add; blend_state.alpha.srcFactor = WGPUBlendFactor_One; blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha; blend_state.color.operation = WGPUBlendOperation_Add; blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha; blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha; WGPUColorTargetState color_state = {}; color_state.format = bd->renderTargetFormat; color_state.blend = &blend_state; color_state.writeMask = WGPUColorWriteMask_All; WGPUFragmentState fragment_state = {}; fragment_state.module = pixel_shader_desc.module; fragment_state.entryPoint = pixel_shader_desc.entryPoint; fragment_state.targetCount = 1; fragment_state.targets = &color_state; graphics_pipeline_desc.fragment = &fragment_state; // Create depth-stencil State WGPUDepthStencilState depth_stencil_state = {}; depth_stencil_state.format = bd->depthStencilFormat; depth_stencil_state.depthWriteEnabled = false; depth_stencil_state.depthCompare = WGPUCompareFunction_Always; depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always; depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep; depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep; depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep; depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always; depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep; depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep; depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep; // Configure disabled depth-stencil state graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state; bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc); ImGui_ImplWGPU_CreateFontsTexture(); ImGui_ImplWGPU_CreateUniformBuffer(); // Create resource bind group WGPUBindGroupEntry common_bg_entries[] = { { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 }, { nullptr, 1, 0, 0, 0, bd->renderResources.Sampler, 0 }, }; WGPUBindGroupDescriptor common_bg_descriptor = {}; common_bg_descriptor.layout = bg_layouts[0]; common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry); common_bg_descriptor.entries = common_bg_entries; bd->renderResources.CommonBindGroup = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor); WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], bd->renderResources.FontTextureView); bd->renderResources.ImageBindGroup = image_bind_group; bd->renderResources.ImageBindGroupLayout = bg_layouts[1]; bd->renderResources.ImageBindGroups.SetVoidPtr(ImHashData(&bd->renderResources.FontTextureView, sizeof(ImTextureID)), image_bind_group); SafeRelease(vertex_shader_desc.module); SafeRelease(pixel_shader_desc.module); SafeRelease(graphics_pipeline_desc.layout); SafeRelease(bg_layouts[0]); return true; } void ImGui_ImplWGPU_InvalidateDeviceObjects() { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); if (!bd->wgpuDevice) return; SafeRelease(bd->pipelineState); SafeRelease(bd->renderResources); ImGuiIO& io = ImGui::GetIO(); io.Fonts->SetTexID(0); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. for (unsigned int i = 0; i < bd->numFramesInFlight; i++) SafeRelease(bd->pFrameResources[i]); } bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_webgpu"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. bd->initInfo = *init_info; bd->wgpuDevice = init_info->Device; bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice); bd->renderTargetFormat = init_info->RenderTargetFormat; bd->depthStencilFormat = init_info->DepthStencilFormat; bd->numFramesInFlight = init_info->NumFramesInFlight; bd->frameIndex = UINT_MAX; bd->renderResources.FontTexture = nullptr; bd->renderResources.FontTextureView = nullptr; bd->renderResources.Sampler = nullptr; bd->renderResources.Uniforms = nullptr; bd->renderResources.CommonBindGroup = nullptr; bd->renderResources.ImageBindGroups.Data.reserve(100); bd->renderResources.ImageBindGroup = nullptr; bd->renderResources.ImageBindGroupLayout = nullptr; // Create buffers with a default size (they will later be grown as needed) bd->pFrameResources = new FrameResources[bd->numFramesInFlight]; for (unsigned int i = 0; i < bd->numFramesInFlight; i++) { FrameResources* fr = &bd->pFrameResources[i]; fr->IndexBuffer = nullptr; fr->VertexBuffer = nullptr; fr->IndexBufferHost = nullptr; fr->VertexBufferHost = nullptr; fr->IndexBufferSize = 10000; fr->VertexBufferSize = 5000; } return true; } void ImGui_ImplWGPU_Shutdown() { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplWGPU_InvalidateDeviceObjects(); delete[] bd->pFrameResources; bd->pFrameResources = nullptr; wgpuQueueRelease(bd->defaultQueue); bd->wgpuDevice = nullptr; bd->numFramesInFlight = 0; bd->frameIndex = UINT_MAX; io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplWGPU_NewFrame() { ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); if (!bd->pipelineState) ImGui_ImplWGPU_CreateDeviceObjects(); } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_glut.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Platform Backend for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! // !!! Nowadays, prefer using GLFW or SDL instead! // Implemented features: // [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I // [ ] Platform: Missing horizontal mouse wheel support. // [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #ifndef IMGUI_DISABLE #include "cimgui.h" typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplGLUT_Init(void); CIMGUI_IMPL_API void cImGui_ImplGLUT_InstallFuncs(void); CIMGUI_IMPL_API void cImGui_ImplGLUT_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplGLUT_NewFrame(void); // You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically, // or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency.. //------------------------------------ GLUT name ---------------------------------------------- Decent Name --------- CIMGUI_IMPL_API void cImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc CIMGUI_IMPL_API void cImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc CIMGUI_IMPL_API void cImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc CIMGUI_IMPL_API void cImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y); // ~ MouseWheelFunc CIMGUI_IMPL_API void cImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y); // ~ CharPressedFunc CIMGUI_IMPL_API void cImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc CIMGUI_IMPL_API void cImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc CIMGUI_IMPL_API void cImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_wgpu.h
// dear imgui: Renderer for WebGPU // This needs to be used along with a Platform Binding (e.g. GLFW) // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.) // Implemented features: // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE #include <webgpu/webgpu.h> // Initialization data, for ImGui_ImplWGPU_Init() struct ImGui_ImplWGPU_InitInfo { WGPUDevice Device; int NumFramesInFlight = 3; WGPUTextureFormat RenderTargetFormat = WGPUTextureFormat_Undefined; WGPUTextureFormat DepthStencilFormat = WGPUTextureFormat_Undefined; WGPUMultisampleState PipelineMultisampleState = {}; ImGui_ImplWGPU_InitInfo() { PipelineMultisampleState.count = 1; PipelineMultisampleState.mask = UINT32_MAX; PipelineMultisampleState.alphaToCoverageEnabled = false; } }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info); IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame(); IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdlrenderer2.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_sdlrenderer2.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_sdlrenderer2.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDLRenderer2_Init(cimgui::SDL_Renderer* renderer) { return ::ImGui_ImplSDLRenderer2_Init(reinterpret_cast<::SDL_Renderer*>(renderer)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer2_Shutdown(void) { ::ImGui_ImplSDLRenderer2_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer2_NewFrame(void) { ::ImGui_ImplSDLRenderer2_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer2_RenderDrawData(cimgui::ImDrawData* draw_data, cimgui::SDL_Renderer* renderer) { ::ImGui_ImplSDLRenderer2_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data), reinterpret_cast<::SDL_Renderer*>(renderer)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDLRenderer2_CreateFontsTexture(void) { return ::ImGui_ImplSDLRenderer2_CreateFontsTexture(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer2_DestroyFontsTexture(void) { ::ImGui_ImplSDLRenderer2_DestroyFontsTexture(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDLRenderer2_CreateDeviceObjects(void) { return ::ImGui_ImplSDLRenderer2_CreateDeviceObjects(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDLRenderer2_DestroyDeviceObjects(void) { ::ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdl2.h
// dear imgui: Platform Backend for SDL2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct SDL_Window; struct SDL_Renderer; struct _SDL_GameController; typedef union SDL_Event SDL_Event; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOther(SDL_Window* window); IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(); IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. // When using manual mode, caller is responsible for opening/closing gamepad. enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual }; IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = NULL, int manual_gamepads_count = -1); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdl3.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct SDL_Window SDL_Window; typedef struct SDL_Renderer SDL_Renderer; typedef struct SDL_Gamepad SDL_Gamepad; typedef union SDL_Event SDL_Event; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); CIMGUI_IMPL_API bool cImGui_ImplSDL3_InitForVulkan(SDL_Window* window); CIMGUI_IMPL_API bool cImGui_ImplSDL3_InitForD3D(SDL_Window* window); CIMGUI_IMPL_API bool cImGui_ImplSDL3_InitForMetal(SDL_Window* window); CIMGUI_IMPL_API bool cImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); CIMGUI_IMPL_API bool cImGui_ImplSDL3_InitForOther(SDL_Window* window); CIMGUI_IMPL_API void cImGui_ImplSDL3_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplSDL3_NewFrame(void); CIMGUI_IMPL_API bool cImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. // When using manual mode, caller is responsible for opening/closing gamepad. typedef enum { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual, } ImGui_ImplSDL3_GamepadMode; CIMGUI_IMPL_API void cImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode); // Implied manual_gamepads_array = NULL, manual_gamepads_count = -1 CIMGUI_IMPL_API void cImGui_ImplSDL3_SetGamepadModeEx(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array /* = NULL */, int manual_gamepads_count /* = -1 */); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_win32.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplWin32_Init(void* hwnd); CIMGUI_IMPL_API bool cImGui_ImplWin32_InitForOpenGL(void* hwnd); CIMGUI_IMPL_API void cImGui_ImplWin32_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplWin32_NewFrame(void); // Win32 message handler your application need to call. // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h> from this helper. // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. // - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. #ifdef IMGUI_BACKEND_HAS_WINDOWS_H extern CIMGUI_IMPL_API LRESULT cImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); #endif // #ifdef IMGUI_BACKEND_HAS_WINDOWS_H // DPI-related helpers (optional) // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. CIMGUI_IMPL_API void cImGui_ImplWin32_EnableDpiAwareness(void); CIMGUI_IMPL_API float cImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd CIMGUI_IMPL_API float cImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor // Transparency related helpers (optional) [experimental] // - Use to enable alpha compositing transparency with the desktop. // - Use together with e.g. clearing your framebuffer with zero-alpha. CIMGUI_IMPL_API void cImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx10.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for DirectX10 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct ID3D10Device_t ID3D10Device; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplDX10_Init(ID3D10Device* device); CIMGUI_IMPL_API void cImGui_ImplDX10_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplDX10_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. CIMGUI_IMPL_API void cImGui_ImplDX10_InvalidateDeviceObjects(void); CIMGUI_IMPL_API bool cImGui_ImplDX10_CreateDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdl3.h
// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct SDL_Window; struct SDL_Renderer; struct SDL_Gamepad; typedef union SDL_Event SDL_Event; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOther(SDL_Window* window); IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame(); IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. // When using manual mode, caller is responsible for opening/closing gamepad. enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual }; IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = NULL, int manual_gamepads_count = -1); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_android.h
// dear imgui: Platform Binding for Android native app // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3) // Implemented features: // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // Missing features: // [ ] Platform: Clipboard support. // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. // Important: // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446) // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446) // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct ANativeWindow; struct AInputEvent; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window); IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event); IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown(); IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx9.cpp
// dear imgui: Renderer Backend for DirectX9 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1. // 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states. // 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857). // 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file. // 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer. // 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example. // 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_dx9.h" // DirectX #include <d3d9.h> // DirectX data struct ImGui_ImplDX9_Data { LPDIRECT3DDEVICE9 pd3dDevice; LPDIRECT3DVERTEXBUFFER9 pVB; LPDIRECT3DINDEXBUFFER9 pIB; LPDIRECT3DTEXTURE9 FontTexture; int VertexBufferSize; int IndexBufferSize; ImGui_ImplDX9_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } }; struct CUSTOMVERTEX { float pos[3]; D3DCOLOR col; float uv[2]; }; #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) #ifdef IMGUI_USE_BGRA_PACKED_COLOR #define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL) #else #define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16)) #endif // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); // Setup viewport D3DVIEWPORT9 vp; vp.X = vp.Y = 0; vp.Width = (DWORD)draw_data->DisplaySize.x; vp.Height = (DWORD)draw_data->DisplaySize.y; vp.MinZ = 0.0f; vp.MaxZ = 1.0f; bd->pd3dDevice->SetViewport(&vp); // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling. bd->pd3dDevice->SetPixelShader(nullptr); bd->pd3dDevice->SetVertexShader(nullptr); bd->pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); bd->pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); bd->pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); bd->pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); bd->pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); bd->pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE); bd->pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); bd->pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); bd->pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); bd->pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); bd->pd3dDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE); bd->pd3dDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE); bd->pd3dDevice->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA); bd->pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE); bd->pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE); bd->pd3dDevice->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE); bd->pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE, FALSE); bd->pd3dDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE); bd->pd3dDevice->SetRenderState(D3DRS_CLIPPING, TRUE); bd->pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE); bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); bd->pd3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); bd->pd3dDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); // Setup orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() { float L = draw_data->DisplayPos.x + 0.5f; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f; float T = draw_data->DisplayPos.y + 0.5f; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f; D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } }; D3DMATRIX mat_projection = { { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f/(T-B), 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f } } }; bd->pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity); bd->pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity); bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection); } } // Render function. void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; // Create and grow buffers if needed ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; if (bd->pd3dDevice->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0) return; } if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) { if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; if (bd->pd3dDevice->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0) return; } // Backup the DX9 state IDirect3DStateBlock9* d3d9_state_block = nullptr; if (bd->pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0) return; if (d3d9_state_block->Capture() < 0) { d3d9_state_block->Release(); return; } // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to) D3DMATRIX last_world, last_view, last_projection; bd->pd3dDevice->GetTransform(D3DTS_WORLD, &last_world); bd->pd3dDevice->GetTransform(D3DTS_VIEW, &last_view); bd->pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection); // Allocate buffers CUSTOMVERTEX* vtx_dst; ImDrawIdx* idx_dst; if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0) { d3d9_state_block->Release(); return; } if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0) { bd->pVB->Unlock(); d3d9_state_block->Release(); return; } // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data; for (int i = 0; i < cmd_list->VtxBuffer.Size; i++) { vtx_dst->pos[0] = vtx_src->pos.x; vtx_dst->pos[1] = vtx_src->pos.y; vtx_dst->pos[2] = 0.0f; vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col); vtx_dst->uv[0] = vtx_src->uv.x; vtx_dst->uv[1] = vtx_src->uv.y; vtx_dst++; vtx_src++; } memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); idx_dst += cmd_list->IdxBuffer.Size; } bd->pVB->Unlock(); bd->pIB->Unlock(); bd->pd3dDevice->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX)); bd->pd3dDevice->SetIndices(bd->pIB); bd->pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); // Setup desired DX state ImGui_ImplDX9_SetupRenderState(draw_data); // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; ImVec2 clip_off = draw_data->DisplayPos; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplDX9_SetupRenderState(draw_data); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply Scissor/clipping rectangle, Bind texture, Draw const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID(); bd->pd3dDevice->SetTexture(0, texture); bd->pd3dDevice->SetScissorRect(&r); bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3); } } global_idx_offset += cmd_list->IdxBuffer.Size; global_vtx_offset += cmd_list->VtxBuffer.Size; } // Restore the DX9 transform bd->pd3dDevice->SetTransform(D3DTS_WORLD, &last_world); bd->pd3dDevice->SetTransform(D3DTS_VIEW, &last_view); bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection); // Restore the DX9 state d3d9_state_block->Apply(); d3d9_state_block->Release(); } bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_dx9"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. bd->pd3dDevice = device; bd->pd3dDevice->AddRef(); return true; } void ImGui_ImplDX9_Shutdown() { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX9_InvalidateDeviceObjects(); if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } static bool ImGui_ImplDX9_CheckFormatSupport(IDirect3DDevice9* pDevice, D3DFORMAT format) { IDirect3D9* pd3d = nullptr; if (pDevice->GetDirect3D(&pd3d) != D3D_OK) return false; D3DDEVICE_CREATION_PARAMETERS param = {}; D3DDISPLAYMODE mode = {}; if (pDevice->GetCreationParameters(&param) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK) { pd3d->Release(); return false; } // Font texture should support linear filter, color blend and write to render-target bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK; pd3d->Release(); return support; } static bool ImGui_ImplDX9_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); unsigned char* pixels; int width, height, bytes_per_pixel; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel); // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices) #ifndef IMGUI_USE_BGRA_PACKED_COLOR const bool rgba_support = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8); if (!rgba_support && io.Fonts->TexPixelsUseColors) { ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel); for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++) *dst = IMGUI_COL_TO_DX9_ARGB(*src); pixels = (unsigned char*)dst_start; } #else const bool rgba_support = false; #endif // Upload texture to graphics system bd->FontTexture = nullptr; if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, rgba_support ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0) return false; D3DLOCKED_RECT tex_locked_rect; if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK) return false; for (int y = 0; y < height; y++) memcpy((unsigned char*)tex_locked_rect.pBits + (size_t)tex_locked_rect.Pitch * y, pixels + (size_t)width * bytes_per_pixel * y, (size_t)width * bytes_per_pixel); bd->FontTexture->UnlockRect(0); // Store our identifier io.Fonts->SetTexID((ImTextureID)bd->FontTexture); #ifndef IMGUI_USE_BGRA_PACKED_COLOR if (!rgba_support && io.Fonts->TexPixelsUseColors) ImGui::MemFree(pixels); #endif return true; } bool ImGui_ImplDX9_CreateDeviceObjects() { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); if (!bd || !bd->pd3dDevice) return false; if (!ImGui_ImplDX9_CreateFontsTexture()) return false; return true; } void ImGui_ImplDX9_InvalidateDeviceObjects() { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); if (!bd || !bd->pd3dDevice) return; if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. } void ImGui_ImplDX9_NewFrame() { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX9_Init()?"); if (!bd->FontTexture) ImGui_ImplDX9_CreateDeviceObjects(); } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_metal.h
// dear imgui: Renderer Backend for Metal // This needs to be used along with a Platform Backend (e.g. OSX) // Implemented features: // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE //----------------------------------------------------------------------------- // ObjC API //----------------------------------------------------------------------------- #ifdef __OBJC__ @class MTLRenderPassDescriptor; @protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id<MTLDevice> device); IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor); IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder); // Called by Init/NewFrame/Shutdown IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(id<MTLDevice> device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); #endif //----------------------------------------------------------------------------- // C++ API //----------------------------------------------------------------------------- // Enable Metal C++ binding support with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file // More info about using Metal from C++: https://developer.apple.com/metal/cpp/ #ifdef IMGUI_IMPL_METAL_CPP #include <Metal/Metal.hpp> #ifndef __OBJC__ // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplMetal_Init(MTL::Device* device); IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor); IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, MTL::CommandBuffer* commandBuffer, MTL::RenderCommandEncoder* commandEncoder); // Called by Init/NewFrame/Shutdown IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); #endif #endif //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_sdl3.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_sdl3.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_sdl3.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL3_InitForOpenGL(cimgui::SDL_Window* window, void* sdl_gl_context) { return ::ImGui_ImplSDL3_InitForOpenGL(reinterpret_cast<::SDL_Window*>(window), sdl_gl_context); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL3_InitForVulkan(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL3_InitForVulkan(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL3_InitForD3D(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL3_InitForD3D(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL3_InitForMetal(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL3_InitForMetal(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL3_InitForSDLRenderer(cimgui::SDL_Window* window, cimgui::SDL_Renderer* renderer) { return ::ImGui_ImplSDL3_InitForSDLRenderer(reinterpret_cast<::SDL_Window*>(window), reinterpret_cast<::SDL_Renderer*>(renderer)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL3_InitForOther(cimgui::SDL_Window* window) { return ::ImGui_ImplSDL3_InitForOther(reinterpret_cast<::SDL_Window*>(window)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL3_Shutdown(void) { ::ImGui_ImplSDL3_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL3_NewFrame(void) { ::ImGui_ImplSDL3_NewFrame(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) { return ::ImGui_ImplSDL3_ProcessEvent(event); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL3_SetGamepadMode(cimgui::ImGui_ImplSDL3_GamepadMode mode) { ::ImGui_ImplSDL3_SetGamepadMode(static_cast<::ImGui_ImplSDL3_GamepadMode>(mode)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplSDL3_SetGamepadModeEx(cimgui::ImGui_ImplSDL3_GamepadMode mode, cimgui::SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count) { ::ImGui_ImplSDL3_SetGamepadMode(static_cast<::ImGui_ImplSDL3_GamepadMode>(mode), reinterpret_cast<::SDL_Gamepad**>(manual_gamepads_array), manual_gamepads_count); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_glut.h
// dear imgui: Platform Backend for GLUT/FreeGLUT // This needs to be used along with a Renderer (e.g. OpenGL2) // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! // !!! Nowadays, prefer using GLFW or SDL instead! // Implemented features: // [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I // [ ] Platform: Missing horizontal mouse wheel support. // [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifndef IMGUI_DISABLE #include "imgui.h" // IMGUI_IMPL_API // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplGLUT_Init(); IMGUI_IMPL_API void ImGui_ImplGLUT_InstallFuncs(); IMGUI_IMPL_API void ImGui_ImplGLUT_Shutdown(); IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame(); // You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically, // or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency.. //------------------------------------ GLUT name ---------------------------------------------- Decent Name --------- IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y); // ~ MouseWheelFunc IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y); // ~ CharPressedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_glfw.h
// dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct GLFWwindow; struct GLFWmonitor; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks); IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks); IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks); IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); // Emscripten related initialization phase methods (call after ImGui_ImplGlfw_InitForOpenGL) #ifdef __EMSCRIPTEN__ IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector); //static inline void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector) { ImGui_ImplGlfw_InstallEmscriptenCallbacks(nullptr, canvas_selector); } } // Renamed in 1.91.0 #endif // GLFW callbacks install // - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any. // - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks. IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window); IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window); // GFLW callbacks options: // - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user) IMGUI_IMPL_API void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows); // GLFW callbacks (individual callbacks to call yourself if you didn't install callbacks) IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84 IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84 IMGUI_IMPL_API void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87 IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event); // GLFW helpers IMGUI_IMPL_API void ImGui_ImplGlfw_Sleep(int milliseconds); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdlrenderer2.cpp
// dear imgui: Renderer Backend for SDL_Renderer for SDL2 // (Requires: SDL 2.0.17+) // Note how SDL_Renderer is an _optional_ component of SDL2. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and // it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter. // 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-12-21: Update SDL_RenderGeometryRaw() format to work with SDL 2.0.19. // 2021-12-03: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2021-10-06: Backup and restore modified ClipRect/Viewport. // 2021-09-21: Initial version. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_sdlrenderer2.h" #include <stdint.h> // intptr_t // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #endif // SDL #include <SDL.h> #if !SDL_VERSION_ATLEAST(2,0,17) #error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function #endif // SDL_Renderer data struct ImGui_ImplSDLRenderer2_Data { SDL_Renderer* Renderer; // Main viewport's renderer SDL_Texture* FontTexture; ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplSDLRenderer2_Data* ImGui_ImplSDLRenderer2_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); // Setup backend capabilities flags ImGui_ImplSDLRenderer2_Data* bd = IM_NEW(ImGui_ImplSDLRenderer2_Data)(); io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_sdlrenderer2"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. bd->Renderer = renderer; return true; } void ImGui_ImplSDLRenderer2_Shutdown() { ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); io.BackendRendererName = nullptr; io.BackendRendererUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer) { // Clear out any viewports and cliprect set by the user // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. SDL_RenderSetViewport(renderer, nullptr); SDL_RenderSetClipRect(renderer, nullptr); } void ImGui_ImplSDLRenderer2_NewFrame() { ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer2_Init()?"); if (!bd->FontTexture) ImGui_ImplSDLRenderer2_CreateDeviceObjects(); } void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer) { // If there's a scale factor set by the user, use that instead // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. float rsx = 1.0f; float rsy = 1.0f; SDL_RenderGetScale(renderer, &rsx, &rsy); ImVec2 render_scale; render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); if (fb_width == 0 || fb_height == 0) return; // Backup SDL_Renderer state that will be modified to restore it afterwards struct BackupSDLRendererState { SDL_Rect Viewport; bool ClipEnabled; SDL_Rect ClipRect; }; BackupSDLRendererState old = {}; old.ClipEnabled = SDL_RenderIsClipEnabled(renderer) == SDL_TRUE; SDL_RenderGetViewport(renderer, &old.Viewport); SDL_RenderGetClipRect(renderer, &old.ClipRect); // Will project scissor/clipping rectangles into framebuffer space ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_scale = render_scale; // Render command lists ImGui_ImplSDLRenderer2_SetupRenderState(renderer); 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; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplSDLRenderer2_SetupRenderState(renderer); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; } if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; } if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) }; SDL_RenderSetClipRect(renderer, &r); const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos)); const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv)); #if SDL_VERSION_ATLEAST(2,0,19) const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+ #else const int* color = (const int*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.17 and 2.0.18 #endif // Bind texture, Draw SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); SDL_RenderGeometryRaw(renderer, tex, xy, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert), uv, (int)sizeof(ImDrawVert), cmd_list->VtxBuffer.Size - pcmd->VtxOffset, idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx)); } } } // Restore modified SDL_Renderer state SDL_RenderSetViewport(renderer, &old.Viewport); SDL_RenderSetClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr); } // Called by Init/NewFrame/Shutdown bool ImGui_ImplSDLRenderer2_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); // Build texture atlas unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); if (bd->FontTexture == nullptr) { SDL_Log("error creating texture"); return false; } SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); SDL_SetTextureScaleMode(bd->FontTexture, SDL_ScaleModeLinear); // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); return true; } void ImGui_ImplSDLRenderer2_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); if (bd->FontTexture) { io.Fonts->SetTexID(0); SDL_DestroyTexture(bd->FontTexture); bd->FontTexture = nullptr; } } bool ImGui_ImplSDLRenderer2_CreateDeviceObjects() { return ImGui_ImplSDLRenderer2_CreateFontsTexture(); } void ImGui_ImplSDLRenderer2_DestroyDeviceObjects() { ImGui_ImplSDLRenderer2_DestroyFontsTexture(); } //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_win32.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_win32.h" #include <stdio.h> #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> // This define indicates that we have windows.h included #define IMGUI_BACKEND_HAS_WINDOWS_H // We need to manually declare this extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_win32.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplWin32_Init(void* hwnd) { return ::ImGui_ImplWin32_Init(hwnd); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplWin32_InitForOpenGL(void* hwnd) { return ::ImGui_ImplWin32_InitForOpenGL(hwnd); } CIMGUI_IMPL_API void cimgui::cImGui_ImplWin32_Shutdown(void) { ::ImGui_ImplWin32_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplWin32_NewFrame(void) { ::ImGui_ImplWin32_NewFrame(); } #ifdef IMGUI_BACKEND_HAS_WINDOWS_H CIMGUI_IMPL_API LRESULT cimgui::cImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { return ::ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam); } #endif // #ifdef IMGUI_BACKEND_HAS_WINDOWS_H CIMGUI_IMPL_API void cimgui::cImGui_ImplWin32_EnableDpiAwareness(void) { ::ImGui_ImplWin32_EnableDpiAwareness(); } CIMGUI_IMPL_API float cimgui::cImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) { return ::ImGui_ImplWin32_GetDpiScaleForHwnd(hwnd); } CIMGUI_IMPL_API float cimgui::cImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) { return ::ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); } CIMGUI_IMPL_API void cimgui::cImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) { ::ImGui_ImplWin32_EnableAlphaCompositing(hwnd); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_allegro5.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_allegro5.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_allegro5.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplAllegro5_Init(cimgui::ALLEGRO_DISPLAY* display) { return ::ImGui_ImplAllegro5_Init(reinterpret_cast<::ALLEGRO_DISPLAY*>(display)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplAllegro5_Shutdown(void) { ::ImGui_ImplAllegro5_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplAllegro5_NewFrame(void) { ::ImGui_ImplAllegro5_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplAllegro5_RenderDrawData(cimgui::ImDrawData* draw_data) { ::ImGui_ImplAllegro5_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplAllegro5_ProcessEvent(cimgui::ALLEGRO_EVENT* event) { return ::ImGui_ImplAllegro5_ProcessEvent(reinterpret_cast<::ALLEGRO_EVENT*>(event)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplAllegro5_CreateDeviceObjects(void) { return ::ImGui_ImplAllegro5_CreateDeviceObjects(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplAllegro5_InvalidateDeviceObjects(void) { ::ImGui_ImplAllegro5_InvalidateDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_android.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_android.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_android.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplAndroid_Init(cimgui::ANativeWindow* window) { return ::ImGui_ImplAndroid_Init(reinterpret_cast<::ANativeWindow*>(window)); } CIMGUI_IMPL_API int32_t cimgui::cImGui_ImplAndroid_HandleInputEvent(const cimgui::AInputEvent* input_event) { return ::ImGui_ImplAndroid_HandleInputEvent(reinterpret_cast<const ::AInputEvent*>(input_event)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplAndroid_Shutdown(void) { ::ImGui_ImplAndroid_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplAndroid_NewFrame(void) { ::ImGui_ImplAndroid_NewFrame(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_opengl3.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_opengl3.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_opengl3.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplOpenGL3_Init(void) { return ::ImGui_ImplOpenGL3_Init(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplOpenGL3_InitEx(const char* glsl_version) { return ::ImGui_ImplOpenGL3_Init(glsl_version); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL3_Shutdown(void) { ::ImGui_ImplOpenGL3_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL3_NewFrame(void) { ::ImGui_ImplOpenGL3_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL3_RenderDrawData(cimgui::ImDrawData* draw_data) { ::ImGui_ImplOpenGL3_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplOpenGL3_CreateFontsTexture(void) { return ::ImGui_ImplOpenGL3_CreateFontsTexture(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL3_DestroyFontsTexture(void) { ::ImGui_ImplOpenGL3_DestroyFontsTexture(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplOpenGL3_CreateDeviceObjects(void) { return ::ImGui_ImplOpenGL3_CreateDeviceObjects(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL3_DestroyDeviceObjects(void) { ::ImGui_ImplOpenGL3_DestroyDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_allegro5.cpp
// dear imgui: Renderer + Platform Backend for Allegro 5 // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) // Implemented features: // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Clipboard support (from Allegro 5.1.12) // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Issues: // [ ] Renderer: The renderer is suboptimal as we need to convert vertices manually. // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // 2022-11-30: Renderer: Restoring using al_draw_indexed_prim() when Allegro version is >= 5.2.5. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). // 2022-01-17: Inputs: always calling io.AddKeyModsEvent() next and before key event (not in NewFrame) to fix input queue with very low framerates. // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2021-12-08: Renderer: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. // 2021-08-17: Calling io.AddFocusEvent() on ALLEGRO_EVENT_DISPLAY_SWITCH_OUT/ALLEGRO_EVENT_DISPLAY_SWITCH_IN events. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: Renderer: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: Change blending equation to preserve alpha in output buffer. // 2020-08-10: Inputs: Fixed horizontal mouse wheel direction. // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-05-11: Inputs: Don't filter character value from ALLEGRO_EVENT_KEY_CHAR before calling AddInputCharacter(). // 2019-04-30: Renderer: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. // 2018-11-30: Platform: Added touchscreen support. // 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window. // 2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12). // 2018-06-13: Renderer: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-06-13: Renderer: Stopped using al_draw_indexed_prim() as it is buggy in Allegro's DX9 backend. // 2018-06-13: Renderer: Backup/restore transform and clipping rectangle. // 2018-06-11: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. // 2018-04-18: Misc: Renamed file from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp. // 2018-04-18: Misc: Added support for 32-bit vertex indices to avoid conversion at runtime. Added imconfig_allegro5.h to enforce 32-bit indices when included from imgui.h. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplAllegro5_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_allegro5.h" #include <stdint.h> // uint64_t #include <cstring> // memcpy // Allegro #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> #ifdef _WIN32 #include <allegro5/allegro_windows.h> #endif #define ALLEGRO_HAS_CLIPBOARD ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12 #define ALLEGRO_HAS_DRAW_INDEXED_PRIM ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (2 << 16) | ( 5 << 8))) // DX9 implementation of al_draw_indexed_prim() got fixed in Allegro 5.2.5 // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #endif struct ImDrawVertAllegro { ImVec2 pos; ImVec2 uv; ALLEGRO_COLOR col; }; // FIXME-OPT: Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 float as well.. // FIXME-OPT: Consider inlining al_map_rgba()? // see https://github.com/liballeg/allegro5/blob/master/src/pixels.c#L554 // and https://github.com/liballeg/allegro5/blob/master/include/allegro5/internal/aintern_pixels.h #define DRAW_VERT_IMGUI_TO_ALLEGRO(DST, SRC) { (DST)->pos = (SRC)->pos; (DST)->uv = (SRC)->uv; unsigned char* c = (unsigned char*)&(SRC)->col; (DST)->col = al_map_rgba(c[0], c[1], c[2], c[3]); } // Allegro Data struct ImGui_ImplAllegro5_Data { ALLEGRO_DISPLAY* Display; ALLEGRO_BITMAP* Texture; double Time; ALLEGRO_MOUSE_CURSOR* MouseCursorInvisible; ALLEGRO_VERTEX_DECL* VertexDecl; char* ClipboardTextData; ImVector<ImDrawVertAllegro> BufVertices; ImVector<int> BufIndices; ImGui_ImplAllegro5_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. static ImGui_ImplAllegro5_Data* ImGui_ImplAllegro5_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplAllegro5_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } static void ImGui_ImplAllegro5_SetupRenderState(ImDrawData* draw_data) { // Setup blending al_set_separate_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA); // Setup orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). { float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; ALLEGRO_TRANSFORM transform; al_identity_transform(&transform); al_use_transform(&transform); al_orthographic_transform(&transform, L, T, 1.0f, R, B, -1.0f); al_use_projection_transform(&transform); } } // Render function. void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) return; // Backup Allegro state that will be modified ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); ALLEGRO_TRANSFORM last_transform = *al_get_current_transform(); ALLEGRO_TRANSFORM last_projection_transform = *al_get_current_projection_transform(); int last_clip_x, last_clip_y, last_clip_w, last_clip_h; al_get_clipping_rectangle(&last_clip_x, &last_clip_y, &last_clip_w, &last_clip_h); int last_blender_op, last_blender_src, last_blender_dst; al_get_blender(&last_blender_op, &last_blender_src, &last_blender_dst); // Setup desired render state ImGui_ImplAllegro5_SetupRenderState(draw_data); // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; ImVector<ImDrawVertAllegro>& vertices = bd->BufVertices; #if ALLEGRO_HAS_DRAW_INDEXED_PRIM vertices.resize(cmd_list->VtxBuffer.Size); for (int i = 0; i < cmd_list->VtxBuffer.Size; i++) { const ImDrawVert* src_v = &cmd_list->VtxBuffer[i]; ImDrawVertAllegro* dst_v = &vertices[i]; DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v); } const int* indices = nullptr; if (sizeof(ImDrawIdx) == 2) { // FIXME-OPT: Allegro doesn't support 16-bit indices. // You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices. // Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful. bd->BufIndices.resize(cmd_list->IdxBuffer.Size); for (int i = 0; i < cmd_list->IdxBuffer.Size; ++i) bd->BufIndices[i] = (int)cmd_list->IdxBuffer.Data[i]; indices = bd->BufIndices.Data; } else if (sizeof(ImDrawIdx) == 4) { indices = (const int*)cmd_list->IdxBuffer.Data; } #else // Allegro's implementation of al_draw_indexed_prim() for DX9 was broken until 5.2.5. Unindex buffers ourselves while converting vertex format. vertices.resize(cmd_list->IdxBuffer.Size); for (int i = 0; i < cmd_list->IdxBuffer.Size; i++) { const ImDrawVert* src_v = &cmd_list->VtxBuffer[cmd_list->IdxBuffer[i]]; ImDrawVertAllegro* dst_v = &vertices[i]; DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v); } #endif // Render command lists ImVec2 clip_off = draw_data->DisplayPos; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) ImGui_ImplAllegro5_SetupRenderState(draw_data); else pcmd->UserCallback(cmd_list, pcmd); } else { // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; // Apply scissor/clipping rectangle, Draw ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->GetTexID(); al_set_clipping_rectangle(clip_min.x, clip_min.y, clip_max.x - clip_min.x, clip_max.y - clip_min.y); #if ALLEGRO_HAS_DRAW_INDEXED_PRIM al_draw_indexed_prim(&vertices[0], bd->VertexDecl, texture, &indices[pcmd->IdxOffset], pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST); #else al_draw_prim(&vertices[0], bd->VertexDecl, texture, pcmd->IdxOffset, pcmd->IdxOffset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST); #endif } } } // Restore modified Allegro state al_set_blender(last_blender_op, last_blender_src, last_blender_dst); al_set_clipping_rectangle(last_clip_x, last_clip_y, last_clip_w, last_clip_h); al_use_transform(&last_transform); al_use_projection_transform(&last_projection_transform); } bool ImGui_ImplAllegro5_CreateDeviceObjects() { // Build texture atlas ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Create texture // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) int flags = al_get_new_bitmap_flags(); int fmt = al_get_new_bitmap_format(); al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE); ALLEGRO_BITMAP* img = al_create_bitmap(width, height); al_set_new_bitmap_flags(flags); al_set_new_bitmap_format(fmt); if (!img) return false; ALLEGRO_LOCKED_REGION* locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY); if (!locked_img) { al_destroy_bitmap(img); return false; } memcpy(locked_img->data, pixels, sizeof(int) * width * height); al_unlock_bitmap(img); // Convert software texture to hardware texture. ALLEGRO_BITMAP* cloned_img = al_clone_bitmap(img); al_destroy_bitmap(img); if (!cloned_img) return false; // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)cloned_img); bd->Texture = cloned_img; // Create an invisible mouse cursor // Because al_hide_mouse_cursor() seems to mess up with the actual inputs.. ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8, 8); bd->MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0); al_destroy_bitmap(mouse_cursor); return true; } void ImGui_ImplAllegro5_InvalidateDeviceObjects() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); if (bd->Texture) { io.Fonts->SetTexID(0); al_destroy_bitmap(bd->Texture); bd->Texture = nullptr; } if (bd->MouseCursorInvisible) { al_destroy_mouse_cursor(bd->MouseCursorInvisible); bd->MouseCursorInvisible = nullptr; } } #if ALLEGRO_HAS_CLIPBOARD static const char* ImGui_ImplAllegro5_GetClipboardText(ImGuiContext*) { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); if (bd->ClipboardTextData) al_free(bd->ClipboardTextData); bd->ClipboardTextData = al_get_clipboard_text(bd->Display); return bd->ClipboardTextData; } static void ImGui_ImplAllegro5_SetClipboardText(ImGuiContext*, const char* text) { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); al_set_clipboard_text(bd->Display, text); } #endif static ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code) { switch (key_code) { case ALLEGRO_KEY_TAB: return ImGuiKey_Tab; case ALLEGRO_KEY_LEFT: return ImGuiKey_LeftArrow; case ALLEGRO_KEY_RIGHT: return ImGuiKey_RightArrow; case ALLEGRO_KEY_UP: return ImGuiKey_UpArrow; case ALLEGRO_KEY_DOWN: return ImGuiKey_DownArrow; case ALLEGRO_KEY_PGUP: return ImGuiKey_PageUp; case ALLEGRO_KEY_PGDN: return ImGuiKey_PageDown; case ALLEGRO_KEY_HOME: return ImGuiKey_Home; case ALLEGRO_KEY_END: return ImGuiKey_End; case ALLEGRO_KEY_INSERT: return ImGuiKey_Insert; case ALLEGRO_KEY_DELETE: return ImGuiKey_Delete; case ALLEGRO_KEY_BACKSPACE: return ImGuiKey_Backspace; case ALLEGRO_KEY_SPACE: return ImGuiKey_Space; case ALLEGRO_KEY_ENTER: return ImGuiKey_Enter; case ALLEGRO_KEY_ESCAPE: return ImGuiKey_Escape; case ALLEGRO_KEY_QUOTE: return ImGuiKey_Apostrophe; case ALLEGRO_KEY_COMMA: return ImGuiKey_Comma; case ALLEGRO_KEY_MINUS: return ImGuiKey_Minus; case ALLEGRO_KEY_FULLSTOP: return ImGuiKey_Period; case ALLEGRO_KEY_SLASH: return ImGuiKey_Slash; case ALLEGRO_KEY_SEMICOLON: return ImGuiKey_Semicolon; case ALLEGRO_KEY_EQUALS: return ImGuiKey_Equal; case ALLEGRO_KEY_OPENBRACE: return ImGuiKey_LeftBracket; case ALLEGRO_KEY_BACKSLASH: return ImGuiKey_Backslash; case ALLEGRO_KEY_CLOSEBRACE: return ImGuiKey_RightBracket; case ALLEGRO_KEY_TILDE: return ImGuiKey_GraveAccent; case ALLEGRO_KEY_CAPSLOCK: return ImGuiKey_CapsLock; case ALLEGRO_KEY_SCROLLLOCK: return ImGuiKey_ScrollLock; case ALLEGRO_KEY_NUMLOCK: return ImGuiKey_NumLock; case ALLEGRO_KEY_PRINTSCREEN: return ImGuiKey_PrintScreen; case ALLEGRO_KEY_PAUSE: return ImGuiKey_Pause; case ALLEGRO_KEY_PAD_0: return ImGuiKey_Keypad0; case ALLEGRO_KEY_PAD_1: return ImGuiKey_Keypad1; case ALLEGRO_KEY_PAD_2: return ImGuiKey_Keypad2; case ALLEGRO_KEY_PAD_3: return ImGuiKey_Keypad3; case ALLEGRO_KEY_PAD_4: return ImGuiKey_Keypad4; case ALLEGRO_KEY_PAD_5: return ImGuiKey_Keypad5; case ALLEGRO_KEY_PAD_6: return ImGuiKey_Keypad6; case ALLEGRO_KEY_PAD_7: return ImGuiKey_Keypad7; case ALLEGRO_KEY_PAD_8: return ImGuiKey_Keypad8; case ALLEGRO_KEY_PAD_9: return ImGuiKey_Keypad9; case ALLEGRO_KEY_PAD_DELETE: return ImGuiKey_KeypadDecimal; case ALLEGRO_KEY_PAD_SLASH: return ImGuiKey_KeypadDivide; case ALLEGRO_KEY_PAD_ASTERISK: return ImGuiKey_KeypadMultiply; case ALLEGRO_KEY_PAD_MINUS: return ImGuiKey_KeypadSubtract; case ALLEGRO_KEY_PAD_PLUS: return ImGuiKey_KeypadAdd; case ALLEGRO_KEY_PAD_ENTER: return ImGuiKey_KeypadEnter; case ALLEGRO_KEY_PAD_EQUALS: return ImGuiKey_KeypadEqual; case ALLEGRO_KEY_LCTRL: return ImGuiKey_LeftCtrl; case ALLEGRO_KEY_LSHIFT: return ImGuiKey_LeftShift; case ALLEGRO_KEY_ALT: return ImGuiKey_LeftAlt; case ALLEGRO_KEY_LWIN: return ImGuiKey_LeftSuper; case ALLEGRO_KEY_RCTRL: return ImGuiKey_RightCtrl; case ALLEGRO_KEY_RSHIFT: return ImGuiKey_RightShift; case ALLEGRO_KEY_ALTGR: return ImGuiKey_RightAlt; case ALLEGRO_KEY_RWIN: return ImGuiKey_RightSuper; case ALLEGRO_KEY_MENU: return ImGuiKey_Menu; case ALLEGRO_KEY_0: return ImGuiKey_0; case ALLEGRO_KEY_1: return ImGuiKey_1; case ALLEGRO_KEY_2: return ImGuiKey_2; case ALLEGRO_KEY_3: return ImGuiKey_3; case ALLEGRO_KEY_4: return ImGuiKey_4; case ALLEGRO_KEY_5: return ImGuiKey_5; case ALLEGRO_KEY_6: return ImGuiKey_6; case ALLEGRO_KEY_7: return ImGuiKey_7; case ALLEGRO_KEY_8: return ImGuiKey_8; case ALLEGRO_KEY_9: return ImGuiKey_9; case ALLEGRO_KEY_A: return ImGuiKey_A; case ALLEGRO_KEY_B: return ImGuiKey_B; case ALLEGRO_KEY_C: return ImGuiKey_C; case ALLEGRO_KEY_D: return ImGuiKey_D; case ALLEGRO_KEY_E: return ImGuiKey_E; case ALLEGRO_KEY_F: return ImGuiKey_F; case ALLEGRO_KEY_G: return ImGuiKey_G; case ALLEGRO_KEY_H: return ImGuiKey_H; case ALLEGRO_KEY_I: return ImGuiKey_I; case ALLEGRO_KEY_J: return ImGuiKey_J; case ALLEGRO_KEY_K: return ImGuiKey_K; case ALLEGRO_KEY_L: return ImGuiKey_L; case ALLEGRO_KEY_M: return ImGuiKey_M; case ALLEGRO_KEY_N: return ImGuiKey_N; case ALLEGRO_KEY_O: return ImGuiKey_O; case ALLEGRO_KEY_P: return ImGuiKey_P; case ALLEGRO_KEY_Q: return ImGuiKey_Q; case ALLEGRO_KEY_R: return ImGuiKey_R; case ALLEGRO_KEY_S: return ImGuiKey_S; case ALLEGRO_KEY_T: return ImGuiKey_T; case ALLEGRO_KEY_U: return ImGuiKey_U; case ALLEGRO_KEY_V: return ImGuiKey_V; case ALLEGRO_KEY_W: return ImGuiKey_W; case ALLEGRO_KEY_X: return ImGuiKey_X; case ALLEGRO_KEY_Y: return ImGuiKey_Y; case ALLEGRO_KEY_Z: return ImGuiKey_Z; case ALLEGRO_KEY_F1: return ImGuiKey_F1; case ALLEGRO_KEY_F2: return ImGuiKey_F2; case ALLEGRO_KEY_F3: return ImGuiKey_F3; case ALLEGRO_KEY_F4: return ImGuiKey_F4; case ALLEGRO_KEY_F5: return ImGuiKey_F5; case ALLEGRO_KEY_F6: return ImGuiKey_F6; case ALLEGRO_KEY_F7: return ImGuiKey_F7; case ALLEGRO_KEY_F8: return ImGuiKey_F8; case ALLEGRO_KEY_F9: return ImGuiKey_F9; case ALLEGRO_KEY_F10: return ImGuiKey_F10; case ALLEGRO_KEY_F11: return ImGuiKey_F11; case ALLEGRO_KEY_F12: return ImGuiKey_F12; default: return ImGuiKey_None; } } bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); // Setup backend capabilities flags ImGui_ImplAllegro5_Data* bd = IM_NEW(ImGui_ImplAllegro5_Data)(); io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = io.BackendRendererName = "imgui_impl_allegro5"; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) bd->Display = display; // Create custom vertex declaration. // Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 floats. // 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) }, { 0, 0, 0 } }; bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); #if ALLEGRO_HAS_CLIPBOARD ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Platform_SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText; platform_io.Platform_GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText; #endif return true; } void ImGui_ImplAllegro5_Shutdown() { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplAllegro5_InvalidateDeviceObjects(); if (bd->VertexDecl) al_destroy_vertex_decl(bd->VertexDecl); if (bd->ClipboardTextData) al_free(bd->ClipboardTextData); io.BackendPlatformName = io.BackendRendererName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~ImGuiBackendFlags_HasMouseCursors; IM_DELETE(bd); } // ev->keyboard.modifiers seems always zero so using that... static void ImGui_ImplAllegro5_UpdateKeyModifiers() { ImGuiIO& io = ImGui::GetIO(); ALLEGRO_KEYBOARD_STATE keys; al_get_keyboard_state(&keys); io.AddKeyEvent(ImGuiMod_Ctrl, al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL)); io.AddKeyEvent(ImGuiMod_Shift, al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT)); io.AddKeyEvent(ImGuiMod_Alt, al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR)); io.AddKeyEvent(ImGuiMod_Super, al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN)); } // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?"); ImGuiIO& io = ImGui::GetIO(); switch (ev->type) { case ALLEGRO_EVENT_MOUSE_AXES: if (ev->mouse.display == bd->Display) { io.AddMousePosEvent(ev->mouse.x, ev->mouse.y); io.AddMouseWheelEvent(-ev->mouse.dw, ev->mouse.dz); } return true; case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: case ALLEGRO_EVENT_MOUSE_BUTTON_UP: if (ev->mouse.display == bd->Display && ev->mouse.button > 0 && ev->mouse.button <= 5) io.AddMouseButtonEvent(ev->mouse.button - 1, ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN); return true; case ALLEGRO_EVENT_TOUCH_MOVE: if (ev->touch.display == bd->Display) io.AddMousePosEvent(ev->touch.x, ev->touch.y); return true; case ALLEGRO_EVENT_TOUCH_BEGIN: case ALLEGRO_EVENT_TOUCH_END: case ALLEGRO_EVENT_TOUCH_CANCEL: if (ev->touch.display == bd->Display && ev->touch.primary) io.AddMouseButtonEvent(0, ev->type == ALLEGRO_EVENT_TOUCH_BEGIN); return true; case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY: if (ev->mouse.display == bd->Display) io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); return true; case ALLEGRO_EVENT_KEY_CHAR: if (ev->keyboard.display == bd->Display) if (ev->keyboard.unichar != 0) io.AddInputCharacter((unsigned int)ev->keyboard.unichar); return true; case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_UP: if (ev->keyboard.display == bd->Display) { ImGui_ImplAllegro5_UpdateKeyModifiers(); ImGuiKey key = ImGui_ImplAllegro5_KeyCodeToImGuiKey(ev->keyboard.keycode); io.AddKeyEvent(key, (ev->type == ALLEGRO_EVENT_KEY_DOWN)); io.SetKeyEventNativeData(key, ev->keyboard.keycode, -1); // To support legacy indexing (<1.87 user code) } return true; case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT: if (ev->display.source == bd->Display) io.AddFocusEvent(false); return true; case ALLEGRO_EVENT_DISPLAY_SWITCH_IN: if (ev->display.source == bd->Display) { io.AddFocusEvent(true); #if defined(ALLEGRO_UNSTABLE) al_clear_keyboard_state(bd->Display); #endif } return true; } return false; } static void ImGui_ImplAllegro5_UpdateMouseCursor() { ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return; ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor al_set_mouse_cursor(bd->Display, bd->MouseCursorInvisible); } else { ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT; switch (imgui_cursor) { case ImGuiMouseCursor_TextInput: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break; case ImGuiMouseCursor_ResizeAll: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break; case ImGuiMouseCursor_ResizeNS: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break; case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break; case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break; case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break; case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break; } al_set_system_mouse_cursor(bd->Display, cursor_id); } } void ImGui_ImplAllegro5_NewFrame() { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?"); if (!bd->Texture) ImGui_ImplAllegro5_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; w = al_get_display_width(bd->Display); h = al_get_display_height(bd->Display); io.DisplaySize = ImVec2((float)w, (float)h); // Setup time step double current_time = al_get_time(); io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f); bd->Time = current_time; // Setup mouse cursor shape ImGui_ImplAllegro5_UpdateMouseCursor(); } //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_opengl3.h
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline // - Desktop GL: 2.x 3.x 4.x // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! // [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). // About WebGL/ES: // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. // - This is done automatically on iOS, Android and Emscripten targets. // - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // About GLSL version: // The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string. // On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" // Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr); IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); // (Optional) Called by Init/NewFrame/Shutdown IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); // Configuration flags to add in your imconfig file: //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten) //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android) // You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. #if !defined(IMGUI_IMPL_OPENGL_ES2) \ && !defined(IMGUI_IMPL_OPENGL_ES3) // Try to detect GLES on matching platforms #if defined(__APPLE__) #include <TargetConditionals.h> #endif #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" #elif defined(__EMSCRIPTEN__) || defined(__amigaos4__) #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" #else // Otherwise imgui_impl_opengl3_loader.h will be used. #endif #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx11.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_dx11.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_dx11.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX11_Init(cimgui::ID3D11Device* device, cimgui::ID3D11DeviceContext* device_context) { return ::ImGui_ImplDX11_Init(reinterpret_cast<::ID3D11Device*>(device), reinterpret_cast<::ID3D11DeviceContext*>(device_context)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX11_Shutdown(void) { ::ImGui_ImplDX11_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX11_NewFrame(void) { ::ImGui_ImplDX11_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX11_RenderDrawData(cimgui::ImDrawData* draw_data) { ::ImGui_ImplDX11_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplDX11_InvalidateDeviceObjects(void) { ::ImGui_ImplDX11_InvalidateDeviceObjects(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplDX11_CreateDeviceObjects(void) { return ::ImGui_ImplDX11_CreateDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_opengl2.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_opengl2.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_opengl2.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplOpenGL2_Init(void) { return ::ImGui_ImplOpenGL2_Init(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL2_Shutdown(void) { ::ImGui_ImplOpenGL2_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL2_NewFrame(void) { ::ImGui_ImplOpenGL2_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL2_RenderDrawData(cimgui::ImDrawData* draw_data) { ::ImGui_ImplOpenGL2_RenderDrawData(reinterpret_cast<::ImDrawData*>(draw_data)); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplOpenGL2_CreateFontsTexture(void) { return ::ImGui_ImplOpenGL2_CreateFontsTexture(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL2_DestroyFontsTexture(void) { ::ImGui_ImplOpenGL2_DestroyFontsTexture(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplOpenGL2_CreateDeviceObjects(void) { return ::ImGui_ImplOpenGL2_CreateDeviceObjects(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplOpenGL2_DestroyDeviceObjects(void) { ::ImGui_ImplOpenGL2_DestroyDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdl2.cpp
// dear imgui: Platform Backend for SDL2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) // (Prefer SDL 2.0.5+ for full feature support.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO: // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn // 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*. // 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853) // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions. // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library. // 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode(). // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) // 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) // 2023-02-07: Implement IME handler (io.SetPlatformImeDataFn will call SDL_SetTextInputRect()/SDL_StartTextInput()). // 2023-02-07: *BREAKING CHANGE* Renamed this backend file from imgui_impl_sdl.cpp/.h to imgui_impl_sdl2.cpp/.h in prevision for the future release of SDL3. // 2023-02-02: Avoid calling SDL_SetCursor() when cursor has not changed, as the function is surprisingly costly on Mac with latest SDL (may be fixed in next SDL version). // 2023-02-02: Added support for SDL 2.0.18+ preciseX/preciseY mouse wheel data for smooth scrolling + Scaling X value on Emscripten (bug?). (#4019, #6096) // 2023-02-02: Removed SDL_MOUSEWHEEL value clamping, as values seem correct in latest Emscripten. (#4019) // 2023-02-01: Flipping SDL_MOUSEWHEEL 'wheel.x' value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463) // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-09-26: Inputs: Disable SDL 2.0.22 new "auto capture" (SDL_HINT_MOUSE_AUTO_CAPTURE) which prevents drag and drop across windows for multi-viewport support + don't capture when drag and dropping. (#5710) // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). // 2022-03-22: Inputs: Fix mouse position issues when dragging outside of boundaries. SDL_CaptureMouse() erroneously still gives out LEAVE events when hovering OS decorations. // 2022-03-22: Inputs: Added support for extra mouse buttons (SDL_BUTTON_X1/SDL_BUTTON_X2). // 2022-02-04: Added SDL_Renderer* parameter to ImGui_ImplSDL2_InitForSDLRenderer(), so we can use SDL_GetRendererOutputSize() instead of SDL_GL_GetDrawableSize() when bound to a SDL_Renderer. // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). // 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates. // 2022-01-12: Update mouse inputs using SDL_MOUSEMOTION/SDL_WINDOWEVENT_LEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API. // 2022-01-12: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST. // 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+) // 2021-06-29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950) // 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends. // 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2). // 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state). // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. // 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application). // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. // 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'. // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls. // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. // 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples. // 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter. // 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText). // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. // 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. // 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS). // 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS. // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert. // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. #include "imgui.h" #ifndef IMGUI_DISABLE #include "imgui_impl_sdl2.h" // Clang warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #endif // SDL #include <SDL.h> #include <SDL_syswm.h> #ifdef __APPLE__ #include <TargetConditionals.h> #endif #ifdef __EMSCRIPTEN__ #include <emscripten/em_js.h> #endif #if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 #else #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 #endif #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) // SDL Data struct ImGui_ImplSDL2_Data { SDL_Window* Window; Uint32 WindowID; SDL_Renderer* Renderer; Uint64 Time; char* ClipboardTextData; // Mouse handling Uint32 MouseWindowID; int MouseButtonsDown; SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; SDL_Cursor* MouseLastCursor; int MouseLastLeaveFrame; bool MouseCanUseGlobalState; // Gamepad handling ImVector<SDL_GameController*> Gamepads; ImGui_ImplSDL2_GamepadMode GamepadMode; bool WantUpdateGamepadsList; ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } // Functions static const char* ImGui_ImplSDL2_GetClipboardText(ImGuiContext*) { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); bd->ClipboardTextData = SDL_GetClipboardText(); return bd->ClipboardTextData; } static void ImGui_ImplSDL2_SetClipboardText(ImGuiContext*, const char* text) { SDL_SetClipboardText(text); } // Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow(). static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData* data) { if (data->WantVisible) { SDL_Rect r; r.x = (int)data->InputPos.x; r.y = (int)data->InputPos.y; r.w = 1; r.h = (int)data->InputLineHeight; SDL_SetTextInputRect(&r); } } static ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode) { IM_UNUSED(scancode); switch (keycode) { case SDLK_TAB: return ImGuiKey_Tab; case SDLK_LEFT: return ImGuiKey_LeftArrow; case SDLK_RIGHT: return ImGuiKey_RightArrow; case SDLK_UP: return ImGuiKey_UpArrow; case SDLK_DOWN: return ImGuiKey_DownArrow; case SDLK_PAGEUP: return ImGuiKey_PageUp; case SDLK_PAGEDOWN: return ImGuiKey_PageDown; case SDLK_HOME: return ImGuiKey_Home; case SDLK_END: return ImGuiKey_End; case SDLK_INSERT: return ImGuiKey_Insert; case SDLK_DELETE: return ImGuiKey_Delete; case SDLK_BACKSPACE: return ImGuiKey_Backspace; case SDLK_SPACE: return ImGuiKey_Space; case SDLK_RETURN: return ImGuiKey_Enter; case SDLK_ESCAPE: return ImGuiKey_Escape; case SDLK_QUOTE: return ImGuiKey_Apostrophe; case SDLK_COMMA: return ImGuiKey_Comma; case SDLK_MINUS: return ImGuiKey_Minus; case SDLK_PERIOD: return ImGuiKey_Period; case SDLK_SLASH: return ImGuiKey_Slash; case SDLK_SEMICOLON: return ImGuiKey_Semicolon; case SDLK_EQUALS: return ImGuiKey_Equal; case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; case SDLK_BACKSLASH: return ImGuiKey_Backslash; case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent; case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; case SDLK_PAUSE: return ImGuiKey_Pause; case SDLK_KP_0: return ImGuiKey_Keypad0; case SDLK_KP_1: return ImGuiKey_Keypad1; case SDLK_KP_2: return ImGuiKey_Keypad2; case SDLK_KP_3: return ImGuiKey_Keypad3; case SDLK_KP_4: return ImGuiKey_Keypad4; case SDLK_KP_5: return ImGuiKey_Keypad5; case SDLK_KP_6: return ImGuiKey_Keypad6; case SDLK_KP_7: return ImGuiKey_Keypad7; case SDLK_KP_8: return ImGuiKey_Keypad8; case SDLK_KP_9: return ImGuiKey_Keypad9; case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal; case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide; case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract; case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd; case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter; case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual; case SDLK_LCTRL: return ImGuiKey_LeftCtrl; case SDLK_LSHIFT: return ImGuiKey_LeftShift; case SDLK_LALT: return ImGuiKey_LeftAlt; case SDLK_LGUI: return ImGuiKey_LeftSuper; case SDLK_RCTRL: return ImGuiKey_RightCtrl; case SDLK_RSHIFT: return ImGuiKey_RightShift; case SDLK_RALT: return ImGuiKey_RightAlt; case SDLK_RGUI: return ImGuiKey_RightSuper; case SDLK_APPLICATION: return ImGuiKey_Menu; case SDLK_0: return ImGuiKey_0; case SDLK_1: return ImGuiKey_1; case SDLK_2: return ImGuiKey_2; case SDLK_3: return ImGuiKey_3; case SDLK_4: return ImGuiKey_4; case SDLK_5: return ImGuiKey_5; case SDLK_6: return ImGuiKey_6; case SDLK_7: return ImGuiKey_7; case SDLK_8: return ImGuiKey_8; case SDLK_9: return ImGuiKey_9; case SDLK_a: return ImGuiKey_A; case SDLK_b: return ImGuiKey_B; case SDLK_c: return ImGuiKey_C; case SDLK_d: return ImGuiKey_D; case SDLK_e: return ImGuiKey_E; case SDLK_f: return ImGuiKey_F; case SDLK_g: return ImGuiKey_G; case SDLK_h: return ImGuiKey_H; case SDLK_i: return ImGuiKey_I; case SDLK_j: return ImGuiKey_J; case SDLK_k: return ImGuiKey_K; case SDLK_l: return ImGuiKey_L; case SDLK_m: return ImGuiKey_M; case SDLK_n: return ImGuiKey_N; case SDLK_o: return ImGuiKey_O; case SDLK_p: return ImGuiKey_P; case SDLK_q: return ImGuiKey_Q; case SDLK_r: return ImGuiKey_R; case SDLK_s: return ImGuiKey_S; case SDLK_t: return ImGuiKey_T; case SDLK_u: return ImGuiKey_U; case SDLK_v: return ImGuiKey_V; case SDLK_w: return ImGuiKey_W; case SDLK_x: return ImGuiKey_X; case SDLK_y: return ImGuiKey_Y; case SDLK_z: return ImGuiKey_Z; case SDLK_F1: return ImGuiKey_F1; case SDLK_F2: return ImGuiKey_F2; case SDLK_F3: return ImGuiKey_F3; case SDLK_F4: return ImGuiKey_F4; case SDLK_F5: return ImGuiKey_F5; case SDLK_F6: return ImGuiKey_F6; case SDLK_F7: return ImGuiKey_F7; case SDLK_F8: return ImGuiKey_F8; case SDLK_F9: return ImGuiKey_F9; case SDLK_F10: return ImGuiKey_F10; case SDLK_F11: return ImGuiKey_F11; case SDLK_F12: return ImGuiKey_F12; case SDLK_F13: return ImGuiKey_F13; case SDLK_F14: return ImGuiKey_F14; case SDLK_F15: return ImGuiKey_F15; case SDLK_F16: return ImGuiKey_F16; case SDLK_F17: return ImGuiKey_F17; case SDLK_F18: return ImGuiKey_F18; case SDLK_F19: return ImGuiKey_F19; case SDLK_F20: return ImGuiKey_F20; case SDLK_F21: return ImGuiKey_F21; case SDLK_F22: return ImGuiKey_F22; case SDLK_F23: return ImGuiKey_F23; case SDLK_F24: return ImGuiKey_F24; case SDLK_AC_BACK: return ImGuiKey_AppBack; case SDLK_AC_FORWARD: return ImGuiKey_AppForward; default: break; } return ImGuiKey_None; } static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) { ImGuiIO& io = ImGui::GetIO(); io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0); io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0); io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0); io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0); } static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id) { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); return (window_id == bd->WindowID) ? ImGui::GetMainViewport() : NULL; } // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. // If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?"); ImGuiIO& io = ImGui::GetIO(); switch (event->type) { case SDL_MOUSEMOTION: { if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == NULL) return false; ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); return true; } case SDL_MOUSEWHEEL: { if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == NULL) return false; //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); #if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten! float wheel_x = -event->wheel.preciseX; float wheel_y = event->wheel.preciseY; #else float wheel_x = -(float)event->wheel.x; float wheel_y = (float)event->wheel.y; #endif #ifdef __EMSCRIPTEN__ wheel_x /= 100.0f; #endif io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMouseWheelEvent(wheel_x, wheel_y); return true; } case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == NULL) return false; int mouse_button = -1; if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; } if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; } if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; } if (mouse_button == -1) break; io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN)); bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button)); return true; } case SDL_TEXTINPUT: { if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == NULL) return false; io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_KEYDOWN: case SDL_KEYUP: { if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == NULL) return false; ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode); io.AddKeyEvent(key, (event->type == SDL_KEYDOWN)); io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. return true; } case SDL_WINDOWEVENT: { if (ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID) == NULL) return false; // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right. // - However we won't get a correct LEAVE event for a captured window. // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details. Uint8 window_event = event->window.event; if (window_event == SDL_WINDOWEVENT_ENTER) { bd->MouseWindowID = event->window.windowID; bd->MouseLastLeaveFrame = 0; } if (window_event == SDL_WINDOWEVENT_LEAVE) bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1; if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED) io.AddFocusEvent(true); else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST) io.AddFocusEvent(false); return true; } case SDL_CONTROLLERDEVICEADDED: case SDL_CONTROLLERDEVICEREMOVED: { bd->WantUpdateGamepadsList = true; return true; } } return false; } #ifdef __EMSCRIPTEN__ EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); #endif static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) { ImGuiIO& io = ImGui::GetIO(); IMGUI_CHECKVERSION(); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); // Check and store if we are on a SDL backend that supports global mouse position // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) bool mouse_can_use_global_state = false; #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE const char* sdl_backend = SDL_GetCurrentVideoDriver(); const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) mouse_can_use_global_state = true; #endif // Setup backend capabilities flags ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)(); io.BackendPlatformUserData = (void*)bd; io.BackendPlatformName = "imgui_impl_sdl2"; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->Window = window; bd->WindowID = SDL_GetWindowID(window); bd->Renderer = renderer; bd->MouseCanUseGlobalState = mouse_can_use_global_state; ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; platform_io.Platform_ClipboardUserData = nullptr; platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData; #ifdef __EMSCRIPTEN__ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; }; #endif // Gamepad handling bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst; bd->WantUpdateGamepadsList = true; // Load mouse cursors bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL); bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS); bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE); bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO); // Set platform dependent data in viewport // Our mouse update function expect PlatformHandle to be filled for the main viewport ImGuiViewport* main_viewport = ImGui::GetMainViewport(); main_viewport->PlatformHandle = (void*)(intptr_t)bd->WindowID; main_viewport->PlatformHandleRaw = nullptr; SDL_SysWMinfo info; SDL_VERSION(&info.version); if (SDL_GetWindowWMInfo(window, &info)) { #if defined(SDL_VIDEO_DRIVER_WINDOWS) main_viewport->PlatformHandleRaw = (void*)info.info.win.window; #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) main_viewport->PlatformHandleRaw = (void*)info.info.cocoa.window; #endif } // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: // you can ignore SDL_MOUSEBUTTONDOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED) #ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); #endif // From 2.0.18: Enable native IME. // IMPORTANT: This is used at the time of SDL_CreateWindow() so this will only affects secondary windows, if any. // For the main window to be affected, your application needs to call this manually before calling SDL_CreateWindow(). #ifdef SDL_HINT_IME_SHOW_UI SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); #endif // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710) #ifdef SDL_HINT_MOUSE_AUTO_CAPTURE SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); #endif (void)sdl_gl_context; // Unused in 'master' branch. return true; } bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) { return ImGui_ImplSDL2_Init(window, nullptr, sdl_gl_context); } bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) { #if !SDL_HAS_VULKAN IM_ASSERT(0 && "Unsupported"); #endif return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) { #if !defined(_WIN32) IM_ASSERT(0 && "Unsupported"); #endif return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window) { return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) { return ImGui_ImplSDL2_Init(window, renderer, nullptr); } bool ImGui_ImplSDL2_InitForOther(SDL_Window* window) { return ImGui_ImplSDL2_Init(window, nullptr, nullptr); } static void ImGui_ImplSDL2_CloseGamepads(); void ImGui_ImplSDL2_Shutdown() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); if (bd->ClipboardTextData) SDL_free(bd->ClipboardTextData); for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) SDL_FreeCursor(bd->MouseCursors[cursor_n]); ImGui_ImplSDL2_CloseGamepads(); io.BackendPlatformName = nullptr; io.BackendPlatformUserData = nullptr; io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); IM_DELETE(bd); } static void ImGui_ImplSDL2_UpdateMouseData() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); // We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below) #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE); SDL_Window* focused_window = SDL_GetKeyboardFocus(); const bool is_app_focused = (bd->Window == focused_window); #else const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only #endif if (is_app_focused) { // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) if (io.WantSetMousePos) SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); // (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured) if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) { int window_x, window_y, mouse_x_global, mouse_y_global; SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); SDL_GetWindowPosition(bd->Window, &window_x, &window_y); io.AddMousePosEvent((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y)); } } } static void ImGui_ImplSDL2_UpdateMouseCursor() { ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return; ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor SDL_ShowCursor(SDL_FALSE); } else { // Show OS mouse cursor SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; if (bd->MouseLastCursor != expected_cursor) { SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) bd->MouseLastCursor = expected_cursor; } SDL_ShowCursor(SDL_TRUE); } } static void ImGui_ImplSDL2_CloseGamepads() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); if (bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual) for (SDL_GameController* gamepad : bd->Gamepads) SDL_GameControllerClose(gamepad); bd->Gamepads.resize(0); } void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array, int manual_gamepads_count) { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ImGui_ImplSDL2_CloseGamepads(); if (mode == ImGui_ImplSDL2_GamepadMode_Manual) { IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0); for (int n = 0; n < manual_gamepads_count; n++) bd->Gamepads.push_back(manual_gamepads_array[n]); } else { IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0); bd->WantUpdateGamepadsList = true; } bd->GamepadMode = mode; } static void ImGui_ImplSDL2_UpdateGamepadButton(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerButton button_no) { bool merged_value = false; for (SDL_GameController* gamepad : bd->Gamepads) merged_value |= SDL_GameControllerGetButton(gamepad, button_no) != 0; io.AddKeyEvent(key, merged_value); } static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } static void ImGui_ImplSDL2_UpdateGamepadAnalog(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerAxis axis_no, float v0, float v1) { float merged_value = 0.0f; for (SDL_GameController* gamepad : bd->Gamepads) { float vn = Saturate((float)(SDL_GameControllerGetAxis(gamepad, axis_no) - v0) / (float)(v1 - v0)); if (merged_value < vn) merged_value = vn; } io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value); } static void ImGui_ImplSDL2_UpdateGamepads() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); // Update list of controller(s) to use if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual) { ImGui_ImplSDL2_CloseGamepads(); int joystick_count = SDL_NumJoysticks(); for (int n = 0; n < joystick_count; n++) if (SDL_IsGameController(n)) if (SDL_GameController* gamepad = SDL_GameControllerOpen(n)) { bd->Gamepads.push_back(gamepad); if (bd->GamepadMode == ImGui_ImplSDL2_GamepadMode_AutoFirst) break; } bd->WantUpdateGamepadsList = false; } // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) return; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; if (bd->Gamepads.Size == 0) return; io.BackendFlags |= ImGuiBackendFlags_HasGamepad; // Update gamepad inputs const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value. ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767); } void ImGui_ImplSDL2_NewFrame() { ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?"); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; int display_w, display_h; SDL_GetWindowSize(bd->Window, &w, &h); if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) w = h = 0; if (bd->Renderer != nullptr) SDL_GetRendererOutputSize(bd->Renderer, &display_w, &display_h); else SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) static Uint64 frequency = SDL_GetPerformanceFrequency(); Uint64 current_time = SDL_GetPerformanceCounter(); if (current_time <= bd->Time) current_time = bd->Time + 1; io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); bd->Time = current_time; if (bd->MouseLastLeaveFrame && bd->MouseLastLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) { bd->MouseWindowID = 0; bd->MouseLastLeaveFrame = 0; io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); } ImGui_ImplSDL2_UpdateMouseData(); ImGui_ImplSDL2_UpdateMouseCursor(); // Update game controllers (if enabled and available) ImGui_ImplSDL2_UpdateGamepads(); } //----------------------------------------------------------------------------- #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_vulkan.h
// dear imgui: Renderer Backend for Vulkan // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: // [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. // See imgui_impl_vulkan.cpp file for details. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering backend in your engine/app. // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. // Read comments in imgui_impl_vulkan.h. #pragma once #ifndef IMGUI_DISABLE #include "imgui.h" // IMGUI_IMPL_API // [Configuration] in order to use a custom Vulkan function loader: // (1) You'll need to disable default Vulkan function prototypes. // We provide a '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' convenience configuration flag. // In order to make sure this is visible from the imgui_impl_vulkan.cpp compilation unit: // - Add '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' in your imconfig.h file // - Or as a compilation flag in your build system // - Or uncomment here (not recommended because you'd be modifying imgui sources!) // - Do not simply add it in a .cpp file! // (2) Call ImGui_ImplVulkan_LoadFunctions() before ImGui_ImplVulkan_Init() with your custom function. // If you have no idea what this is, leave it alone! //#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES // Convenience support for Volk // (you can also technically use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().) //#define IMGUI_IMPL_VULKAN_USE_VOLK #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) #define VK_NO_PROTOTYPES #endif #if defined(VK_USE_PLATFORM_WIN32_KHR) && !defined(NOMINMAX) #define NOMINMAX #endif // Vulkan includes #ifdef IMGUI_IMPL_VULKAN_USE_VOLK #include <volk.h> #else #include <vulkan/vulkan.h> #endif #if defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering) #define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #endif // Initialization data, for ImGui_ImplVulkan_Init() // - VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, // and must contain a pool size large enough to hold an ImGui VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptor. // - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. // [Please zero-clear before use!] struct ImGui_ImplVulkan_InitInfo { VkInstance Instance; VkPhysicalDevice PhysicalDevice; VkDevice Device; uint32_t QueueFamily; VkQueue Queue; VkDescriptorPool DescriptorPool; // See requirements in note above VkRenderPass RenderPass; // Ignored if using dynamic rendering uint32_t MinImageCount; // >= 2 uint32_t ImageCount; // >= MinImageCount VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT // (Optional) VkPipelineCache PipelineCache; uint32_t Subpass; // (Optional) Dynamic Rendering // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. bool UseDynamicRendering; #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; #endif // (Optional) Allocation, Debugging const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. }; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontsTexture(); IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) // Register a texture (VkDescriptorSet == ImTextureID) // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem // Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. IMGUI_IMPL_API VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout); IMGUI_IMPL_API void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set); // Optional: load Vulkan functions with a custom function loader // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr); //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) //------------------------------------------------------------------------- // You probably do NOT need to use or care about those functions. // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. // 2) the multi-viewport / platform window implementation needs them internally. // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, // but it is too much code to duplicate everywhere so we exceptionally expose them. // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) //------------------------------------------------------------------------- struct ImGui_ImplVulkanH_Frame; struct ImGui_ImplVulkanH_Window; // Helpers IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); // Helper structure to hold the data needed by one rendering frame // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) // [Please zero-clear before use!] struct ImGui_ImplVulkanH_Frame { VkCommandPool CommandPool; VkCommandBuffer CommandBuffer; VkFence Fence; VkImage Backbuffer; VkImageView BackbufferView; VkFramebuffer Framebuffer; }; struct ImGui_ImplVulkanH_FrameSemaphores { VkSemaphore ImageAcquiredSemaphore; VkSemaphore RenderCompleteSemaphore; }; // Helper structure to hold the data needed by one rendering context into one OS window // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) struct ImGui_ImplVulkanH_Window { int Width; int Height; VkSwapchainKHR Swapchain; VkSurfaceKHR Surface; VkSurfaceFormatKHR SurfaceFormat; VkPresentModeKHR PresentMode; VkRenderPass RenderPass; VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo bool UseDynamicRendering; bool ClearEnable; VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) ImGui_ImplVulkanH_Frame* Frames; ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; ImGui_ImplVulkanH_Window() { memset((void*)this, 0, sizeof(*this)); PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this. ClearEnable = true; } }; #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_wgpu.cpp
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings #include "imgui.h" #include "imgui_impl_wgpu.h" #include <stdio.h> // Wrap this in a namespace to keep it separate from the C++ API namespace cimgui { #include "cimgui_impl_wgpu.h" } // By-value struct conversions // Function stubs #ifndef IMGUI_DISABLE CIMGUI_IMPL_API bool cimgui::cImGui_ImplWGPU_Init(cimgui::ImGui_ImplWGPU_InitInfo* init_info) { return ::ImGui_ImplWGPU_Init(reinterpret_cast<::ImGui_ImplWGPU_InitInfo*>(init_info)); } CIMGUI_IMPL_API void cimgui::cImGui_ImplWGPU_Shutdown(void) { ::ImGui_ImplWGPU_Shutdown(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplWGPU_NewFrame(void) { ::ImGui_ImplWGPU_NewFrame(); } CIMGUI_IMPL_API void cimgui::cImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder) { ::ImGui_ImplWGPU_RenderDrawData(draw_data, pass_encoder); } CIMGUI_IMPL_API void cimgui::cImGui_ImplWGPU_InvalidateDeviceObjects(void) { ::ImGui_ImplWGPU_InvalidateDeviceObjects(); } CIMGUI_IMPL_API bool cimgui::cImGui_ImplWGPU_CreateDeviceObjects(void) { return ::ImGui_ImplWGPU_CreateDeviceObjects(); } #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx12.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for DirectX12 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // See imgui_impl_dx12.cpp file for details. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE #include <dxgiformat.h> typedef struct ID3D12Device ID3D12Device; typedef struct ID3D12DescriptorHeap ID3D12DescriptorHeap; typedef struct ID3D12GraphicsCommandList ID3D12GraphicsCommandList; typedef struct D3D12_CPU_DESCRIPTOR_HANDLE D3D12_CPU_DESCRIPTOR_HANDLE; typedef struct D3D12_GPU_DESCRIPTOR_HANDLE D3D12_GPU_DESCRIPTOR_HANDLE; // Follow "Getting Started" link and check examples/ folder to learn about using backends! // cmd_list is the command list that the implementation will use to render imgui draw lists. // Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate // render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle. typedef struct ImDrawData_t ImDrawData; // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture. CIMGUI_IMPL_API bool cImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle); CIMGUI_IMPL_API void cImGui_ImplDX12_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplDX12_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list); // Use if you want to reset your rendering device without losing Dear ImGui state. CIMGUI_IMPL_API void cImGui_ImplDX12_InvalidateDeviceObjects(void); CIMGUI_IMPL_API bool cImGui_ImplDX12_CreateDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_sdlrenderer3.h
// dear imgui: Renderer Backend for SDL_Renderer for SDL3 // (Requires: SDL 3.0.0+) // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**) // Note how SDL_Renderer is an _optional_ component of SDL3. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and // it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct SDL_Renderer; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer); // Called by Init/NewFrame/Shutdown IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateFontsTexture(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_glfw.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) // Implemented features: // [X] Platform: Clipboard support. // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct GLFWwindow GLFWwindow; typedef struct GLFWmonitor GLFWmonitor; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks); CIMGUI_IMPL_API bool cImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks); CIMGUI_IMPL_API bool cImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks); CIMGUI_IMPL_API void cImGui_ImplGlfw_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplGlfw_NewFrame(void); // Emscripten related initialization phase methods (call after ImGui_ImplGlfw_InitForOpenGL) #ifdef __EMSCRIPTEN__ CIMGUI_IMPL_API void cImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector); //static inline void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector) { ImGui_ImplGlfw_InstallEmscriptenCallbacks(nullptr, canvas_selector); } } // Renamed in 1.91.0 #endif // #ifdef __EMSCRIPTEN__ // GLFW callbacks install // - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any. // - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks. CIMGUI_IMPL_API void cImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window); CIMGUI_IMPL_API void cImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window); // GFLW callbacks options: // - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user) CIMGUI_IMPL_API void cImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows); // GLFW callbacks (individual callbacks to call yourself if you didn't install callbacks) CIMGUI_IMPL_API void cImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84 CIMGUI_IMPL_API void cImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84 CIMGUI_IMPL_API void cImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87 CIMGUI_IMPL_API void cImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); CIMGUI_IMPL_API void cImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); CIMGUI_IMPL_API void cImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); CIMGUI_IMPL_API void cImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); CIMGUI_IMPL_API void cImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event); // GLFW helpers CIMGUI_IMPL_API void cImGui_ImplGlfw_Sleep(int milliseconds); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/cimgui_impl_dx11.h
// THIS FILE HAS BEEN AUTO-GENERATED BY THE 'DEAR BINDINGS' GENERATOR. // **DO NOT EDIT DIRECTLY** // https://github.com/dearimgui/dear_bindings // dear imgui: Renderer Backend for DirectX11 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #ifdef __cplusplus extern "C" { #endif #include "cimgui.h" #ifndef IMGUI_DISABLE typedef struct ID3D11Device ID3D11Device; typedef struct ID3D11DeviceContext ID3D11DeviceContext; typedef struct ImDrawData_t ImDrawData; // Follow "Getting Started" link and check examples/ folder to learn about using backends! CIMGUI_IMPL_API bool cImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context); CIMGUI_IMPL_API void cImGui_ImplDX11_Shutdown(void); CIMGUI_IMPL_API void cImGui_ImplDX11_NewFrame(void); CIMGUI_IMPL_API void cImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. CIMGUI_IMPL_API void cImGui_ImplDX11_InvalidateDeviceObjects(void); CIMGUI_IMPL_API bool cImGui_ImplDX11_CreateDeviceObjects(void); #endif// #ifndef IMGUI_DISABLE #ifdef __cplusplus } // End of extern "C" block #endif
0
repos/cimgui.zig/cimgui
repos/cimgui.zig/cimgui/backends/imgui_impl_dx9.h
// dear imgui: Renderer Backend for DirectX9 // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Learn about Dear ImGui: // - FAQ https://dearimgui.com/faq // - Getting Started https://dearimgui.com/getting-started // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). // - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API #ifndef IMGUI_DISABLE struct IDirect3DDevice9; // Follow "Getting Started" link and check examples/ folder to learn about using backends! IMGUI_IMPL_API bool ImGui_ImplDX9_Init(IDirect3DDevice9* device); IMGUI_IMPL_API void ImGui_ImplDX9_Shutdown(); IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame(); IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); #endif // #ifndef IMGUI_DISABLE
0
repos/cimgui.zig
repos/cimgui.zig/examples/build.zig.zon
.{ .name = "examples", .version = "1.0.0", .dependencies = .{ .cimgui = .{ .path = "..", }, }, .paths = .{ "", }, }
0
repos/cimgui.zig
repos/cimgui.zig/examples/build.zig
const std = @import ("std"); const cimgui = @import ("cimgui"); const Platform = cimgui.Platform; const Renderer = cimgui.Renderer; fn platform (dir_name: [] const u8) !Platform { return if (std.mem.indexOf (u8, dir_name, "_glfw") != null) .GLFW else error.UnknownPlatformBackend; } fn renderer (dir_name: [] const u8) !Renderer { return if (std.mem.indexOf (u8, dir_name, "_vulkan") != null) .Vulkan else error.UnknownRendererBackend; } pub fn build (builder: *std.Build) !void { const target = builder.standardTargetOptions (.{}); const optimize = .Debug; const pattern = builder.option ([] const u8, "pattern", "Simple & stupid indexOf pattern matching to select examples") orelse ""; var examples_dir = try builder.build_root.handle.openDir (".", .{ .iterate = true, }); defer examples_dir.close (); var exe: *std.Build.Step.Compile = undefined; var cimgui_dep: *std.Build.Dependency = undefined; var it = examples_dir.iterate (); while (try it.next ()) |*entry| { if (entry.kind == .directory and std.mem.startsWith (u8, entry.name, "example_") and std.mem.indexOf (u8, entry.name, pattern) != null) { exe = builder.addExecutable (.{ .name = entry.name, .root_source_file = .{ .cwd_relative = try builder.build_root.join ( builder.allocator, &.{ entry.name, "main.zig", }), }, .target = target, .optimize = optimize, }); cimgui_dep = builder.dependency ("cimgui", .{ .target = target, .optimize = optimize, .platform = try platform (entry.name), .renderer = try renderer (entry.name), }); exe.linkLibrary (cimgui_dep.artifact ("cimgui")); //exe.module.addImport ("") builder.installArtifact (exe); } } }
0
repos/cimgui.zig/examples
repos/cimgui.zig/examples/example_glfw_vulkan/main.zig
const std = @import ("std"); const builtin = @import ("builtin"); pub const c = @cImport ({ @cDefine ("GLFW_INCLUDE_VULKAN", "1"); @cDefine ("GLFW_INCLUDE_NONE", "1"); @cInclude ("GLFW/glfw3.h"); @cInclude ("cimgui.h"); @cInclude ("backends/cimgui_impl_glfw.h"); @cInclude ("backends/cimgui_impl_vulkan.h"); }); var g_Allocator: *c.VkAllocationCallbacks = undefined; var g_Instance: c.VkInstance = undefined; var g_PhysicalDevice: c.VkPhysicalDevice = undefined; var g_Device: c.VkDevice = undefined; var g_QueueFamily: ?u32 = null; var g_Queue: c.VkQueue = undefined; var g_DebugReport: c.VkDebugReportCallbackEXT = undefined; var g_PipelineCache: c.VkPipelineCache = undefined; var g_DescriptorPool: c.VkDescriptorPool = undefined; var g_MainWindowData: c.ImGui_ImplVulkanH_Window = undefined; var g_MinImageCount: u32 = 2; var g_SwapChainRebuild: bool = false; const required_layers = [_][*:0] const u8 { "VK_LAYER_KHRONOS_validation", }; fn get_vulkan_instance_func (comptime PFN: type, instance: c.VkInstance, name: [*c] const u8) PFN { return @ptrCast (c.glfwGetInstanceProcAddress (instance, name)); } fn get_vulkan_device_func (comptime PFN: type, device: c.VkDevice, name: [*c] const u8) PFN { const vkGetDeviceProcAddr = get_vulkan_instance_func (c.PFN_vkGetDeviceProcAddr, g_Instance, "vkGetDeviceProcAddr").?; return @ptrCast (vkGetDeviceProcAddr (device, name)); } fn vkEnumerateInstanceExtensionProperties (name: [*c] const u8, count: [*c] u32, properties: [*c] c.VkExtensionProperties) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkEnumerateInstanceExtensionProperties, null, "vkEnumerateInstanceExtensionProperties").?; return func (name, count, properties); } fn vkEnumerateInstanceLayerProperties (count: [*c] u32, properties: [*c] c.VkLayerProperties) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkEnumerateInstanceLayerProperties, null, "vkEnumerateInstanceLayerProperties").?; return func (count, properties); } fn vkCreateInstance (info: [*c] const c.VkInstanceCreateInfo, allocator: [*c] const c.VkAllocationCallbacks, instance: [*c] c.VkInstance) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkCreateInstance, null, "vkCreateInstance").?; return func (info, allocator, instance); } fn vkEnumerateDeviceExtensionProperties (physical_device: c.VkPhysicalDevice, name: [*c] const u8, count: [*c] u32, properties: [*c] c.VkExtensionProperties) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkEnumerateDeviceExtensionProperties, null, "vkEnumerateDeviceExtensionProperties").?; return func (physical_device, name, count, properties); } fn vkGetPhysicalDeviceSurfaceSupportKHR (physical_device: c.VkPhysicalDevice, index: u32, surface: c.VkSurfaceKHR, supported: [*c] c.VkBool32) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkGetPhysicalDeviceSurfaceSupportKHR, g_Instance, "vkGetPhysicalDeviceSurfaceSupportKHR").?; return func (physical_device, index, surface, supported); } fn vkCreateDebugReportCallbackEXT (instance: c.VkInstance, debug_report_ci: [*c] const c.VkDebugReportCallbackCreateInfoEXT, allocator: [*c] const c.VkAllocationCallbacks, debug_report: [*c] c.VkDebugReportCallbackEXT) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkCreateDebugReportCallbackEXT, instance, "vkCreateDebugReportCallbackEXT").?; return func (instance, debug_report_ci, allocator, debug_report); } fn vkGetPhysicalDeviceProperties (physical_device: c.VkPhysicalDevice, properties: [*c] c.VkPhysicalDeviceProperties) void { const func = get_vulkan_instance_func (c.PFN_vkGetPhysicalDeviceProperties, g_Instance, "vkGetPhysicalDeviceProperties").?; func (physical_device, properties); } fn vkEnumeratePhysicalDevices (instance: c.VkInstance, count: [*c] u32, physical_devices: [*c] c.VkPhysicalDevice) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkEnumeratePhysicalDevices, instance, "vkEnumeratePhysicalDevices").?; return func (instance, count, physical_devices); } fn vkGetPhysicalDeviceQueueFamilyProperties (physical_device: c.VkPhysicalDevice, count: [*c]u32, properties: [*c] c.VkQueueFamilyProperties) void { const func = get_vulkan_instance_func (c.PFN_vkGetPhysicalDeviceQueueFamilyProperties, g_Instance, "vkGetPhysicalDeviceQueueFamilyProperties").?; func (physical_device, count, properties); } fn vkCreateDevice (physical_device: c.VkPhysicalDevice, info: [*c] const c.VkDeviceCreateInfo, allocator: [*c] const c.VkAllocationCallbacks, device: [*c] c.VkDevice) c.VkResult { const func = get_vulkan_instance_func (c.PFN_vkCreateDevice, g_Instance, "vkCreateDevice").?; return func (physical_device, info, allocator, device); } fn vkDestroyInstance (instance: c.VkInstance, allocator: [*c] const c.VkAllocationCallbacks) void { const func = get_vulkan_instance_func (c.PFN_vkDestroyInstance, instance, "vkDestroyInstance").?; func (instance, allocator); } fn vkAcquireNextImageKHR (device: c.VkDevice, swapchain: c.VkSwapchainKHR, timeout: u64, semaphore: c.VkSemaphore, fence: c.VkFence, index: [*c] u32) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkAcquireNextImageKHR, device, "vkAcquireNextImageKHR").?; return func (device, swapchain, timeout, semaphore, fence, index); } fn vkWaitForFences (device: c.VkDevice, count: u32, fences: [*c] const c.VkFence, wait: c.VkBool32, timeout: u64) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkWaitForFences, device, "vkWaitForFences").?; return func (device, count, fences, wait, timeout); } fn vkResetFences (device: c.VkDevice, count: u32, fences: [*c] const c.VkFence) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkResetFences, device, "vkResetFences").?; return func (device, count, fences); } fn vkGetDeviceQueue (device: c.VkDevice, family: u32, index: u32, queue: [*c] c.VkQueue) void { const func = get_vulkan_device_func (c.PFN_vkGetDeviceQueue, device, "vkGetDeviceQueue").?; func (device, family, index, queue); } fn vkCreateDescriptorPool (device: c.VkDevice, info: [*c] const c.VkDescriptorPoolCreateInfo, allocator: [*c] const c.VkAllocationCallbacks, descriptor_pool: [*c] c.VkDescriptorPool) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkCreateDescriptorPool, device, "vkCreateDescriptorPool").?; return func (device, info, allocator, descriptor_pool); } fn vkCmdBeginRenderPass (command_buffer: c.VkCommandBuffer, info: [*c] const c.VkRenderPassBeginInfo, contents: c.VkSubpassContents) void { const func = get_vulkan_device_func (c.PFN_vkCmdBeginRenderPass, g_Device, "vkCmdBeginRenderPass").?; func (command_buffer, info, contents); } fn vkCmdEndRenderPass (command_buffer: c.VkCommandBuffer) void { const func = get_vulkan_device_func (c.PFN_vkCmdEndRenderPass, g_Device, "vkCmdEndRenderPass").?; func (command_buffer); } fn vkEndCommandBuffer (command_buffer: c.VkCommandBuffer) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkEndCommandBuffer, g_Device, "vkEndCommandBuffer").?; return func (command_buffer); } fn vkQueueSubmit (queue: c.VkQueue, count: u32, info: [*c] const c.VkSubmitInfo, fence: c.VkFence) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkQueueSubmit, g_Device, "vkQueueSubmit").?; return func (queue, count, info, fence); } fn vkResetCommandPool (device: c.VkDevice, command_pool: c.VkCommandPool, flags: c.VkCommandPoolResetFlags) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkResetCommandPool, device, "vkResetCommandPool").?; return func (device, command_pool, flags); } fn vkBeginCommandBuffer (command_buffer: c.VkCommandBuffer, info: [*c] const c.VkCommandBufferBeginInfo) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkBeginCommandBuffer, g_Device, "vkBeginCommandBuffer").?; return func (command_buffer, info); } fn vkQueuePresentKHR (queue: c.VkQueue, info: [*c] const c.VkPresentInfoKHR) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkQueuePresentKHR, g_Device, "vkQueuePresentKHR").?; return func (queue, info); } fn vkDeviceWaitIdle (device: c.VkDevice) c.VkResult { const func = get_vulkan_device_func (c.PFN_vkDeviceWaitIdle, device, "vkDeviceWaitIdle").?; return func (device); } fn vkDestroyDescriptorPool (device: c.VkDevice, descriptor_pool: c.VkDescriptorPool, allocator: [*c] const c.VkAllocationCallbacks) void { const func = get_vulkan_device_func (c.PFN_vkDestroyDescriptorPool, device, "vkDestroyDescriptorPool").?; func (device, descriptor_pool, allocator); } fn vkDestroyDebugReportCallbackEXT (instance: c.VkInstance, debug_report: c.VkDebugReportCallbackEXT, allocator: [*c] const c.VkAllocationCallbacks) void { const func = get_vulkan_instance_func (c.PFN_vkDestroyDebugReportCallbackEXT, instance, "vkDestroyDebugReportCallbackEXT").?; func (instance, debug_report, allocator); } fn vkDestroyDevice (device: c.VkDevice, allocator: [*c] const c.VkAllocationCallbacks) void { const func = get_vulkan_device_func (c.PFN_vkDestroyDevice, device, "vkDestroyDevice").?; func (device, allocator); } fn loader (name: [*c] const u8, instance: ?*anyopaque) callconv (.C) ?*const fn () callconv (.C) void { return c.glfwGetInstanceProcAddress (@ptrCast (instance), name); } fn glfw_error_callback (err: c_int, description: [*c] const u8) callconv (.C) void { std.debug.print ("GLFW Error {d}: {s}\n", .{ err, description }); } fn check_vk_result (err: c.VkResult) callconv (.C) void { if (err == 0) return; std.debug.print ("[vulkan] Error: VkResult = {d}\n", .{ err }); if (err < 0) std.process.exit (1); } fn debugReport (_: c.VkDebugReportFlagsEXT, objectType: c.VkDebugReportObjectTypeEXT, _: u64, _: usize, _: i32, _: ?*const u8, pMessage: ?[*:0] const u8, _: ?*anyopaque) callconv (.C) c.VkBool32 { std.debug.print ("[vulkan] Debug report from ObjectType: {any}\nMessage: {s}\n\n", .{ objectType, pMessage orelse "No message available" }); return c.VK_FALSE; } fn IsExtensionAvailable (properties: [] const c.VkExtensionProperties, extension: [] const u8) bool { for (0 .. properties.len) |i| { if (std.mem.eql (u8, &properties [i].extensionName, extension)) return true; } else return false; } fn IsLayerAvailable (layers: [] const c.VkLayerProperties, layer: [*:0] const u8) bool { const span = std.mem.span (layer); for (0 .. layers.len) |i| { if (std.mem.eql (u8, layers [i].layerName [0 .. span.len], span)) return true; } else return false; } fn SetupVulkan_SelectPhysicalDevice (allocator: std.mem.Allocator) !c.VkPhysicalDevice { var gpu_count: u32 = undefined; var err = vkEnumeratePhysicalDevices (g_Instance, &gpu_count, null); check_vk_result (err); const gpus = try allocator.alloc (c.VkPhysicalDevice, gpu_count); err = vkEnumeratePhysicalDevices (g_Instance, &gpu_count, gpus.ptr); check_vk_result(err); for (gpus) |device| { var properties: c.VkPhysicalDeviceProperties = undefined; vkGetPhysicalDeviceProperties (device, &properties); if (properties.deviceType == c.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) return device; } // Use first GPU (Integrated) is a Discrete one is not available. if (gpu_count > 0) return gpus [0]; return error.NoPhysicalDeviceAvailable; } fn SetupVulkan (allocator: std.mem.Allocator, instance_extensions: *std.ArrayList ([*:0] const u8)) !void { var err: c.VkResult = undefined; var app_info = c.VkApplicationInfo {}; app_info.pApplicationName = "example_glfw_vulkan"; app_info.applicationVersion = c.VK_API_VERSION_1_2; app_info.pEngineName = "No Engine"; app_info.engineVersion = c.VK_API_VERSION_1_2; app_info.apiVersion = c.VK_API_VERSION_1_2; // Setup the debug report callback var debug_report_ci = c.VkDebugReportCallbackCreateInfoEXT {}; debug_report_ci.sType = c.VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debug_report_ci.flags = c.VK_DEBUG_REPORT_ERROR_BIT_EXT | c.VK_DEBUG_REPORT_WARNING_BIT_EXT | c.VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; debug_report_ci.pfnCallback = debugReport; debug_report_ci.pUserData = null; // Create Vulkan Instance var create_info = c.VkInstanceCreateInfo {}; create_info.sType = c.VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; create_info.pApplicationInfo = &app_info; create_info.pNext = &debug_report_ci; // Enumerate available extensions var properties_count: u32 = undefined; _ = vkEnumerateInstanceExtensionProperties (null, &properties_count, null); const properties = try allocator.alloc (c.VkExtensionProperties, properties_count); err = vkEnumerateInstanceExtensionProperties (null, &properties_count, properties.ptr); check_vk_result (err); // Enable required extensions if (IsExtensionAvailable (properties [0 .. properties_count], c.VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) try instance_extensions.append (c.VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); // Enumerate available layers var layers_count: u32 = undefined; _ = vkEnumerateInstanceLayerProperties (&layers_count, null); const layers = try allocator.alloc (c.VkLayerProperties, layers_count); err = vkEnumerateInstanceLayerProperties (&layers_count, layers.ptr); check_vk_result (err); // Enable required layers if (!IsLayerAvailable (layers [0 .. layers_count], required_layers [0])) return error.RequiredLayerNotAvailable; // Enabling validation layers create_info.enabledLayerCount = required_layers.len; create_info.ppEnabledLayerNames = required_layers [0 ..].ptr; try instance_extensions.append ("VK_EXT_debug_report"); // Create Vulkan Instance create_info.enabledExtensionCount = @intCast (instance_extensions.items.len); create_info.ppEnabledExtensionNames = instance_extensions.items.ptr; err = vkCreateInstance (&create_info, g_Allocator, &g_Instance); check_vk_result (err); err = vkCreateDebugReportCallbackEXT (g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); check_vk_result (err); // Select Physical Device (GPU) g_PhysicalDevice = try SetupVulkan_SelectPhysicalDevice (allocator); // Select graphics queue family var count: u32 = undefined; vkGetPhysicalDeviceQueueFamilyProperties (g_PhysicalDevice, &count, null); const queues = try allocator.alloc (c.VkQueueFamilyProperties, count); defer allocator.free (queues); vkGetPhysicalDeviceQueueFamilyProperties (g_PhysicalDevice, &count, queues.ptr); var i: u32 = 0; while (i < count) { if (queues [i].queueFlags & c.VK_QUEUE_GRAPHICS_BIT != 0) { g_QueueFamily = i; break; } i += 1; } // Create Logical Device (with 1 queue) var device_extensions = std.ArrayList ([*:0] const u8).init (allocator); try device_extensions.append ("VK_KHR_swapchain"); // Enumerate physical device extension _ = vkEnumerateDeviceExtensionProperties (g_PhysicalDevice, null, &properties_count, null); const properties2 = try allocator.alloc (c.VkExtensionProperties, properties_count); _ = vkEnumerateDeviceExtensionProperties (g_PhysicalDevice, null, &properties_count, properties2.ptr); const queue_priority = [_] f32 { 1.0 }; var queue_info = [1] c.VkDeviceQueueCreateInfo { .{} }; queue_info [0].sType = c.VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_info [0].queueFamilyIndex = g_QueueFamily.?; queue_info [0].queueCount = 1; queue_info [0].pQueuePriorities = &queue_priority; var device_create_info = c.VkDeviceCreateInfo {}; device_create_info.sType = c.VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; device_create_info.queueCreateInfoCount = queue_info.len; device_create_info.pQueueCreateInfos = &queue_info; device_create_info.enabledLayerCount = required_layers.len; device_create_info.ppEnabledLayerNames = required_layers [0 ..].ptr; device_create_info.enabledExtensionCount = @intCast (device_extensions.items.len); device_create_info.ppEnabledExtensionNames = device_extensions.items.ptr; err = vkCreateDevice (g_PhysicalDevice, &device_create_info, g_Allocator, &g_Device); check_vk_result (err); vkGetDeviceQueue (g_Device, g_QueueFamily.?, 0, &g_Queue); // Create Descriptor Pool // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) // If you wish to load e.g. additional textures you may need to alter pools sizes. const pool_sizes = [_] c.VkDescriptorPoolSize { .{ .@"type" = c.VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 1, }, }; var pool_info = c.VkDescriptorPoolCreateInfo {}; pool_info.sType = c.VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = c.VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; pool_info.maxSets = 1; pool_info.poolSizeCount = pool_sizes.len; pool_info.pPoolSizes = &pool_sizes; err = vkCreateDescriptorPool (g_Device, &pool_info, g_Allocator, &g_DescriptorPool); check_vk_result (err); } // All the ImGui_ImplVulkanH_XXX structures/functions are optional helpers used by the demo. // Your real engine/app may not use them. fn SetupVulkanWindow (wd: *c.ImGui_ImplVulkanH_Window, surface: c.VkSurfaceKHR, width: i32, height: i32) !void { wd.Surface = surface; // Check for WSI support var res: c.VkBool32 = undefined; _ = vkGetPhysicalDeviceSurfaceSupportKHR (g_PhysicalDevice, g_QueueFamily.?, wd.Surface, &res); if (res != c.VK_TRUE) return error.NoWSISupport; // Select Surface Format const requestSurfaceImageFormat = [_] c.VkFormat { c.VK_FORMAT_B8G8R8A8_UNORM, c.VK_FORMAT_R8G8B8A8_UNORM, c.VK_FORMAT_B8G8R8_UNORM, c.VK_FORMAT_R8G8B8_UNORM }; const ptrRequestSurfaceImageFormat: [*] const c.VkFormat = &requestSurfaceImageFormat; const requestSurfaceColorSpace = c.VK_COLORSPACE_SRGB_NONLINEAR_KHR; wd.SurfaceFormat = c.cImGui_ImplVulkanH_SelectSurfaceFormat (g_PhysicalDevice, wd.Surface, ptrRequestSurfaceImageFormat, requestSurfaceImageFormat.len, requestSurfaceColorSpace); // Select Present Mode const present_modes = [_] c.VkPresentModeKHR { c.VK_PRESENT_MODE_FIFO_KHR }; wd.PresentMode = c.cImGui_ImplVulkanH_SelectPresentMode (g_PhysicalDevice, wd.Surface, &present_modes [0], present_modes.len); // Create SwapChain, RenderPass, Framebuffer, etc. c.cImGui_ImplVulkanH_CreateOrResizeWindow (g_Instance, g_PhysicalDevice, g_Device, wd, g_QueueFamily.?, g_Allocator, width, height, g_MinImageCount); } fn CleanupVulkan () void { vkDestroyDescriptorPool (g_Device, g_DescriptorPool, g_Allocator); // Remove the debug report callback vkDestroyDebugReportCallbackEXT (g_Instance, g_DebugReport, g_Allocator); vkDestroyDevice (g_Device, g_Allocator); vkDestroyInstance (g_Instance, g_Allocator); } fn CleanupVulkanWindow () void { c.cImGui_ImplVulkanH_DestroyWindow (g_Instance, g_Device, &g_MainWindowData, g_Allocator); } fn FrameRender (wd: *c.ImGui_ImplVulkanH_Window, draw_data: *c.ImDrawData) void { var err: c.VkResult = undefined; var image_acquired_semaphore = wd.FrameSemaphores [wd.SemaphoreIndex].ImageAcquiredSemaphore; var render_complete_semaphore = wd.FrameSemaphores [wd.SemaphoreIndex].RenderCompleteSemaphore; err = vkAcquireNextImageKHR (g_Device, wd.Swapchain, std.math.maxInt (u64), image_acquired_semaphore, null, &wd.FrameIndex); if (err == c.VK_ERROR_OUT_OF_DATE_KHR or err == c.VK_SUBOPTIMAL_KHR) { g_SwapChainRebuild = true; return; } check_vk_result (err); var fd = &wd.Frames [wd.FrameIndex]; err = vkWaitForFences (g_Device, 1, &fd.Fence, c.VK_TRUE, std.math.maxInt (u64)); // wait indefinitely instead of periodically checking check_vk_result (err); { err = vkResetFences (g_Device, 1, &fd.Fence); check_vk_result (err); err = vkResetCommandPool (g_Device, fd.CommandPool, 0); check_vk_result (err); var info = c.VkCommandBufferBeginInfo {}; info.sType = c.VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; info.flags |= c.VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; err = vkBeginCommandBuffer (fd.CommandBuffer, &info); check_vk_result (err); }{ var info = c.VkRenderPassBeginInfo {}; info.sType = c.VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; info.renderPass = wd.RenderPass; info.framebuffer = fd.Framebuffer; info.renderArea.extent.width = @intCast (wd.Width); info.renderArea.extent.height = @intCast (wd.Height); info.clearValueCount = 1; info.pClearValues = &wd.ClearValue; vkCmdBeginRenderPass (fd.CommandBuffer, &info, c.VK_SUBPASS_CONTENTS_INLINE); } // Record dear imgui primitives into command buffer c.cImGui_ImplVulkan_RenderDrawData (draw_data, fd.CommandBuffer); // Submit command buffer vkCmdEndRenderPass (fd.CommandBuffer); { var wait_stage: c.VkPipelineStageFlags = c.VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; var info = c.VkSubmitInfo {}; info.sType = c.VK_STRUCTURE_TYPE_SUBMIT_INFO; info.waitSemaphoreCount = 1; info.pWaitSemaphores = &image_acquired_semaphore; info.pWaitDstStageMask = &wait_stage; info.commandBufferCount = 1; info.pCommandBuffers = &fd.CommandBuffer; info.signalSemaphoreCount = 1; info.pSignalSemaphores = &render_complete_semaphore; err = vkEndCommandBuffer (fd.CommandBuffer); check_vk_result (err); err = vkQueueSubmit (g_Queue, 1, &info, fd.Fence); check_vk_result (err); } } fn FramePresent (wd: *c.ImGui_ImplVulkanH_Window) void { if (g_SwapChainRebuild) return; var render_complete_semaphore = wd.FrameSemaphores [wd.SemaphoreIndex].RenderCompleteSemaphore; var info = c.VkPresentInfoKHR {}; info.sType = c.VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; info.waitSemaphoreCount = 1; info.pWaitSemaphores = &render_complete_semaphore; info.swapchainCount = 1; info.pSwapchains = &wd.Swapchain; info.pImageIndices = &wd.FrameIndex; const err = vkQueuePresentKHR (g_Queue, &info); if (err == c.VK_ERROR_OUT_OF_DATE_KHR or err == c.VK_SUBOPTIMAL_KHR) { g_SwapChainRebuild = true; return; } check_vk_result (err); wd.SemaphoreIndex = (wd.SemaphoreIndex + 1) % wd.SemaphoreCount; // Now we can use the next set of semaphores } pub fn main () !void { var arena = std.heap.ArenaAllocator.init (std.heap.page_allocator); defer arena.deinit (); const allocator = arena.allocator (); _ = c.glfwSetErrorCallback (glfw_error_callback); if (c.glfwInit () == 0) return error.glfwInitFailure; // Create window with Vulkan context c.glfwWindowHint (c.GLFW_CLIENT_API, c.GLFW_NO_API); const window = c.glfwCreateWindow (1280, 720, "Dear ImGui GLFW+Vulkan example", null, null); if (c.glfwVulkanSupported () == 0) return error.VulkanNotSupported; var extensions = std.ArrayList ([*:0] const u8).init (allocator); var extensions_count: u32 = 0; const glfw_extensions = c.glfwGetRequiredInstanceExtensions (&extensions_count); for (0 .. extensions_count) |i| try extensions.append (std.mem.span (glfw_extensions [i])); try SetupVulkan (allocator, &extensions); // Create Window Surface var surface: c.VkSurfaceKHR = undefined; var err = c.glfwCreateWindowSurface (g_Instance, window, g_Allocator, &surface); check_vk_result (err); if (!c.cImGui_ImplVulkan_LoadFunctions (loader)) return error.ImGuiVulkanLoadFailure; // Create Framebuffers var w: i32 = undefined; var h: i32 = undefined; c.glfwGetFramebufferSize (window, &w, &h); var wd = &g_MainWindowData; try SetupVulkanWindow (wd, surface, w, h); // Setup Dear ImGui context if (c.ImGui_CreateContext (null) == null) return error.ImGuiCreateContextFailure; const io = c.ImGui_GetIO ();// (void)io; io.*.ConfigFlags |= c.ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.*.ConfigFlags |= c.ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style c.ImGui_StyleColorsDark (null); // Setup Platform/Renderer backends if (!c.cImGui_ImplGlfw_InitForVulkan (window, true)) return error.ImGuiGlfwInitForVulkanFailure; var init_info = c.ImGui_ImplVulkan_InitInfo {}; init_info.Instance = g_Instance; init_info.PhysicalDevice = g_PhysicalDevice; init_info.Device = g_Device; init_info.QueueFamily = g_QueueFamily.?; init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; init_info.RenderPass = wd.RenderPass; init_info.Subpass = 0; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd.ImageCount; init_info.MSAASamples = c.VK_SAMPLE_COUNT_1_BIT; init_info.Allocator = g_Allocator; init_info.CheckVkResultFn = check_vk_result; if (!c.cImGui_ImplVulkan_Init (&init_info)) return error.ImGuiVulkanInitFailure; // Our state var show_demo_window = true; var show_another_window = false; const clear_color: c.ImVec4 = .{ .x = 0.45, .y = 0.55, .z = 0.6, .w = 1.0 }; const clear_color_slice = try allocator.alloc (f32, 3); clear_color_slice [0] = clear_color.x; clear_color_slice [1] = clear_color.y; clear_color_slice [2] = clear_color.z; defer { // Cleanup err = vkDeviceWaitIdle (g_Device); check_vk_result (err); c.cImGui_ImplVulkan_Shutdown (); c.cImGui_ImplGlfw_Shutdown (); c.ImGui_DestroyContext (null); CleanupVulkanWindow (); CleanupVulkan (); c.glfwDestroyWindow (window); c.glfwTerminate (); } while (c.glfwWindowShouldClose (window) == 0) { c.glfwPollEvents (); // Resize swap chain? if (g_SwapChainRebuild) { var width: i32 = undefined; var height: i32 = undefined; c.glfwGetFramebufferSize (window, &width, &height); if (width > 0 and height > 0) { c.cImGui_ImplVulkan_SetMinImageCount (g_MinImageCount); c.cImGui_ImplVulkanH_CreateOrResizeWindow (g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily.?, g_Allocator, width, height, g_MinImageCount); g_MainWindowData.FrameIndex = 0; g_SwapChainRebuild = false; } } // Start the Dear ImGui frame c.cImGui_ImplVulkan_NewFrame (); c.cImGui_ImplGlfw_NewFrame (); c.ImGui_NewFrame (); defer { // Rendering c.ImGui_Render (); const draw_data = c.ImGui_GetDrawData (); const is_minimized = (draw_data.*.DisplaySize.x <= 0.0 or draw_data.*.DisplaySize.y <= 0.0); if (!is_minimized) { wd.ClearValue.color.float32 [0] = clear_color.x * clear_color.w; wd.ClearValue.color.float32 [1] = clear_color.y * clear_color.w; wd.ClearValue.color.float32 [2] = clear_color.z * clear_color.w; wd.ClearValue.color.float32 [3] = clear_color.w; FrameRender (wd, draw_data); FramePresent (wd); } } // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (show_demo_window) c.ImGui_ShowDemoWindow (&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. var f: f32 = 0.0; var counter: i32 = 0; { _ = c.ImGui_Begin ("Hello, world!", null, 0); defer c.ImGui_End (); c.ImGui_Text ("This is some useful text."); _ = c.ImGui_Checkbox ("Demo Window", &show_demo_window); _ = c.ImGui_Checkbox ("Another Window", &show_another_window); _ = c.ImGui_SliderFloat ("float", &f, 0.0, 1.0); _ = c.ImGui_ColorEdit3 ("clear color", clear_color_slice.ptr, 0); if (c.ImGui_Button ("Button")) counter += 1; c.ImGui_SameLine (); c.ImGui_Text ("counter = %d", counter); c.ImGui_Text ("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / io.*.Framerate, io.*.Framerate); } // 3. Show another simple window. if (show_another_window) { _ = c.ImGui_Begin ("Another Window", &show_another_window, 0); defer c.ImGui_End (); c.ImGui_Text ("Hello from another window!"); if (c.ImGui_Button ("Close Me")) show_another_window = false; } } }
0
repos
repos/zig-clap/clap.zig
const std = @import("std"); const builtin = std.builtin; const debug = std.debug; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const meta = std.meta; const process = std.process; const testing = std.testing; pub const args = @import("clap/args.zig"); pub const parsers = @import("clap/parsers.zig"); pub const streaming = @import("clap/streaming.zig"); pub const ccw = @import("clap/codepoint_counting_writer.zig"); test "clap" { testing.refAllDecls(@This()); } pub const default_assignment_separators = "="; /// The names a `Param` can have. pub const Names = struct { /// '-' prefix short: ?u8 = null, /// '--' prefix long: ?[]const u8 = null, /// The longest of the possible names this `Names` struct can represent. pub fn longest(names: *const Names) Longest { if (names.long) |long| return .{ .kind = .long, .name = long }; if (names.short) |*short| return .{ .kind = .short, .name = @as(*const [1]u8, short) }; return .{ .kind = .positional, .name = "" }; } pub const Longest = struct { kind: Kind, name: []const u8, }; pub const Kind = enum { long, short, positional, pub fn prefix(kind: Kind) []const u8 { return switch (kind) { .long => "--", .short => "-", .positional => "", }; } }; }; /// Whether a param takes no value (a flag), one value, or can be specified multiple times. pub const Values = enum { none, one, many, }; /// Represents a parameter for the command line. /// Parameters come in three kinds: /// * Short ("-a"): Should be used for the most commonly used parameters in your program. /// * They can take a value three different ways. /// * "-a value" /// * "-a=value" /// * "-avalue" /// * They chain if they don't take values: "-abc". /// * The last given parameter can take a value in the same way that a single parameter can: /// * "-abc value" /// * "-abc=value" /// * "-abcvalue" /// * Long ("--long-param"): Should be used for less common parameters, or when no single /// character can describe the parameter. /// * They can take a value two different ways. /// * "--long-param value" /// * "--long-param=value" /// * Positional: Should be used as the primary parameter of the program, like a filename or /// an expression to parse. /// * Positional parameters have both names.long and names.short == null. /// * Positional parameters must take a value. pub fn Param(comptime Id: type) type { return struct { id: Id, names: Names = Names{}, takes_value: Values = .none, }; } /// Takes a string and parses it into many Param(Help). Returned is a newly allocated slice /// containing all the parsed params. The caller is responsible for freeing the slice. pub fn parseParams(allocator: mem.Allocator, str: []const u8) ![]Param(Help) { var end: usize = undefined; return parseParamsEx(allocator, str, &end); } /// Takes a string and parses it into many Param(Help). Returned is a newly allocated slice /// containing all the parsed params. The caller is responsible for freeing the slice. pub fn parseParamsEx(allocator: mem.Allocator, str: []const u8, end: *usize) ![]Param(Help) { var list = std.ArrayList(Param(Help)).init(allocator); errdefer list.deinit(); try parseParamsIntoArrayListEx(&list, str, end); return try list.toOwnedSlice(); } /// Takes a string and parses it into many Param(Help) at comptime. Returned is an array of /// exactly the number of params that was parsed from `str`. A parse error becomes a compiler /// error. pub fn parseParamsComptime(comptime str: []const u8) [countParams(str)]Param(Help) { var end: usize = undefined; var res: [countParams(str)]Param(Help) = undefined; _ = parseParamsIntoSliceEx(&res, str, &end) catch { const loc = std.zig.findLineColumn(str, end); @compileError(std.fmt.comptimePrint("error:{}:{}: Failed to parse parameter:\n{s}", .{ loc.line + 1, loc.column + 1, loc.source_line, })); }; return res; } fn countParams(str: []const u8) usize { // See parseParam for reasoning. I would like to remove it from parseParam, but people depend // on that function to still work conveniently at comptime, so leaving it for now. @setEvalBranchQuota(std.math.maxInt(u32)); var res: usize = 0; var it = mem.splitScalar(u8, str, '\n'); while (it.next()) |line| { const trimmed = mem.trimLeft(u8, line, " \t"); if (mem.startsWith(u8, trimmed, "-") or mem.startsWith(u8, trimmed, "<")) { res += 1; } } return res; } /// Takes a string and parses it into many Param(Help), which are written to `slice`. A subslice /// is returned, containing all the parameters parsed. This function will fail if the input slice /// is to small. pub fn parseParamsIntoSlice(slice: []Param(Help), str: []const u8) ![]Param(Help) { var null_alloc = heap.FixedBufferAllocator.init(""); var list = std.ArrayList(Param(Help)){ .allocator = null_alloc.allocator(), .items = slice[0..0], .capacity = slice.len, }; try parseParamsIntoArrayList(&list, str); return list.items; } /// Takes a string and parses it into many Param(Help), which are written to `slice`. A subslice /// is returned, containing all the parameters parsed. This function will fail if the input slice /// is to small. pub fn parseParamsIntoSliceEx(slice: []Param(Help), str: []const u8, end: *usize) ![]Param(Help) { var null_alloc = heap.FixedBufferAllocator.init(""); var list = std.ArrayList(Param(Help)){ .allocator = null_alloc.allocator(), .items = slice[0..0], .capacity = slice.len, }; try parseParamsIntoArrayListEx(&list, str, end); return list.items; } /// Takes a string and parses it into many Param(Help), which are appended onto `list`. pub fn parseParamsIntoArrayList(list: *std.ArrayList(Param(Help)), str: []const u8) !void { var end: usize = undefined; return parseParamsIntoArrayListEx(list, str, &end); } /// Takes a string and parses it into many Param(Help), which are appended onto `list`. pub fn parseParamsIntoArrayListEx(list: *std.ArrayList(Param(Help)), str: []const u8, end: *usize) !void { var i: usize = 0; while (i != str.len) { var end_of_this: usize = undefined; errdefer end.* = i + end_of_this; try list.append(try parseParamEx(str[i..], &end_of_this)); i += end_of_this; } end.* = str.len; } pub fn parseParam(str: []const u8) !Param(Help) { var end: usize = undefined; return parseParamEx(str, &end); } /// Takes a string and parses it to a Param(Help). pub fn parseParamEx(str: []const u8, end: *usize) !Param(Help) { // This function become a lot less ergonomic to use once you hit the eval branch quota. To // avoid this we pick a sane default. Sadly, the only sane default is the biggest possible // value. If we pick something a lot smaller and a user hits the quota after that, they have // no way of overriding it, since we set it here. // We can recosider this again if: // * We get parseParams: https://github.com/Hejsil/zig-clap/issues/39 // * We get a larger default branch quota in the zig compiler (stage 2). // * Someone points out how this is a really bad idea. @setEvalBranchQuota(std.math.maxInt(u32)); var res = Param(Help){ .id = .{} }; var start: usize = 0; var state: enum { start, start_of_short_name, end_of_short_name, before_long_name_or_value_or_description, before_long_name, start_of_long_name, first_char_of_long_name, rest_of_long_name, before_value_or_description, first_char_of_value, rest_of_value, end_of_one_value, second_dot_of_multi_value, third_dot_of_multi_value, before_description, rest_of_description, rest_of_description_new_line, } = .start; for (str, 0..) |c, i| { errdefer end.* = i; switch (state) { .start => switch (c) { ' ', '\t', '\n' => {}, '-' => state = .start_of_short_name, '<' => state = .first_char_of_value, else => return error.InvalidParameter, }, .start_of_short_name => switch (c) { '-' => state = .first_char_of_long_name, 'a'...'z', 'A'...'Z', '0'...'9' => { res.names.short = c; state = .end_of_short_name; }, else => return error.InvalidParameter, }, .end_of_short_name => switch (c) { ' ', '\t' => state = .before_long_name_or_value_or_description, '\n' => { start = i + 1; end.* = i + 1; state = .rest_of_description_new_line; }, ',' => state = .before_long_name, else => return error.InvalidParameter, }, .before_long_name => switch (c) { ' ', '\t' => {}, '-' => state = .start_of_long_name, else => return error.InvalidParameter, }, .start_of_long_name => switch (c) { '-' => state = .first_char_of_long_name, else => return error.InvalidParameter, }, .first_char_of_long_name => switch (c) { 'a'...'z', 'A'...'Z', '0'...'9', '-', '_' => { start = i; state = .rest_of_long_name; }, else => return error.InvalidParameter, }, .rest_of_long_name => switch (c) { 'a'...'z', 'A'...'Z', '0'...'9', '-', '_' => {}, ' ', '\t' => { res.names.long = str[start..i]; state = .before_value_or_description; }, '\n' => { res.names.long = str[start..i]; start = i + 1; end.* = i + 1; state = .rest_of_description_new_line; }, else => return error.InvalidParameter, }, .before_long_name_or_value_or_description => switch (c) { ' ', '\t' => {}, ',' => state = .before_long_name, '<' => state = .first_char_of_value, else => { start = i; state = .rest_of_description; }, }, .before_value_or_description => switch (c) { ' ', '\t' => {}, '<' => state = .first_char_of_value, else => { start = i; state = .rest_of_description; }, }, .first_char_of_value => switch (c) { '>' => return error.InvalidParameter, else => { start = i; state = .rest_of_value; }, }, .rest_of_value => switch (c) { '>' => { res.takes_value = .one; res.id.val = str[start..i]; state = .end_of_one_value; }, else => {}, }, .end_of_one_value => switch (c) { '.' => state = .second_dot_of_multi_value, ' ', '\t' => state = .before_description, '\n' => { start = i + 1; end.* = i + 1; state = .rest_of_description_new_line; }, else => { start = i; state = .rest_of_description; }, }, .second_dot_of_multi_value => switch (c) { '.' => state = .third_dot_of_multi_value, else => return error.InvalidParameter, }, .third_dot_of_multi_value => switch (c) { '.' => { res.takes_value = .many; state = .before_description; }, else => return error.InvalidParameter, }, .before_description => switch (c) { ' ', '\t' => {}, '\n' => { start = i + 1; end.* = i + 1; state = .rest_of_description_new_line; }, else => { start = i; state = .rest_of_description; }, }, .rest_of_description => switch (c) { '\n' => { end.* = i; state = .rest_of_description_new_line; }, else => {}, }, .rest_of_description_new_line => switch (c) { ' ', '\t', '\n' => {}, '-', '<' => { res.id.desc = str[start..end.*]; end.* = i; break; }, else => state = .rest_of_description, }, } } else { defer end.* = str.len; switch (state) { .rest_of_description => res.id.desc = str[start..], .rest_of_description_new_line => res.id.desc = str[start..end.*], .rest_of_long_name => res.names.long = str[start..], .end_of_short_name, .end_of_one_value, .before_value_or_description, .before_description, => {}, else => return error.InvalidParameter, } } return res; } fn testParseParams(str: []const u8, expected_params: []const Param(Help)) !void { var end: usize = undefined; const actual_params = parseParamsEx(testing.allocator, str, &end) catch |err| { const loc = std.zig.findLineColumn(str, end); std.debug.print("error:{}:{}: Failed to parse parameter:\n{s}\n", .{ loc.line + 1, loc.column + 1, loc.source_line, }); return err; }; defer testing.allocator.free(actual_params); try testing.expectEqual(expected_params.len, actual_params.len); for (expected_params, 0..) |_, i| try expectParam(expected_params[i], actual_params[i]); } fn expectParam(expect: Param(Help), actual: Param(Help)) !void { try testing.expectEqualStrings(expect.id.desc, actual.id.desc); try testing.expectEqualStrings(expect.id.val, actual.id.val); try testing.expectEqual(expect.names.short, actual.names.short); try testing.expectEqual(expect.takes_value, actual.takes_value); if (expect.names.long) |long| { try testing.expectEqualStrings(long, actual.names.long.?); } else { try testing.expectEqual(@as(?[]const u8, null), actual.names.long); } } test "parseParams" { try testParseParams( \\-s \\--str \\--str-str \\--str_str \\-s, --str \\--str <str> \\-s, --str <str> \\-s, --long <val> Help text \\-s, --long <val>... Help text \\--long <val> Help text \\-s <val> Help text \\-s, --long Help text \\-s Help text \\--long Help text \\--long <A | B> Help text \\<A> Help text \\<A>... Help text \\--aa \\ This is \\ help spanning multiple \\ lines \\--aa This msg should end and the newline cause of new param \\--bb This should be a new param \\ , &.{ .{ .id = .{}, .names = .{ .short = 's' } }, .{ .id = .{}, .names = .{ .long = "str" } }, .{ .id = .{}, .names = .{ .long = "str-str" } }, .{ .id = .{}, .names = .{ .long = "str_str" } }, .{ .id = .{}, .names = .{ .short = 's', .long = "str" } }, .{ .id = .{ .val = "str" }, .names = .{ .long = "str" }, .takes_value = .one, }, .{ .id = .{ .val = "str" }, .names = .{ .short = 's', .long = "str" }, .takes_value = .one, }, .{ .id = .{ .desc = "Help text", .val = "val" }, .names = .{ .short = 's', .long = "long" }, .takes_value = .one, }, .{ .id = .{ .desc = "Help text", .val = "val" }, .names = .{ .short = 's', .long = "long" }, .takes_value = .many, }, .{ .id = .{ .desc = "Help text", .val = "val" }, .names = .{ .long = "long" }, .takes_value = .one, }, .{ .id = .{ .desc = "Help text", .val = "val" }, .names = .{ .short = 's' }, .takes_value = .one, }, .{ .id = .{ .desc = "Help text" }, .names = .{ .short = 's', .long = "long" }, }, .{ .id = .{ .desc = "Help text" }, .names = .{ .short = 's' }, }, .{ .id = .{ .desc = "Help text" }, .names = .{ .long = "long" }, }, .{ .id = .{ .desc = "Help text", .val = "A | B" }, .names = .{ .long = "long" }, .takes_value = .one, }, .{ .id = .{ .desc = "Help text", .val = "A" }, .takes_value = .one, }, .{ .id = .{ .desc = "Help text", .val = "A" }, .names = .{}, .takes_value = .many, }, .{ .id = .{ .desc = \\ This is \\ help spanning multiple \\ lines , }, .names = .{ .long = "aa" }, .takes_value = .none, }, .{ .id = .{ .desc = "This msg should end and the newline cause of new param" }, .names = .{ .long = "aa" }, .takes_value = .none, }, .{ .id = .{ .desc = "This should be a new param" }, .names = .{ .long = "bb" }, .takes_value = .none, }, }); try testing.expectError(error.InvalidParameter, parseParam("--long, Help")); try testing.expectError(error.InvalidParameter, parseParam("-s, Help")); try testing.expectError(error.InvalidParameter, parseParam("-ss Help")); try testing.expectError(error.InvalidParameter, parseParam("-ss <val> Help")); try testing.expectError(error.InvalidParameter, parseParam("- Help")); } /// Optional diagnostics used for reporting useful errors pub const Diagnostic = struct { arg: []const u8 = "", name: Names = Names{}, /// Default diagnostics reporter when all you want is English with no colors. /// Use this as a reference for implementing your own if needed. pub fn report(diag: Diagnostic, stream: anytype, err: anyerror) !void { var longest = diag.name.longest(); if (longest.kind == .positional) longest.name = diag.arg; switch (err) { streaming.Error.DoesntTakeValue => try stream.print( "The argument '{s}{s}' does not take a value\n", .{ longest.kind.prefix(), longest.name }, ), streaming.Error.MissingValue => try stream.print( "The argument '{s}{s}' requires a value but none was supplied\n", .{ longest.kind.prefix(), longest.name }, ), streaming.Error.InvalidArgument => try stream.print( "Invalid argument '{s}{s}'\n", .{ longest.kind.prefix(), longest.name }, ), else => try stream.print("Error while parsing arguments: {s}\n", .{@errorName(err)}), } } }; fn testDiag(diag: Diagnostic, err: anyerror, expected: []const u8) !void { var buf: [1024]u8 = undefined; var slice_stream = io.fixedBufferStream(&buf); diag.report(slice_stream.writer(), err) catch unreachable; try testing.expectEqualStrings(expected, slice_stream.getWritten()); } test "Diagnostic.report" { try testDiag(.{ .arg = "c" }, error.InvalidArgument, "Invalid argument 'c'\n"); try testDiag( .{ .name = .{ .long = "cc" } }, error.InvalidArgument, "Invalid argument '--cc'\n", ); try testDiag( .{ .name = .{ .short = 'c' } }, error.DoesntTakeValue, "The argument '-c' does not take a value\n", ); try testDiag( .{ .name = .{ .long = "cc" } }, error.DoesntTakeValue, "The argument '--cc' does not take a value\n", ); try testDiag( .{ .name = .{ .short = 'c' } }, error.MissingValue, "The argument '-c' requires a value but none was supplied\n", ); try testDiag( .{ .name = .{ .long = "cc" } }, error.MissingValue, "The argument '--cc' requires a value but none was supplied\n", ); try testDiag( .{ .name = .{ .short = 'c' } }, error.InvalidArgument, "Invalid argument '-c'\n", ); try testDiag( .{ .name = .{ .long = "cc" } }, error.InvalidArgument, "Invalid argument '--cc'\n", ); try testDiag( .{ .name = .{ .short = 'c' } }, error.SomethingElse, "Error while parsing arguments: SomethingElse\n", ); try testDiag( .{ .name = .{ .long = "cc" } }, error.SomethingElse, "Error while parsing arguments: SomethingElse\n", ); } /// Options that can be set to customize the behavior of parsing. pub const ParseOptions = struct { allocator: mem.Allocator, diagnostic: ?*Diagnostic = null, assignment_separators: []const u8 = default_assignment_separators, }; /// Same as `parseEx` but uses the `args.OsIterator` by default. pub fn parse( comptime Id: type, comptime params: []const Param(Id), comptime value_parsers: anytype, opt: ParseOptions, ) !Result(Id, params, value_parsers) { var arena = heap.ArenaAllocator.init(opt.allocator); errdefer arena.deinit(); var iter = try process.ArgIterator.initWithAllocator(arena.allocator()); const exe_arg = iter.next(); const result = try parseEx(Id, params, value_parsers, &iter, .{ // Let's reuse the arena from the `OSIterator` since we already have it. .allocator = arena.allocator(), .diagnostic = opt.diagnostic, .assignment_separators = opt.assignment_separators, }); return Result(Id, params, value_parsers){ .args = result.args, .positionals = result.positionals, .exe_arg = exe_arg, .arena = arena, }; } /// The result of `parse`. Is owned by the caller and should be freed with `deinit`. pub fn Result( comptime Id: type, comptime params: []const Param(Id), comptime value_parsers: anytype, ) type { return struct { args: Arguments(Id, params, value_parsers, .slice), positionals: []const FindPositionalType(Id, params, value_parsers), exe_arg: ?[]const u8, arena: std.heap.ArenaAllocator, pub fn deinit(result: @This()) void { result.arena.deinit(); } }; } /// Parses the command line arguments passed into the program based on an array of parameters. /// /// The result will contain an `args` field which contains all the non positional arguments passed /// in. There is a field in `args` for each parameter. The name of that field will be the result /// of this expression: /// ``` /// param.names.longest().name` /// ``` /// /// The fields can have types other that `[]const u8` and this is based on what `value_parsers` /// you provide. The parser to use for each parameter is determined by the following expression: /// ``` /// @field(value_parsers, param.id.value()) /// ``` /// /// Where `value` is a function that returns the name of the value this parameter takes. A parser /// is simple a function with the signature: /// ``` /// fn ([]const u8) Error!T /// ``` /// /// `T` can be any type and `Error` can be any error. You can pass `clap.parsers.default` if you /// just wonna get something up and running. /// /// Caller owns the result and should free it by calling `result.deinit()` pub fn parseEx( comptime Id: type, comptime params: []const Param(Id), comptime value_parsers: anytype, iter: anytype, opt: ParseOptions, ) !ResultEx(Id, params, value_parsers) { const allocator = opt.allocator; const Positional = FindPositionalType(Id, params, value_parsers); var positionals = std.ArrayList(Positional).init(allocator); var arguments = Arguments(Id, params, value_parsers, .list){}; errdefer deinitArgs(Id, params, allocator, &arguments); var stream = streaming.Clap(Id, meta.Child(@TypeOf(iter))){ .params = params, .iter = iter, .diagnostic = opt.diagnostic, .assignment_separators = opt.assignment_separators, }; while (try stream.next()) |arg| { // TODO: We cannot use `try` inside the inline for because of a compiler bug that // generates an infinite loop. For now, use a variable to store the error // and use `try` outside. The downside of this is that we have to use // `anyerror` :( var res: anyerror!void = {}; inline for (params) |*param| { if (param == arg.param) { res = parseArg( Id, param.*, value_parsers, allocator, &arguments, &positionals, arg, ); } } try res; } // We are done parsing, but our arguments are stored in lists, and not slices. Map the list // fields to slices and return that. var result_args = Arguments(Id, params, value_parsers, .slice){}; inline for (meta.fields(@TypeOf(arguments))) |field| { if (@typeInfo(field.type) == .@"struct" and @hasDecl(field.type, "toOwnedSlice")) { const slice = try @field(arguments, field.name).toOwnedSlice(allocator); @field(result_args, field.name) = slice; } else { @field(result_args, field.name) = @field(arguments, field.name); } } return ResultEx(Id, params, value_parsers){ .args = result_args, .positionals = try positionals.toOwnedSlice(), .allocator = allocator, }; } fn parseArg( comptime Id: type, comptime param: Param(Id), comptime value_parsers: anytype, allocator: mem.Allocator, arguments: anytype, positionals: anytype, arg: streaming.Arg(Id), ) !void { const parser = comptime switch (param.takes_value) { .none => undefined, .one, .many => @field(value_parsers, param.id.value()), }; const longest = comptime param.names.longest(); const name = longest.name[0..longest.name.len].*; switch (longest.kind) { .short, .long => switch (param.takes_value) { .none => @field(arguments, &name) +|= 1, .one => @field(arguments, &name) = try parser(arg.value.?), .many => { const value = try parser(arg.value.?); try @field(arguments, &name).append(allocator, value); }, }, .positional => try positionals.append(try parser(arg.value.?)), } } /// The result of `parseEx`. Is owned by the caller and should be freed with `deinit`. pub fn ResultEx( comptime Id: type, comptime params: []const Param(Id), comptime value_parsers: anytype, ) type { return struct { args: Arguments(Id, params, value_parsers, .slice), positionals: []const FindPositionalType(Id, params, value_parsers), allocator: mem.Allocator, pub fn deinit(result: *@This()) void { deinitArgs(Id, params, result.allocator, &result.args); result.allocator.free(result.positionals); } }; } fn FindPositionalType( comptime Id: type, comptime params: []const Param(Id), comptime value_parsers: anytype, ) type { const pos = findPositional(Id, params) orelse return []const u8; return ParamType(Id, pos, value_parsers); } fn findPositional(comptime Id: type, params: []const Param(Id)) ?Param(Id) { for (params) |param| { const longest = param.names.longest(); if (longest.kind == .positional) return param; } return null; } /// Given a parameter figure out which type that parameter is parsed into when using the correct /// parser from `value_parsers`. fn ParamType( comptime Id: type, comptime param: Param(Id), comptime value_parsers: anytype, ) type { const parser = switch (param.takes_value) { .none => parsers.string, .one, .many => @field(value_parsers, param.id.value()), }; return parsers.Result(@TypeOf(parser)); } /// Deinitializes a struct of type `Argument`. Since the `Argument` type is generated, and we /// cannot add the deinit declaration to it, we declare it here instead. fn deinitArgs( comptime Id: type, comptime params: []const Param(Id), allocator: mem.Allocator, arguments: anytype, ) void { inline for (params) |param| { const longest = comptime param.names.longest(); if (longest.kind == .positional) continue; if (param.takes_value != .many) continue; const field = @field(arguments, longest.name); // If the multi value field is a struct, we know it is a list and should be deinited. // Otherwise, it is a slice that should be freed. switch (@typeInfo(@TypeOf(field))) { .@"struct" => @field(arguments, longest.name).deinit(allocator), else => allocator.free(@field(arguments, longest.name)), } } } const MultiArgKind = enum { slice, list }; /// Turn a list of parameters into a struct with one field for each none positional parameter. /// The type of each parameter field is determined by `ParamType`. Positional arguments will not /// have a field in this struct. fn Arguments( comptime Id: type, comptime params: []const Param(Id), comptime value_parsers: anytype, comptime multi_arg_kind: MultiArgKind, ) type { var fields_len: usize = 0; for (params) |param| { const longest = param.names.longest(); if (longest.kind == .positional) continue; fields_len += 1; } var fields: [fields_len]builtin.Type.StructField = undefined; var i: usize = 0; for (params) |param| { const longest = param.names.longest(); if (longest.kind == .positional) continue; const T = ParamType(Id, param, value_parsers); const default_value = switch (param.takes_value) { .none => @as(u8, 0), .one => @as(?T, null), .many => switch (multi_arg_kind) { .slice => @as([]const T, &[_]T{}), .list => std.ArrayListUnmanaged(T){}, }, }; const name = longest.name[0..longest.name.len] ++ ""; // Adds null terminator fields[i] = .{ .name = name, .type = @TypeOf(default_value), .default_value = @ptrCast(&default_value), .is_comptime = false, .alignment = @alignOf(@TypeOf(default_value)), }; i += 1; } return @Type(.{ .@"struct" = .{ .layout = .auto, .fields = &fields, .decls = &.{}, .is_tuple = false, } }); } test "str and u64" { const params = comptime parseParamsComptime( \\--str <str> \\--num <u64> \\ ); var iter = args.SliceIterator{ .args = &.{ "--num", "10", "--str", "cooley_rec_inp_ptr" }, }; var res = try parseEx(Help, &params, parsers.default, &iter, .{ .allocator = testing.allocator, }); defer res.deinit(); } test "different assignment separators" { const params = comptime parseParamsComptime( \\-a, --aa <usize>... \\ ); var iter = args.SliceIterator{ .args = &.{ "-a=0", "--aa=1", "-a:2", "--aa:3" }, }; var res = try parseEx(Help, &params, parsers.default, &iter, .{ .allocator = testing.allocator, .assignment_separators = "=:", }); defer res.deinit(); try testing.expectEqualSlices(usize, &.{ 0, 1, 2, 3 }, res.args.aa); } test "everything" { const params = comptime parseParamsComptime( \\-a, --aa \\-b, --bb \\-c, --cc <str> \\-d, --dd <usize>... \\-h \\<str> \\ ); var iter = args.SliceIterator{ .args = &.{ "-a", "--aa", "-c", "0", "something", "-d", "1", "--dd", "2", "-h" }, }; var res = try parseEx(Help, &params, parsers.default, &iter, .{ .allocator = testing.allocator, }); defer res.deinit(); try testing.expect(res.args.aa == 2); try testing.expect(res.args.bb == 0); try testing.expect(res.args.h == 1); try testing.expectEqualStrings("0", res.args.cc.?); try testing.expectEqual(@as(usize, 1), res.positionals.len); try testing.expectEqualStrings("something", res.positionals[0]); try testing.expectEqualSlices(usize, &.{ 1, 2 }, res.args.dd); } test "overflow-safe" { const params = comptime parseParamsComptime( \\-a, --aa ); var iter = args.SliceIterator{ .args = &(.{"-" ++ ("a" ** 300)}), }; // This just needs to not crash var res = try parseEx(Help, &params, parsers.default, &iter, .{ .allocator = testing.allocator, }); defer res.deinit(); } test "empty" { var iter = args.SliceIterator{ .args = &.{} }; var res = try parseEx(u8, &[_]Param(u8){}, parsers.default, &iter, .{ .allocator = testing.allocator, }); defer res.deinit(); } fn testErr( comptime params: []const Param(Help), args_strings: []const []const u8, expected: []const u8, ) !void { var diag = Diagnostic{}; var iter = args.SliceIterator{ .args = args_strings }; _ = parseEx(Help, params, parsers.default, &iter, .{ .allocator = testing.allocator, .diagnostic = &diag, }) catch |err| { var buf: [1024]u8 = undefined; var fbs = io.fixedBufferStream(&buf); diag.report(fbs.writer(), err) catch return error.TestFailed; try testing.expectEqualStrings(expected, fbs.getWritten()); return; }; try testing.expect(false); } test "errors" { const params = comptime parseParamsComptime( \\-a, --aa \\-c, --cc <str> \\ ); try testErr(&params, &.{"q"}, "Invalid argument 'q'\n"); try testErr(&params, &.{"-q"}, "Invalid argument '-q'\n"); try testErr(&params, &.{"--q"}, "Invalid argument '--q'\n"); try testErr(&params, &.{"--q=1"}, "Invalid argument '--q'\n"); try testErr(&params, &.{"-a=1"}, "The argument '-a' does not take a value\n"); try testErr(&params, &.{"--aa=1"}, "The argument '--aa' does not take a value\n"); try testErr(&params, &.{"-c"}, "The argument '-c' requires a value but none was supplied\n"); try testErr( &params, &.{"--cc"}, "The argument '--cc' requires a value but none was supplied\n", ); } pub const Help = struct { desc: []const u8 = "", val: []const u8 = "", pub fn description(h: Help) []const u8 { return h.desc; } pub fn value(h: Help) []const u8 { return h.val; } }; pub const HelpOptions = struct { /// Render the description of a parameter in a simular way to how markdown would render /// such a string. This means that single newlines won't be respected unless followed by /// bullet points or other markdown elements. markdown_lite: bool = true, /// Whether `help` should print the description of a parameter on a new line instead of after /// the parameter names. This options works together with `description_indent` to change /// where descriptions are printed. /// /// description_on_new_line=false, description_indent=4 /// /// -a, --aa <v> This is a description /// that is not placed on /// a new line. /// /// description_on_new_line=true, description_indent=4 /// /// -a, --aa <v> /// This is a description /// that is placed on a /// new line. description_on_new_line: bool = true, /// How much to indent descriptions. See `description_on_new_line` for examples of how this /// changes the output. description_indent: usize = 8, /// How much to indent each parameter. /// /// indent=0, description_on_new_line=false, description_indent=4 /// /// -a, --aa <v> This is a description /// that is not placed on /// a new line. /// /// indent=4, description_on_new_line=false, description_indent=4 /// /// -a, --aa <v> This is a description /// that is not placed on /// a new line. /// indent: usize = 4, /// The maximum width of the help message. `help` will try to break the description of /// parameters into multiple lines if they exceed this maximum. Setting this to the width /// of the terminal is a nice way of using this option. max_width: usize = std.math.maxInt(usize), /// The number of empty lines between each printed parameter. spacing_between_parameters: usize = 1, }; /// Print a slice of `Param` formatted as a help string to `writer`. This function expects /// `Id` to have the methods `description` and `value` which are used by `help` to describe /// each parameter. Using `Help` as `Id` is good choice. /// /// The output can be constumized with the `opt` parameter. For default formatting `.{}` can /// be passed. pub fn help( writer: anytype, comptime Id: type, params: []const Param(Id), opt: HelpOptions, ) !void { const max_spacing = blk: { var res: usize = 0; for (params) |param| { var cs = ccw.codepointCountingWriter(io.null_writer); try printParam(cs.writer(), Id, param); if (res < cs.codepoints_written) res = @intCast(cs.codepoints_written); } break :blk res; }; const description_indentation = opt.indent + opt.description_indent + max_spacing * @intFromBool(!opt.description_on_new_line); var first_parameter: bool = true; for (params) |param| { if (!first_parameter) try writer.writeByteNTimes('\n', opt.spacing_between_parameters); first_parameter = false; try writer.writeByteNTimes(' ', opt.indent); var cw = ccw.codepointCountingWriter(writer); try printParam(cw.writer(), Id, param); const Writer = DescriptionWriter(@TypeOf(writer)); var description_writer = Writer{ .underlying_writer = writer, .indentation = description_indentation, .printed_chars = @intCast(cw.codepoints_written), .max_width = opt.max_width, }; if (opt.description_on_new_line) try description_writer.newline(); const min_description_indent = blk: { const description = param.id.description(); var first_line = true; var res: usize = std.math.maxInt(usize); var it = mem.tokenizeScalar(u8, description, '\n'); while (it.next()) |line| : (first_line = false) { const trimmed = mem.trimLeft(u8, line, " "); const indent = line.len - trimmed.len; // If the first line has no indentation, then we ignore the indentation of the // first line. We do this as the parameter might have been parsed from: // // -a, --aa The first line // is not indented, // but the rest of // the lines are. // // In this case, we want to pretend that the first line has the same indentation // as the min_description_indent, even though it is not so in the string we get. if (first_line and indent == 0) continue; if (indent < res) res = indent; } break :blk res; }; const description = param.id.description(); var it = mem.splitScalar(u8, description, '\n'); var first_line = true; var non_emitted_newlines: usize = 0; var last_line_indentation: usize = 0; while (it.next()) |raw_line| : (first_line = false) { // First line might be special. See comment above. const indented_line = if (first_line and !mem.startsWith(u8, raw_line, " ")) raw_line else raw_line[@min(min_description_indent, raw_line.len)..]; const line = mem.trimLeft(u8, indented_line, " "); if (line.len == 0) { non_emitted_newlines += 1; continue; } const line_indentation = indented_line.len - line.len; description_writer.indentation = description_indentation + line_indentation; if (opt.markdown_lite) { const new_paragraph = non_emitted_newlines > 1; const does_not_have_same_indent_as_last_line = line_indentation != last_line_indentation; const starts_with_control_char = mem.indexOfScalar(u8, "=*", line[0]) != null; // Either the input contains 2 or more newlines, in which case we should start // a new paragraph. if (new_paragraph) { try description_writer.newline(); try description_writer.newline(); } // Or this line has a special control char or different indentation which means // we should output it on a new line as well. else if (starts_with_control_char or does_not_have_same_indent_as_last_line) { try description_writer.newline(); } } else { // For none markdown like format, we just respect the newlines in the input // string and output them as is. for (0..non_emitted_newlines) |_| try description_writer.newline(); } var words = mem.tokenizeScalar(u8, line, ' '); while (words.next()) |word| try description_writer.writeWord(word); // We have not emitted the end of this line yet. non_emitted_newlines = 1; last_line_indentation = line_indentation; } try writer.writeAll("\n"); } } fn DescriptionWriter(comptime UnderlyingWriter: type) type { return struct { pub const WriteError = UnderlyingWriter.Error; underlying_writer: UnderlyingWriter, indentation: usize, max_width: usize, printed_chars: usize, pub fn writeWord(writer: *@This(), word: []const u8) !void { debug.assert(word.len != 0); var first_word = writer.printed_chars <= writer.indentation; const chars_to_write = try std.unicode.utf8CountCodepoints(word) + @intFromBool(!first_word); if (chars_to_write + writer.printed_chars > writer.max_width) { // If the word does not fit on this line, then we insert a new line and print // it on that line. The only exception to this is if this was the first word. // If the first word does not fit on this line, then it will also not fit on the // next one. In that case, all we can really do is just output the word. if (!first_word) try writer.newline(); first_word = true; } if (!first_word) try writer.underlying_writer.writeAll(" "); try writer.ensureIndented(); try writer.underlying_writer.writeAll(word); writer.printed_chars += chars_to_write; } pub fn newline(writer: *@This()) !void { try writer.underlying_writer.writeAll("\n"); writer.printed_chars = 0; } fn ensureIndented(writer: *@This()) !void { if (writer.printed_chars < writer.indentation) { const to_indent = writer.indentation - writer.printed_chars; try writer.underlying_writer.writeByteNTimes(' ', to_indent); writer.printed_chars += to_indent; } } }; } fn printParam( stream: anytype, comptime Id: type, param: Param(Id), ) !void { if (param.names.short != null or param.names.long != null) { try stream.writeAll(&[_]u8{ if (param.names.short) |_| '-' else ' ', param.names.short orelse ' ', }); if (param.names.long) |l| { try stream.writeByte(if (param.names.short) |_| ',' else ' '); try stream.writeAll(" --"); try stream.writeAll(l); } if (param.takes_value != .none) try stream.writeAll(" "); } if (param.takes_value == .none) return; try stream.writeAll("<"); try stream.writeAll(param.id.value()); try stream.writeAll(">"); if (param.takes_value == .many) try stream.writeAll("..."); } fn testHelp(opt: HelpOptions, str: []const u8) !void { const params = try parseParams(testing.allocator, str); defer testing.allocator.free(params); var buf: [2048]u8 = undefined; var fbs = io.fixedBufferStream(&buf); try help(fbs.writer(), Help, params, opt); try testing.expectEqualStrings(str, fbs.getWritten()); } test "clap.help" { try testHelp(.{}, \\ -a \\ Short flag. \\ \\ -b <V1> \\ Short option. \\ \\ --aa \\ Long flag. \\ \\ --bb <V2> \\ Long option. \\ \\ -c, --cc \\ Both flag. \\ \\ --complicate \\ Flag with a complicated and very long description that spans multiple lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something something something \\ \\ -d, --dd <V3> \\ Both option. \\ \\ -d, --dd <V3>... \\ Both repeated option. \\ \\ <A> \\ Help text \\ \\ <B>... \\ Another help text \\ ); try testHelp(.{ .markdown_lite = false }, \\ -a \\ Short flag. \\ \\ -b <V1> \\ Short option. \\ \\ --aa \\ Long flag. \\ \\ --bb <V2> \\ Long option. \\ \\ -c, --cc \\ Both flag. \\ \\ --complicate \\ Flag with a complicated and \\ very long description that \\ spans multiple lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ \\ Example: \\ something something something \\ \\ -d, --dd <V3> \\ Both option. \\ \\ -d, --dd <V3>... \\ Both repeated option. \\ ); try testHelp(.{ .indent = 0 }, \\-a \\ Short flag. \\ \\-b <V1> \\ Short option. \\ \\ --aa \\ Long flag. \\ \\ --bb <V2> \\ Long option. \\ \\-c, --cc \\ Both flag. \\ \\ --complicate \\ Flag with a complicated and very long description that spans multiple lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something something something \\ \\-d, --dd <V3> \\ Both option. \\ \\-d, --dd <V3>... \\ Both repeated option. \\ ); try testHelp(.{ .indent = 0 }, \\-a \\ Short flag. \\ \\-b <V1> \\ Short option. \\ \\ --aa \\ Long flag. \\ \\ --bb <V2> \\ Long option. \\ \\-c, --cc \\ Both flag. \\ \\ --complicate \\ Flag with a complicated and very long description that spans multiple lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something something something \\ \\-d, --dd <V3> \\ Both option. \\ \\-d, --dd <V3>... \\ Both repeated option. \\ ); try testHelp(.{ .indent = 0, .max_width = 26 }, \\-a \\ Short flag. \\ \\-b <V1> \\ Short option. \\ \\ --aa \\ Long flag. \\ \\ --bb <V2> \\ Long option. \\ \\-c, --cc \\ Both flag. \\ \\ --complicate \\ Flag with a \\ complicated and \\ very long \\ description that \\ spans multiple \\ lines. \\ \\ Paragraph number \\ 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something \\ something \\ something \\ \\-d, --dd <V3> \\ Both option. \\ \\-d, --dd <V3>... \\ Both repeated \\ option. \\ ); try testHelp(.{ .indent = 0, .max_width = 26, .description_indent = 6, }, \\-a \\ Short flag. \\ \\-b <V1> \\ Short option. \\ \\ --aa \\ Long flag. \\ \\ --bb <V2> \\ Long option. \\ \\-c, --cc \\ Both flag. \\ \\ --complicate \\ Flag with a \\ complicated and \\ very long \\ description that \\ spans multiple \\ lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something \\ something \\ something \\ \\-d, --dd <V3> \\ Both option. \\ \\-d, --dd <V3>... \\ Both repeated \\ option. \\ ); try testHelp(.{ .indent = 0, .max_width = 46, .description_on_new_line = false, }, \\-a Short flag. \\ \\-b <V1> Short option. \\ \\ --aa Long flag. \\ \\ --bb <V2> Long option. \\ \\-c, --cc Both flag. \\ \\ --complicate Flag with a \\ complicated and very \\ long description that \\ spans multiple lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something \\ something \\ something \\ \\-d, --dd <V3> Both option. \\ \\-d, --dd <V3>... Both repeated option. \\ ); try testHelp(.{ .indent = 0, .max_width = 46, .description_on_new_line = false, .description_indent = 4, }, \\-a Short flag. \\ \\-b <V1> Short option. \\ \\ --aa Long flag. \\ \\ --bb <V2> Long option. \\ \\-c, --cc Both flag. \\ \\ --complicate Flag with a complicated \\ and very long description \\ that spans multiple \\ lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something something \\ something \\ \\-d, --dd <V3> Both option. \\ \\-d, --dd <V3>... Both repeated option. \\ ); try testHelp(.{ .indent = 0, .max_width = 46, .description_on_new_line = false, .description_indent = 4, .spacing_between_parameters = 0, }, \\-a Short flag. \\-b <V1> Short option. \\ --aa Long flag. \\ --bb <V2> Long option. \\-c, --cc Both flag. \\ --complicate Flag with a complicated \\ and very long description \\ that spans multiple \\ lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something something \\ something \\-d, --dd <V3> Both option. \\-d, --dd <V3>... Both repeated option. \\ ); try testHelp(.{ .indent = 0, .max_width = 46, .description_on_new_line = false, .description_indent = 4, .spacing_between_parameters = 2, }, \\-a Short flag. \\ \\ \\-b <V1> Short option. \\ \\ \\ --aa Long flag. \\ \\ \\ --bb <V2> Long option. \\ \\ \\-c, --cc Both flag. \\ \\ \\ --complicate Flag with a complicated \\ and very long description \\ that spans multiple \\ lines. \\ \\ Paragraph number 2: \\ * Bullet point \\ * Bullet point \\ \\ Example: \\ something something \\ something \\ \\ \\-d, --dd <V3> Both option. \\ \\ \\-d, --dd <V3>... Both repeated option. \\ ); // Test with multibyte characters. try testHelp(.{ .indent = 0, .max_width = 46, .description_on_new_line = false, .description_indent = 4, .spacing_between_parameters = 2, }, \\-a Shört flåg. \\ \\ \\-b <V1> Shört öptiön. \\ \\ \\ --aa Löng fläg. \\ \\ \\ --bb <V2> Löng öptiön. \\ \\ \\-c, --cc Bóth fläg. \\ \\ \\ --complicate Fläg wíth ä cömplǐcätéd \\ änd vërý löng dèscrıptıön \\ thät späns mültíplë \\ lınēs. \\ \\ Pärägräph number 2: \\ * Bullet pöint \\ * Bullet pöint \\ \\ Exämple: \\ sömething sömething \\ sömething \\ \\ \\-d, --dd <V3> Böth öptiön. \\ \\ \\-d, --dd <V3>... Böth repeäted öptiön. \\ ); } /// Will print a usage message in the following format: /// [-abc] [--longa] [-d <T>] [--longb <T>] <T> /// /// First all none value taking parameters, which have a short name are printed, then non /// positional parameters and finally the positional. pub fn usage(stream: anytype, comptime Id: type, params: []const Param(Id)) !void { var cos = ccw.codepointCountingWriter(stream); const cs = cos.writer(); for (params) |param| { const name = param.names.short orelse continue; if (param.takes_value != .none) continue; if (cos.codepoints_written == 0) try stream.writeAll("[-"); try cs.writeByte(name); } if (cos.codepoints_written != 0) try cs.writeAll("]"); var has_positionals: bool = false; for (params) |param| { if (param.takes_value == .none and param.names.short != null) continue; const prefix = if (param.names.short) |_| "-" else "--"; const name = blk: { if (param.names.short) |*s| break :blk @as(*const [1]u8, s); if (param.names.long) |l| break :blk l; has_positionals = true; continue; }; if (cos.codepoints_written != 0) try cs.writeAll(" "); try cs.writeAll("["); try cs.writeAll(prefix); try cs.writeAll(name); if (param.takes_value != .none) { try cs.writeAll(" <"); try cs.writeAll(param.id.value()); try cs.writeAll(">"); if (param.takes_value == .many) try cs.writeAll("..."); } try cs.writeByte(']'); } if (!has_positionals) return; for (params) |param| { if (param.names.short != null or param.names.long != null) continue; if (cos.codepoints_written != 0) try cs.writeAll(" "); try cs.writeAll("<"); try cs.writeAll(param.id.value()); try cs.writeAll(">"); if (param.takes_value == .many) try cs.writeAll("..."); } } fn testUsage(expected: []const u8, params: []const Param(Help)) !void { var buf: [1024]u8 = undefined; var fbs = io.fixedBufferStream(&buf); try usage(fbs.writer(), Help, params); try testing.expectEqualStrings(expected, fbs.getWritten()); } test "usage" { @setEvalBranchQuota(100000); try testUsage("[-ab]", &comptime parseParamsComptime( \\-a \\-b \\ )); try testUsage("[-a <value>] [-b <v>]", &comptime parseParamsComptime( \\-a <value> \\-b <v> \\ )); try testUsage("[--a] [--b]", &comptime parseParamsComptime( \\--a \\--b \\ )); try testUsage("[--a <value>] [--b <v>]", &comptime parseParamsComptime( \\--a <value> \\--b <v> \\ )); try testUsage("<file>", &comptime parseParamsComptime( \\<file> \\ )); try testUsage("<file>...", &comptime parseParamsComptime( \\<file>... \\ )); try testUsage( "[-ab] [-c <value>] [-d <v>] [--e] [--f] [--g <value>] [--h <v>] [-i <v>...] <file>", &comptime parseParamsComptime( \\-a \\-b \\-c <value> \\-d <v> \\--e \\--f \\--g <value> \\--h <v> \\-i <v>... \\<file> \\ ), ); try testUsage("<number> <file> <file>", &comptime parseParamsComptime( \\<number> \\<file> \\<file> \\ )); try testUsage("<number> <outfile> <infile>...", &comptime parseParamsComptime( \\<number> \\<outfile> \\<infile>... \\ )); }
0
repos
repos/zig-clap/README.md
<!--- README.md is autogenerated. Please edit example/README.md.template instead. --> # zig-clap A simple and easy to use command line argument parser library for Zig. The master branch of zig-clap targets the master branch of Zig. For a version of zig-clap that targets a specific Zig release, have a look at the releases. Each release specifies the Zig version it compiles with in the release notes. ## Installation First, run the following: ``` zig fetch --save git+https://github.com/Hejsil/zig-clap ``` Then add the following to `build.zig`: ```zig const clap = b.dependency("clap", .{}); exe.root_module.addImport("clap", clap.module("clap")); ``` ## Features * Short arguments `-a` * Chaining `-abc` where `a` and `b` does not take values. * Multiple specifications are tallied (e.g. `-v -v`). * Long arguments `--long` * Supports both passing values using spacing and `=` (`-a 100`, `-a=100`) * Short args also support passing values with no spacing or `=` (`-a100`) * This all works with chaining (`-ba 100`, `-ba=100`, `-ba100`) * Supports options that can be specified multiple times (`-e 1 -e 2 -e 3`) * Print help message from parameter specification. * Parse help message to parameter specification. ## API Reference Automatically generated API Reference for the project can be found at https://Hejsil.github.io/zig-clap. Note that Zig autodoc is in beta; the website may be broken or incomplete. ## Examples ### `clap.parse` The simplest way to use this library is to just call the `clap.parse` function. ```zig const clap = @import("clap"); const std = @import("std"); const debug = std.debug; const io = std.io; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // First we specify what parameters our program can take. // We can use `parseParamsComptime` to parse a string into an array of `Param(Help)` const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-n, --number <usize> An option parameter, which takes a value. \\-s, --string <str>... An option parameter which can be specified multiple times. \\<str>... \\ ); // Initialize our diagnostics, which can be used for reporting useful errors. // This is optional. You can also pass `.{}` to `clap.parse` if you don't // care about the extra information `Diagnostics` provides. var diag = clap.Diagnostic{}; var res = clap.parse(clap.Help, &params, clap.parsers.default, .{ .diagnostic = &diag, .allocator = gpa.allocator(), }) catch |err| { // Report useful error and exit diag.report(io.getStdErr().writer(), err) catch {}; return err; }; defer res.deinit(); if (res.args.help != 0) debug.print("--help\n", .{}); if (res.args.number) |n| debug.print("--number = {}\n", .{n}); for (res.args.string) |s| debug.print("--string = {s}\n", .{s}); for (res.positionals) |pos| debug.print("{s}\n", .{pos}); } ``` The result will contain an `args` field and a `positionals` field. `args` will have one field for each none positional parameter of your program. The name of the field will be the longest name of the parameter. The fields in `args` are typed. The type is based on the name of the value the parameter takes. Since `--number` takes a `usize` the field `res.args.number` has the type `usize`. Note that this is only the case because `clap.parsers.default` has a field called `usize` which contains a parser that returns `usize`. You can pass in something other than `clap.parsers.default` if you want some other mapping. ```zig const clap = @import("clap"); const std = @import("std"); const debug = std.debug; const io = std.io; const process = std.process; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // First we specify what parameters our program can take. // We can use `parseParamsComptime` to parse a string into an array of `Param(Help)` const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-n, --number <INT> An option parameter, which takes a value. \\-a, --answer <ANSWER> An option parameter which takes an enum. \\-s, --string <STR>... An option parameter which can be specified multiple times. \\<FILE>... \\ ); // Declare our own parsers which are used to map the argument strings to other // types. const YesNo = enum { yes, no }; const parsers = comptime .{ .STR = clap.parsers.string, .FILE = clap.parsers.string, .INT = clap.parsers.int(usize, 10), .ANSWER = clap.parsers.enumeration(YesNo), }; var diag = clap.Diagnostic{}; var res = clap.parse(clap.Help, &params, parsers, .{ .diagnostic = &diag, .allocator = gpa.allocator(), // The assignment separator can be configured. `--number=1` and `--number:1` is now // allowed. .assignment_separators = "=:", }) catch |err| { diag.report(io.getStdErr().writer(), err) catch {}; return err; }; defer res.deinit(); if (res.args.help != 0) debug.print("--help\n", .{}); if (res.args.number) |n| debug.print("--number = {}\n", .{n}); if (res.args.answer) |a| debug.print("--answer = {s}\n", .{@tagName(a)}); for (res.args.string) |s| debug.print("--string = {s}\n", .{s}); for (res.positionals) |pos| debug.print("{s}\n", .{pos}); } ``` ### `streaming.Clap` The `streaming.Clap` is the base of all the other parsers. It's a streaming parser that uses an `args.Iterator` to provide it with arguments lazily. ```zig const clap = @import("clap"); const std = @import("std"); const debug = std.debug; const io = std.io; const process = std.process; pub fn main() !void { const allocator = std.heap.page_allocator; // First we specify what parameters our program can take. const params = [_]clap.Param(u8){ .{ .id = 'h', .names = .{ .short = 'h', .long = "help" }, }, .{ .id = 'n', .names = .{ .short = 'n', .long = "number" }, .takes_value = .one, }, .{ .id = 'f', .takes_value = .one }, }; var iter = try process.ArgIterator.initWithAllocator(allocator); defer iter.deinit(); // Skip exe argument _ = iter.next(); // Initialize our diagnostics, which can be used for reporting useful errors. // This is optional. You can also leave the `diagnostic` field unset if you // don't care about the extra information `Diagnostic` provides. var diag = clap.Diagnostic{}; var parser = clap.streaming.Clap(u8, process.ArgIterator){ .params = &params, .iter = &iter, .diagnostic = &diag, }; // Because we use a streaming parser, we have to consume each argument parsed individually. while (parser.next() catch |err| { // Report useful error and exit diag.report(io.getStdErr().writer(), err) catch {}; return err; }) |arg| { // arg.param will point to the parameter which matched the argument. switch (arg.param.id) { 'h' => debug.print("Help!\n", .{}), 'n' => debug.print("--number = {s}\n", .{arg.value.?}), // arg.value == null, if arg.param.takes_value == .none. // Otherwise, arg.value is the value passed with the argument, such as "-a=10" // or "-a 10". 'f' => debug.print("{s}\n", .{arg.value.?}), else => unreachable, } } } ``` Currently, this parser is the only parser that allows an array of `Param` that is generated at runtime. ### `help` The `help` prints a simple list of all parameters the program can take. It expects the `Id` to have a `description` method and an `value` method so that it can provide that in the output. `HelpOptions` is passed to `help` to control how the help message is printed. ```zig const clap = @import("clap"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-v, --version Output version information and exit. \\ ); var res = try clap.parse(clap.Help, &params, clap.parsers.default, .{ .allocator = gpa.allocator(), }); defer res.deinit(); // `clap.help` is a function that can print a simple help message. It can print any `Param` // where `Id` has a `describtion` and `value` method (`Param(Help)` is one such parameter). // The last argument contains options as to how `help` should print those parameters. Using // `.{}` means the default options. if (res.args.help != 0) return clap.help(std.io.getStdErr().writer(), clap.Help, &params, .{}); } ``` ``` $ zig-out/bin/help --help -h, --help Display this help and exit. -v, --version Output version information and exit. ``` ### `usage` The `usage` prints a small abbreviated version of the help message. It expects the `Id` to have a `value` method so it can provide that in the output. ```zig const clap = @import("clap"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-v, --version Output version information and exit. \\ --value <str> An option parameter, which takes a value. \\ ); var res = try clap.parse(clap.Help, &params, clap.parsers.default, .{ .allocator = gpa.allocator(), }); defer res.deinit(); // `clap.usage` is a function that can print a simple help message. It can print any `Param` // where `Id` has a `value` method (`Param(Help)` is one such parameter). if (res.args.help != 0) return clap.usage(std.io.getStdErr().writer(), clap.Help, &params); } ``` ``` $ zig-out/bin/usage --help [-hv] [--value <str>] ```
0
repos
repos/zig-clap/build.zig.zon
.{ .name = "clap", .version = "0.7.0", .paths = .{"."}, }
0
repos
repos/zig-clap/build.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const clap_mod = b.addModule("clap", .{ .root_source_file = b.path("clap.zig") }); const optimize = b.standardOptimizeOption(.{}); const target = b.standardTargetOptions(.{}); const test_step = b.step("test", "Run all tests in all modes."); const tests = b.addTest(.{ .root_source_file = b.path("clap.zig"), .target = target, .optimize = optimize, }); const run_tests = b.addRunArtifact(tests); test_step.dependOn(&run_tests.step); const example_step = b.step("examples", "Build examples"); for ([_][]const u8{ "simple", "simple-ex", "streaming-clap", "help", "usage", }) |example_name| { const example = b.addExecutable(.{ .name = example_name, .root_source_file = b.path(b.fmt("example/{s}.zig", .{example_name})), .target = target, .optimize = optimize, }); const install_example = b.addInstallArtifact(example, .{}); example.root_module.addImport("clap", clap_mod); example_step.dependOn(&example.step); example_step.dependOn(&install_example.step); } const docs_step = b.step("docs", "Generate docs."); const install_docs = b.addInstallDirectory(.{ .source_dir = tests.getEmittedDocs(), .install_dir = .prefix, .install_subdir = "docs", }); docs_step.dependOn(&install_docs.step); const readme_step = b.step("readme", "Remake README."); const readme = readMeStep(b); readme.dependOn(example_step); readme_step.dependOn(readme); const all_step = b.step("all", "Build everything and runs all tests"); all_step.dependOn(test_step); all_step.dependOn(example_step); all_step.dependOn(readme_step); b.default_step.dependOn(all_step); } fn readMeStep(b: *std.Build) *std.Build.Step { const s = b.allocator.create(std.Build.Step) catch unreachable; s.* = std.Build.Step.init(.{ .id = .custom, .name = "ReadMeStep", .owner = b, .makeFn = struct { fn make(step: *std.Build.Step, _: std.Build.Step.MakeOptions) anyerror!void { @setEvalBranchQuota(10000); _ = step; const file = try std.fs.cwd().createFile("README.md", .{}); const stream = file.writer(); try stream.print(@embedFile("example/README.md.template"), .{ @embedFile("example/simple.zig"), @embedFile("example/simple-ex.zig"), @embedFile("example/streaming-clap.zig"), @embedFile("example/help.zig"), @embedFile("example/usage.zig"), }); } }.make, }); return s; }
0
repos/zig-clap
repos/zig-clap/example/README.md.template
<!--- README.md is autogenerated. Please edit example/README.md.template instead. --> # zig-clap A simple and easy to use command line argument parser library for Zig. The master branch of zig-clap targets the master branch of Zig. For a version of zig-clap that targets a specific Zig release, have a look at the releases. Each release specifies the Zig version it compiles with in the release notes. ## Installation First, run the following: ``` zig fetch --save git+https://github.com/Hejsil/zig-clap ``` Then add the following to `build.zig`: ```zig const clap = b.dependency("clap", .{{}}); exe.root_module.addImport("clap", clap.module("clap")); ``` ## Features * Short arguments `-a` * Chaining `-abc` where `a` and `b` does not take values. * Multiple specifications are tallied (e.g. `-v -v`). * Long arguments `--long` * Supports both passing values using spacing and `=` (`-a 100`, `-a=100`) * Short args also support passing values with no spacing or `=` (`-a100`) * This all works with chaining (`-ba 100`, `-ba=100`, `-ba100`) * Supports options that can be specified multiple times (`-e 1 -e 2 -e 3`) * Print help message from parameter specification. * Parse help message to parameter specification. ## API Reference Automatically generated API Reference for the project can be found at https://Hejsil.github.io/zig-clap. Note that Zig autodoc is in beta; the website may be broken or incomplete. ## Examples ### `clap.parse` The simplest way to use this library is to just call the `clap.parse` function. ```zig {s} ``` The result will contain an `args` field and a `positionals` field. `args` will have one field for each none positional parameter of your program. The name of the field will be the longest name of the parameter. The fields in `args` are typed. The type is based on the name of the value the parameter takes. Since `--number` takes a `usize` the field `res.args.number` has the type `usize`. Note that this is only the case because `clap.parsers.default` has a field called `usize` which contains a parser that returns `usize`. You can pass in something other than `clap.parsers.default` if you want some other mapping. ```zig {s} ``` ### `streaming.Clap` The `streaming.Clap` is the base of all the other parsers. It's a streaming parser that uses an `args.Iterator` to provide it with arguments lazily. ```zig {s} ``` Currently, this parser is the only parser that allows an array of `Param` that is generated at runtime. ### `help` The `help` prints a simple list of all parameters the program can take. It expects the `Id` to have a `description` method and an `value` method so that it can provide that in the output. `HelpOptions` is passed to `help` to control how the help message is printed. ```zig {s} ``` ``` $ zig-out/bin/help --help -h, --help Display this help and exit. -v, --version Output version information and exit. ``` ### `usage` The `usage` prints a small abbreviated version of the help message. It expects the `Id` to have a `value` method so it can provide that in the output. ```zig {s} ``` ``` $ zig-out/bin/usage --help [-hv] [--value <str>] ```
0
repos/zig-clap
repos/zig-clap/example/streaming-clap.zig
const clap = @import("clap"); const std = @import("std"); const debug = std.debug; const io = std.io; const process = std.process; pub fn main() !void { const allocator = std.heap.page_allocator; // First we specify what parameters our program can take. const params = [_]clap.Param(u8){ .{ .id = 'h', .names = .{ .short = 'h', .long = "help" }, }, .{ .id = 'n', .names = .{ .short = 'n', .long = "number" }, .takes_value = .one, }, .{ .id = 'f', .takes_value = .one }, }; var iter = try process.ArgIterator.initWithAllocator(allocator); defer iter.deinit(); // Skip exe argument _ = iter.next(); // Initialize our diagnostics, which can be used for reporting useful errors. // This is optional. You can also leave the `diagnostic` field unset if you // don't care about the extra information `Diagnostic` provides. var diag = clap.Diagnostic{}; var parser = clap.streaming.Clap(u8, process.ArgIterator){ .params = &params, .iter = &iter, .diagnostic = &diag, }; // Because we use a streaming parser, we have to consume each argument parsed individually. while (parser.next() catch |err| { // Report useful error and exit diag.report(io.getStdErr().writer(), err) catch {}; return err; }) |arg| { // arg.param will point to the parameter which matched the argument. switch (arg.param.id) { 'h' => debug.print("Help!\n", .{}), 'n' => debug.print("--number = {s}\n", .{arg.value.?}), // arg.value == null, if arg.param.takes_value == .none. // Otherwise, arg.value is the value passed with the argument, such as "-a=10" // or "-a 10". 'f' => debug.print("{s}\n", .{arg.value.?}), else => unreachable, } } }
0
repos/zig-clap
repos/zig-clap/example/simple-ex.zig
const clap = @import("clap"); const std = @import("std"); const debug = std.debug; const io = std.io; const process = std.process; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // First we specify what parameters our program can take. // We can use `parseParamsComptime` to parse a string into an array of `Param(Help)` const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-n, --number <INT> An option parameter, which takes a value. \\-a, --answer <ANSWER> An option parameter which takes an enum. \\-s, --string <STR>... An option parameter which can be specified multiple times. \\<FILE>... \\ ); // Declare our own parsers which are used to map the argument strings to other // types. const YesNo = enum { yes, no }; const parsers = comptime .{ .STR = clap.parsers.string, .FILE = clap.parsers.string, .INT = clap.parsers.int(usize, 10), .ANSWER = clap.parsers.enumeration(YesNo), }; var diag = clap.Diagnostic{}; var res = clap.parse(clap.Help, &params, parsers, .{ .diagnostic = &diag, .allocator = gpa.allocator(), // The assignment separator can be configured. `--number=1` and `--number:1` is now // allowed. .assignment_separators = "=:", }) catch |err| { diag.report(io.getStdErr().writer(), err) catch {}; return err; }; defer res.deinit(); if (res.args.help != 0) debug.print("--help\n", .{}); if (res.args.number) |n| debug.print("--number = {}\n", .{n}); if (res.args.answer) |a| debug.print("--answer = {s}\n", .{@tagName(a)}); for (res.args.string) |s| debug.print("--string = {s}\n", .{s}); for (res.positionals) |pos| debug.print("{s}\n", .{pos}); }
0
repos/zig-clap
repos/zig-clap/example/usage.zig
const clap = @import("clap"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-v, --version Output version information and exit. \\ --value <str> An option parameter, which takes a value. \\ ); var res = try clap.parse(clap.Help, &params, clap.parsers.default, .{ .allocator = gpa.allocator(), }); defer res.deinit(); // `clap.usage` is a function that can print a simple help message. It can print any `Param` // where `Id` has a `value` method (`Param(Help)` is one such parameter). if (res.args.help != 0) return clap.usage(std.io.getStdErr().writer(), clap.Help, &params); }
0
repos/zig-clap
repos/zig-clap/example/help.zig
const clap = @import("clap"); const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-v, --version Output version information and exit. \\ ); var res = try clap.parse(clap.Help, &params, clap.parsers.default, .{ .allocator = gpa.allocator(), }); defer res.deinit(); // `clap.help` is a function that can print a simple help message. It can print any `Param` // where `Id` has a `describtion` and `value` method (`Param(Help)` is one such parameter). // The last argument contains options as to how `help` should print those parameters. Using // `.{}` means the default options. if (res.args.help != 0) return clap.help(std.io.getStdErr().writer(), clap.Help, &params, .{}); }
0
repos/zig-clap
repos/zig-clap/example/simple.zig
const clap = @import("clap"); const std = @import("std"); const debug = std.debug; const io = std.io; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); // First we specify what parameters our program can take. // We can use `parseParamsComptime` to parse a string into an array of `Param(Help)` const params = comptime clap.parseParamsComptime( \\-h, --help Display this help and exit. \\-n, --number <usize> An option parameter, which takes a value. \\-s, --string <str>... An option parameter which can be specified multiple times. \\<str>... \\ ); // Initialize our diagnostics, which can be used for reporting useful errors. // This is optional. You can also pass `.{}` to `clap.parse` if you don't // care about the extra information `Diagnostics` provides. var diag = clap.Diagnostic{}; var res = clap.parse(clap.Help, &params, clap.parsers.default, .{ .diagnostic = &diag, .allocator = gpa.allocator(), }) catch |err| { // Report useful error and exit diag.report(io.getStdErr().writer(), err) catch {}; return err; }; defer res.deinit(); if (res.args.help != 0) debug.print("--help\n", .{}); if (res.args.number) |n| debug.print("--number = {}\n", .{n}); for (res.args.string) |s| debug.print("--string = {s}\n", .{s}); for (res.positionals) |pos| debug.print("{s}\n", .{pos}); }
0
repos/zig-clap
repos/zig-clap/clap/parsers.zig
const std = @import("std"); const fmt = std.fmt; const testing = std.testing; pub const default = .{ .string = string, .str = string, .u8 = int(u8, 0), .u16 = int(u16, 0), .u32 = int(u32, 0), .u64 = int(u64, 0), .usize = int(usize, 0), .i8 = int(i8, 0), .i16 = int(i16, 0), .i32 = int(i32, 0), .i64 = int(i64, 0), .isize = int(isize, 0), .f32 = float(f32), .f64 = float(f64), }; /// A parser that does nothing. pub fn string(in: []const u8) error{}![]const u8 { return in; } test "string" { try testing.expectEqualStrings("aa", try string("aa")); } /// A parser that uses `std.fmt.parseInt` to parse the string into an integer value. /// See `std.fmt.parseInt` documentation for more information. pub fn int(comptime T: type, comptime base: u8) fn ([]const u8) fmt.ParseIntError!T { return struct { fn parse(in: []const u8) fmt.ParseIntError!T { return fmt.parseInt(T, in, base); } }.parse; } test "int" { try testing.expectEqual(@as(u8, 0), try int(u8, 10)("0")); try testing.expectEqual(@as(u8, 1), try int(u8, 10)("1")); try testing.expectEqual(@as(u8, 10), try int(u8, 10)("10")); try testing.expectEqual(@as(u8, 0b10), try int(u8, 2)("10")); try testing.expectEqual(@as(u8, 0x10), try int(u8, 0)("0x10")); try testing.expectEqual(@as(u8, 0b10), try int(u8, 0)("0b10")); try testing.expectEqual(@as(u16, 0), try int(u16, 10)("0")); try testing.expectEqual(@as(u16, 1), try int(u16, 10)("1")); try testing.expectEqual(@as(u16, 10), try int(u16, 10)("10")); try testing.expectEqual(@as(u16, 0b10), try int(u16, 2)("10")); try testing.expectEqual(@as(u16, 0x10), try int(u16, 0)("0x10")); try testing.expectEqual(@as(u16, 0b10), try int(u16, 0)("0b10")); } /// A parser that uses `std.fmt.parseFloat` to parse the string into an float value. /// See `std.fmt.parseFloat` documentation for more information. pub fn float(comptime T: type) fn ([]const u8) fmt.ParseFloatError!T { return struct { fn parse(in: []const u8) fmt.ParseFloatError!T { return fmt.parseFloat(T, in); } }.parse; } test "float" { try testing.expectEqual(@as(f32, 0), try float(f32)("0")); } pub const EnumError = error{ NameNotPartOfEnum, }; /// A parser that uses `std.meta.stringToEnum` to parse the string into an enum value. On `null`, /// this function returns the error `NameNotPartOfEnum`. /// See `std.meta.stringToEnum` documentation for more information. pub fn enumeration(comptime T: type) fn ([]const u8) EnumError!T { return struct { fn parse(in: []const u8) EnumError!T { return std.meta.stringToEnum(T, in) orelse error.NameNotPartOfEnum; } }.parse; } test "enumeration" { const E = enum { a, b, c }; try testing.expectEqual(E.a, try enumeration(E)("a")); try testing.expectEqual(E.b, try enumeration(E)("b")); try testing.expectEqual(E.c, try enumeration(E)("c")); try testing.expectError(EnumError.NameNotPartOfEnum, enumeration(E)("d")); } fn ReturnType(comptime P: type) type { return @typeInfo(P).@"fn".return_type.?; } pub fn Result(comptime P: type) type { return @typeInfo(ReturnType(P)).error_union.payload; }
0
repos/zig-clap
repos/zig-clap/clap/streaming.zig
const builtin = @import("builtin"); const clap = @import("../clap.zig"); const std = @import("std"); const args = clap.args; const debug = std.debug; const heap = std.heap; const io = std.io; const mem = std.mem; const os = std.os; const testing = std.testing; /// The result returned from Clap.next pub fn Arg(comptime Id: type) type { return struct { const Self = @This(); param: *const clap.Param(Id), value: ?[]const u8 = null, }; } pub const Error = error{ MissingValue, InvalidArgument, DoesntTakeValue, }; /// A command line argument parser which, given an ArgIterator, will parse arguments according /// to the params. Clap parses in an iterating manner, so you have to use a loop together with /// Clap.next to parse all the arguments of your program. /// /// This parser is the building block for all the more complicated parsers. pub fn Clap(comptime Id: type, comptime ArgIterator: type) type { return struct { const State = union(enum) { normal, chaining: Chaining, rest_are_positional, const Chaining = struct { arg: []const u8, index: usize, }; }; state: State = .normal, params: []const clap.Param(Id), iter: *ArgIterator, positional: ?*const clap.Param(Id) = null, diagnostic: ?*clap.Diagnostic = null, assignment_separators: []const u8 = clap.default_assignment_separators, /// Get the next Arg that matches a Param. pub fn next(parser: *@This()) !?Arg(Id) { switch (parser.state) { .normal => return try parser.normal(), .chaining => |state| return try parser.chaining(state), .rest_are_positional => { const param = parser.positionalParam() orelse unreachable; const value = parser.iter.next() orelse return null; return Arg(Id){ .param = param, .value = value }; }, } } fn normal(parser: *@This()) !?Arg(Id) { const arg_info = (try parser.parseNextArg()) orelse return null; const arg = arg_info.arg; switch (arg_info.kind) { .long => { const eql_index = mem.indexOfAny(u8, arg, parser.assignment_separators); const name = if (eql_index) |i| arg[0..i] else arg; const maybe_value = if (eql_index) |i| arg[i + 1 ..] else null; for (parser.params) |*param| { const match = param.names.long orelse continue; if (!mem.eql(u8, name, match)) continue; if (param.takes_value == .none) { if (maybe_value != null) return parser.err(arg, .{ .long = name }, Error.DoesntTakeValue); return Arg(Id){ .param = param }; } const value = blk: { if (maybe_value) |v| break :blk v; break :blk parser.iter.next() orelse return parser.err(arg, .{ .long = name }, Error.MissingValue); }; return Arg(Id){ .param = param, .value = value }; } return parser.err(arg, .{ .long = name }, Error.InvalidArgument); }, .short => return try parser.chaining(.{ .arg = arg, .index = 0, }), .positional => if (parser.positionalParam()) |param| { // If we find a positional with the value `--` then we // interpret the rest of the arguments as positional // arguments. if (mem.eql(u8, arg, "--")) { parser.state = .rest_are_positional; const value = parser.iter.next() orelse return null; return Arg(Id){ .param = param, .value = value }; } return Arg(Id){ .param = param, .value = arg }; } else { return parser.err(arg, .{}, Error.InvalidArgument); }, } } fn chaining(parser: *@This(), state: State.Chaining) !?Arg(Id) { const arg = state.arg; const index = state.index; const next_index = index + 1; for (parser.params) |*param| { const short = param.names.short orelse continue; if (short != arg[index]) continue; // Before we return, we have to set the new state of the clap defer { if (arg.len <= next_index or param.takes_value != .none) { parser.state = .normal; } else { parser.state = .{ .chaining = .{ .arg = arg, .index = next_index, }, }; } } const next_is_separator = if (next_index < arg.len) std.mem.indexOfScalar(u8, parser.assignment_separators, arg[next_index]) != null else false; if (param.takes_value == .none) { if (next_is_separator) return parser.err(arg, .{ .short = short }, Error.DoesntTakeValue); return Arg(Id){ .param = param }; } if (arg.len <= next_index) { const value = parser.iter.next() orelse return parser.err(arg, .{ .short = short }, Error.MissingValue); return Arg(Id){ .param = param, .value = value }; } if (next_is_separator) return Arg(Id){ .param = param, .value = arg[next_index + 1 ..] }; return Arg(Id){ .param = param, .value = arg[next_index..] }; } return parser.err(arg, .{ .short = arg[index] }, Error.InvalidArgument); } fn positionalParam(parser: *@This()) ?*const clap.Param(Id) { if (parser.positional) |p| return p; for (parser.params) |*param| { if (param.names.long) |_| continue; if (param.names.short) |_| continue; parser.positional = param; return param; } return null; } const ArgInfo = struct { arg: []const u8, kind: enum { long, short, positional, }, }; fn parseNextArg(parser: *@This()) !?ArgInfo { const full_arg = parser.iter.next() orelse return null; if (mem.eql(u8, full_arg, "--") or mem.eql(u8, full_arg, "-")) return ArgInfo{ .arg = full_arg, .kind = .positional }; if (mem.startsWith(u8, full_arg, "--")) return ArgInfo{ .arg = full_arg[2..], .kind = .long }; if (mem.startsWith(u8, full_arg, "-")) return ArgInfo{ .arg = full_arg[1..], .kind = .short }; return ArgInfo{ .arg = full_arg, .kind = .positional }; } fn err(parser: @This(), arg: []const u8, names: clap.Names, _err: anytype) @TypeOf(_err) { if (parser.diagnostic) |d| d.* = .{ .arg = arg, .name = names }; return _err; } }; } fn expectArgs( parser: *Clap(u8, args.SliceIterator), results: []const Arg(u8), ) !void { for (results) |res| { const arg = (try parser.next()) orelse return error.TestFailed; try testing.expectEqual(res.param, arg.param); const expected_value = res.value orelse { try testing.expectEqual(@as(@TypeOf(arg.value), null), arg.value); continue; }; const actual_value = arg.value orelse return error.TestFailed; try testing.expectEqualSlices(u8, expected_value, actual_value); } if (try parser.next()) |_| return error.TestFailed; } fn expectError( parser: *Clap(u8, args.SliceIterator), expected: []const u8, ) !void { var diag: clap.Diagnostic = .{}; parser.diagnostic = &diag; while (parser.next() catch |err| { var buf: [1024]u8 = undefined; var fbs = io.fixedBufferStream(&buf); diag.report(fbs.writer(), err) catch return error.TestFailed; try testing.expectEqualStrings(expected, fbs.getWritten()); return; }) |_| {} try testing.expect(false); } test "short params" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .short = 'a' } }, .{ .id = 1, .names = .{ .short = 'b' } }, .{ .id = 2, .names = .{ .short = 'c' }, .takes_value = .one, }, .{ .id = 3, .names = .{ .short = 'd' }, .takes_value = .many, }, }; const a = &params[0]; const b = &params[1]; const c = &params[2]; const d = &params[3]; var iter = args.SliceIterator{ .args = &.{ "-a", "-b", "-ab", "-ba", "-c", "0", "-c=0", "-ac", "0", "-ac=0", "-d=0", } }; var parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectArgs(&parser, &.{ .{ .param = a }, .{ .param = b }, .{ .param = a }, .{ .param = b }, .{ .param = b }, .{ .param = a }, .{ .param = c, .value = "0" }, .{ .param = c, .value = "0" }, .{ .param = a }, .{ .param = c, .value = "0" }, .{ .param = a }, .{ .param = c, .value = "0" }, .{ .param = d, .value = "0" }, }); } test "long params" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .long = "aa" } }, .{ .id = 1, .names = .{ .long = "bb" } }, .{ .id = 2, .names = .{ .long = "cc" }, .takes_value = .one, }, .{ .id = 3, .names = .{ .long = "dd" }, .takes_value = .many, }, }; const aa = &params[0]; const bb = &params[1]; const cc = &params[2]; const dd = &params[3]; var iter = args.SliceIterator{ .args = &.{ "--aa", "--bb", "--cc", "0", "--cc=0", "--dd=0", } }; var parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectArgs(&parser, &.{ .{ .param = aa }, .{ .param = bb }, .{ .param = cc, .value = "0" }, .{ .param = cc, .value = "0" }, .{ .param = dd, .value = "0" }, }); } test "positional params" { const params = [_]clap.Param(u8){.{ .id = 0, .takes_value = .one, }}; var iter = args.SliceIterator{ .args = &.{ "aa", "bb", } }; var parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectArgs(&parser, &.{ .{ .param = &params[0], .value = "aa" }, .{ .param = &params[0], .value = "bb" }, }); } test "all params" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .short = 'a', .long = "aa" }, }, .{ .id = 1, .names = .{ .short = 'b', .long = "bb" }, }, .{ .id = 2, .names = .{ .short = 'c', .long = "cc" }, .takes_value = .one, }, .{ .id = 3, .takes_value = .one }, }; const aa = &params[0]; const bb = &params[1]; const cc = &params[2]; const positional = &params[3]; var iter = args.SliceIterator{ .args = &.{ "-a", "-b", "-ab", "-ba", "-c", "0", "-c=0", "-ac", "0", "-ac=0", "--aa", "--bb", "--cc", "0", "--cc=0", "something", "-", "--", "--cc=0", "-a", } }; var parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectArgs(&parser, &.{ .{ .param = aa }, .{ .param = bb }, .{ .param = aa }, .{ .param = bb }, .{ .param = bb }, .{ .param = aa }, .{ .param = cc, .value = "0" }, .{ .param = cc, .value = "0" }, .{ .param = aa }, .{ .param = cc, .value = "0" }, .{ .param = aa }, .{ .param = cc, .value = "0" }, .{ .param = aa }, .{ .param = bb }, .{ .param = cc, .value = "0" }, .{ .param = cc, .value = "0" }, .{ .param = positional, .value = "something" }, .{ .param = positional, .value = "-" }, .{ .param = positional, .value = "--cc=0" }, .{ .param = positional, .value = "-a" }, }); } test "different assignment separators" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .short = 'a', .long = "aa" }, .takes_value = .one, }, }; const aa = &params[0]; var iter = args.SliceIterator{ .args = &.{ "-a=0", "--aa=0", "-a:0", "--aa:0", } }; var parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter, .assignment_separators = "=:", }; try expectArgs(&parser, &.{ .{ .param = aa, .value = "0" }, .{ .param = aa, .value = "0" }, .{ .param = aa, .value = "0" }, .{ .param = aa, .value = "0" }, }); } test "errors" { const params = [_]clap.Param(u8){ .{ .id = 0, .names = .{ .short = 'a', .long = "aa" }, }, .{ .id = 1, .names = .{ .short = 'c', .long = "cc" }, .takes_value = .one, }, }; var iter = args.SliceIterator{ .args = &.{"q"} }; var parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "Invalid argument 'q'\n"); iter = args.SliceIterator{ .args = &.{"-q"} }; parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "Invalid argument '-q'\n"); iter = args.SliceIterator{ .args = &.{"--q"} }; parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "Invalid argument '--q'\n"); iter = args.SliceIterator{ .args = &.{"--q=1"} }; parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "Invalid argument '--q'\n"); iter = args.SliceIterator{ .args = &.{"-a=1"} }; parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "The argument '-a' does not take a value\n"); iter = args.SliceIterator{ .args = &.{"--aa=1"} }; parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "The argument '--aa' does not take a value\n"); iter = args.SliceIterator{ .args = &.{"-c"} }; parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "The argument '-c' requires a value but none was supplied\n"); iter = args.SliceIterator{ .args = &.{"--cc"} }; parser = Clap(u8, args.SliceIterator){ .params = &params, .iter = &iter }; try expectError(&parser, "The argument '--cc' requires a value but none was supplied\n"); }
0
repos/zig-clap
repos/zig-clap/clap/codepoint_counting_writer.zig
const std = @import("std"); const builtin = @import("builtin"); const native_endian = builtin.cpu.arch.endian(); /// A Writer that counts how many codepoints has been written to it. /// Expects valid UTF-8 input, and does not validate the input. pub fn CodepointCountingWriter(comptime WriterType: type) type { return struct { codepoints_written: u64, child_stream: WriterType, pub const Error = WriterType.Error || error{Utf8InvalidStartByte}; pub const Writer = std.io.Writer(*Self, Error, write); const Self = @This(); pub fn write(self: *Self, bytes: []const u8) Error!usize { const bytes_and_codepoints = try utf8CountCodepointsAllowTruncate(bytes); // Might not be the full input, so the leftover bytes are written on the next call. const bytes_to_write = bytes[0..bytes_and_codepoints.bytes]; const amt = try self.child_stream.write(bytes_to_write); const bytes_written = bytes_to_write[0..amt]; self.codepoints_written += (try utf8CountCodepointsAllowTruncate(bytes_written)).codepoints; return amt; } pub fn writer(self: *Self) Writer { return .{ .context = self }; } }; } // Like `std.unicode.utf8CountCodepoints`, but on truncated input, it returns // the number of codepoints up to that point. // Does not validate UTF-8 beyond checking the start byte. fn utf8CountCodepointsAllowTruncate(s: []const u8) !struct { bytes: usize, codepoints: usize } { var len: usize = 0; const N = @sizeOf(usize); const MASK = 0x80 * (std.math.maxInt(usize) / 0xff); var i: usize = 0; while (i < s.len) { // Fast path for ASCII sequences while (i + N <= s.len) : (i += N) { const v = std.mem.readInt(usize, s[i..][0..N], native_endian); if (v & MASK != 0) break; len += N; } if (i < s.len) { const n = try std.unicode.utf8ByteSequenceLength(s[i]); // Truncated input; return the current counts. if (i + n > s.len) return .{ .bytes = i, .codepoints = len }; i += n; len += 1; } } return .{ .bytes = i, .codepoints = len }; } pub fn codepointCountingWriter(child_stream: anytype) CodepointCountingWriter(@TypeOf(child_stream)) { return .{ .codepoints_written = 0, .child_stream = child_stream }; } const testing = std.testing; test CodepointCountingWriter { var counting_stream = codepointCountingWriter(std.io.null_writer); const stream = counting_stream.writer(); const utf8_text = "blåhaj" ** 100; stream.writeAll(utf8_text) catch unreachable; const expected_count = try std.unicode.utf8CountCodepoints(utf8_text); try testing.expectEqual(expected_count, counting_stream.codepoints_written); } test "handles partial UTF-8 writes" { var buf: [100]u8 = undefined; var fbs = std.io.fixedBufferStream(&buf); var counting_stream = codepointCountingWriter(fbs.writer()); const stream = counting_stream.writer(); const utf8_text = "ååå"; // `å` is represented as `\xC5\xA5`, write 1.5 `å`s. var wc = try stream.write(utf8_text[0..3]); // One should have been written fully. try testing.expectEqual("å".len, wc); try testing.expectEqual(1, counting_stream.codepoints_written); // Write the rest, continuing from the reported number of bytes written. wc = try stream.write(utf8_text[wc..]); try testing.expectEqual(4, wc); try testing.expectEqual(3, counting_stream.codepoints_written); const expected_count = try std.unicode.utf8CountCodepoints(utf8_text); try testing.expectEqual(expected_count, counting_stream.codepoints_written); try testing.expectEqualSlices(u8, utf8_text, fbs.getWritten()); }
0
repos/zig-clap
repos/zig-clap/clap/args.zig
const builtin = @import("builtin"); const std = @import("std"); const debug = std.debug; const heap = std.heap; const mem = std.mem; const process = std.process; const testing = std.testing; /// An example of what methods should be implemented on an arg iterator. pub const ExampleArgIterator = struct { pub fn next(iter: *ExampleArgIterator) ?[]const u8 { _ = iter; return "2"; } }; /// An argument iterator which iterates over a slice of arguments. /// This implementation does not allocate. pub const SliceIterator = struct { args: []const []const u8, index: usize = 0, pub fn next(iter: *SliceIterator) ?[]const u8 { if (iter.args.len <= iter.index) return null; defer iter.index += 1; return iter.args[iter.index]; } }; test "SliceIterator" { const args = [_][]const u8{ "A", "BB", "CCC" }; var iter = SliceIterator{ .args = &args }; for (args) |a| try testing.expectEqualStrings(a, iter.next().?); try testing.expectEqual(@as(?[]const u8, null), iter.next()); }
0
repos
repos/asio/.appveyor.yml
version: "{branch} (#{build})" image: - Visual Studio 2015 - Visual Studio 2017 - Visual Studio 2019 environment: DEBUG: 1 WARNINGS: 1 matrix: - STANDALONE: 1 HEADER_ONLY: 1 MSVC: 1 - STANDALONE: 1 SEPARATE_COMPILATION: 1 MSVC: 1 - STANDALONE: 1 MINGW: 1 - STANDALONE: 1 CXXLATEST: 1 MSVC: 1 - STANDALONE: 1 HEADER_ONLY: 1 WIN9X: 1 MSVC: 1 - STANDALONE: 1 SEPARATE_COMPILATION: 1 WIN9X: 1 MSVC: 1 - USING_BOOST: 1 HEADER_ONLY: 1 MSVC: 1 - USING_BOOST: 1 SEPARATE_COMPILATION: 1 MSVC: 1 - USING_BOOST: 1 MINGW: 1 for: - matrix: only: - image: Visual Studio 2015 MSVC: 1 environment: BOOSTDIR: C:\Libraries\boost_1_67_0 build_script: - call "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64 - call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86_amd64 - cd asio\src - nmake -f Makefile.msc - nmake -f Makefile.msc check - matrix: only: - image: Visual Studio 2017 MSVC: 1 environment: BOOSTDIR: C:\Libraries\boost_1_69_0 _WIN32_WINNT: 0x0603 build_script: - call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x86_amd64 - cd asio\src - nmake -f Makefile.msc - nmake -f Makefile.msc check - matrix: only: - image: Visual Studio 2019 MSVC: 1 environment: BOOSTDIR: C:\Libraries\boost_1_83_0 _WIN32_WINNT: 0x0A00 build_script: - call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x86_amd64 - cd asio\src - nmake -f Makefile.msc - nmake -f Makefile.msc check - matrix: only: - image: Visual Studio 2019 MINGW: 1 environment: BOOSTDIR: C:/Libraries/boost_1_83_0 build_script: - PATH=C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin;C:\msys64\usr\bin;%PATH% - cd asio\src - mingw32-make -f Makefile.mgw - mingw32-make -f Makefile.mgw check matrix: exclude: - image: Visual Studio 2015 HEADER_ONLY: 1 - image: Visual Studio 2015 CXXLATEST: 1 - image: Visual Studio 2015 WIN9X: 1 - image: Visual Studio 2015 USING_BOOST: 1 - image: Visual Studio 2015 MINGW: 1 - image: Visual Studio 2017 SEPARATE_COMPILATION: 1 - image: Visual Studio 2017 CXXLATEST: 1 - image: Visual Studio 2017 WIN9X: 1 - image: Visual Studio 2017 USING_BOOST: 1 - image: Visual Studio 2017 MINGW: 1 - image: Visual Studio 2019 HEADER_ONLY: 1 - image: Visual Studio 2019 WIN9X: 1
0
repos
repos/asio/README.md
## Asio Standalone for Zig Package Manager (MVP) * Original source: https://github.com/chriskohlhoff/asio ### How to use * Download [Zig v0.13 or higher](https://ziglang.org/download) * Make on your project `build.zig` & `build.zig.zon` file e.g: * **build.zig** ```zig const asio_dep = b.dependency("asio", .{ // <== as declared in build.zig.zon .target = target, // the same as passing `-Dtarget=<...>` to the library's build.zig script .optimize = optimize, // ditto for `-Doptimize=<...>` }); const libasio = asio_dep.artifact("asio"); // <== has the location of the dependency files (asio) /// your executable config exe.linkLibrary(libasio); // <== link libasio exe.installLibraryHeaders(libasio); // <== get copy asio headers to zig-out/include ``` * **build.zig.zon** ```bash # '--save=asio': (over)write latest git commit (no need manually update) $ zig fetch --save=asio git+https://github.com/kassane/asio ``` or add manually to your `build.zig.zon` file: ```zig .{ .name = "example", .version = "0.1.0", .paths = .{""}, .dependencies = .{ .asio = .{ .url = "https://github.com/kassane/asio/archive/[tag/commit-hash].tar.gz", // or .url = "git+https://https://github.com/kassane/asio#commit-hash", .hash = "[multihash - sha256-2]", }, }, } ``` ```bash # zig project helper Project-Specific Options: -Dtarget=[string] The CPU architecture, OS, and ABI to build for -Dcpu=[string] Target CPU features to add or subtract -Ddynamic-linker=[string] Path to interpreter on the target system -Doptimize=[enum] Prioritize performance, safety, or binary size Supported Values: Debug ReleaseSafe ReleaseFast ReleaseSmall -DShared=[bool] Build the Shared Library (default: false) -DSSL=[bool] Build Asio with OpenSSL support (default: false) -DTests=[bool] Build tests (default: false) ``` ### More info about zig-pkg - https://github.com/ziglang/zig/pull/14265 - https://github.com/ziglang/zig/issues/14307
0
repos
repos/asio/.cirrus.yml
freebsd_instance: image_family: freebsd-14-0 cpu: 1 env: CXXFLAGS: -std=c++14 -Wall -Wextra -O2 task: install_script: - pkg install -y autoconf automake pkgconf build_script: - cd asio - ./autogen.sh - ./configure --with-boost=no - make - make check
0
repos
repos/asio/build.zig.zon
.{ .name = "asio", .version = "1.30.2", .minimum_zig_version = "0.13.0", .paths = .{ "asio/include", "asio/src", "build.zig", "LICENSE", "README.md", }, }
0
repos
repos/asio/build.zig
//! Requires zig version: 0.13 or higher //! build: zig build -Doptimize=ReleaseFast -DShared (or -DShared=true/false) const std = @import("std"); const Path = std.Build.LazyPath; pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); // Options const shared = b.option(bool, "Shared", "Build the Shared Library (default: false)") orelse false; const ssl = b.option(bool, "SSL", "Build Asio with OpenSSL support (default: false)") orelse false; const tests = b.option(bool, "Tests", "Build tests (default: false)") orelse false; const libasio = if (!shared) b.addStaticLibrary(.{ .name = "asio", .target = target, .optimize = optimize, }) else b.addSharedLibrary(.{ .name = "asio", .target = target, .version = .{ .major = 1, .minor = 30, .patch = 2, }, .optimize = optimize, }); libasio.defineCMacro("ASIO_STANDALONE", null); libasio.defineCMacro("ASIO_SEPARATE_COMPILATION", null); if (optimize == .Debug or optimize == .ReleaseSafe) libasio.bundle_compiler_rt = true else libasio.root_module.strip = true; libasio.addIncludePath(b.path("asio/include")); libasio.addCSourceFiles(.{ .files = switch (ssl) { true => &.{ "asio/src/asio_ssl.cpp", }, else => &.{ "asio/src/asio.cpp", }, }, .flags = cxxFlags, }); if (libasio.rootModuleTarget().os.tag == .windows) { if (libasio.linkage == .dynamic) { libasio.linkSystemLibrary("ws2_32"); if (ssl) { libasio.linkSystemLibrary("crypto"); libasio.linkSystemLibrary("ssl"); } libasio.want_lto = false; } } // TODO: MSVC support libC++ (need: ucrt/msvcrt/vcruntime) // https://github.com/ziglang/zig/issues/4785 - drop replacement for MSVC if (libasio.rootModuleTarget().abi == .msvc) { libasio.linkLibC(); } else { libasio.linkLibCpp(); // LLVM libc++ (builtin) } libasio.installHeadersDirectory(b.path("asio/include"), "", .{ .include_extensions = &.{ ".hpp", ".h", ".ipp" }, .exclude_extensions = &.{ "am", "gitignore", }, }); b.installArtifact(libasio); if (tests) { buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/coroutine.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/awaitable.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/async_result.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/associator.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/co_spawn.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/compose.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/connect.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/defer.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/executor.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/error.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/strand.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/thread_pool.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/this_coro.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/socket_base.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/serial_port.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/signal_set.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/post.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/prepend.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/cancellation_type.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/as_tuple.cpp", .optimize = optimize, .target = target, }); if (target.result.os.tag == .windows) { buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/windows/object_handle.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/windows/overlapped_handle.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/windows/stream_handle.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/windows/overlapped_ptr.cpp", .optimize = optimize, .target = target, }); buildTest(b, .{ .lib = libasio, .path = "asio/src/tests/unit/windows/random_access_handle.cpp", .optimize = optimize, .target = target, }); } } } fn buildTest(b: *std.Build, info: BuildInfo) void { const test_exe = b.addExecutable(.{ .name = info.filename(), .optimize = info.optimize, .target = info.target, }); if (test_exe.root_module.optimize.? == .Debug) test_exe.defineCMacro("ASIO_ENABLE_HANDLER_TRACKING", null); test_exe.linkLibrary(info.lib); for (info.lib.root_module.include_dirs.items) |include| { test_exe.root_module.include_dirs.append(b.allocator, include) catch {}; } test_exe.addIncludePath(b.path("asio/src/tests/unit")); // unit_test.hpp test_exe.addCSourceFile(.{ .file = b.path(info.path), .flags = cxxFlags }); if (test_exe.rootModuleTarget().os.tag == .windows) { test_exe.linkSystemLibrary("ws2_32"); } if (test_exe.rootModuleTarget().abi == .msvc) test_exe.linkLibC() else test_exe.linkLibCpp(); b.installArtifact(test_exe); const run_cmd = b.addRunArtifact(test_exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step( b.fmt("{s}", .{info.filename()}), b.fmt("Run the {s} test", .{info.filename()}), ); run_step.dependOn(&run_cmd.step); } const cxxFlags: []const []const u8 = &.{ "-Wall", "-Wextra", "-Wpedantic", "-Werror", "-Wno-deprecated-declarations", }; const BuildInfo = struct { optimize: std.builtin.OptimizeMode, target: std.Build.ResolvedTarget, lib: *std.Build.Step.Compile, path: []const u8, fn filename(self: BuildInfo) []const u8 { var split = std.mem.splitSequence(u8, std.fs.path.basename(self.path), "."); return split.first(); } };
0
repos/asio
repos/asio/asio/autogen.sh
#!/bin/sh # Helps bootstrapping the application when checked out from CVS. # Requires GNU autoconf, GNU automake and GNU which. # # Copyright (C) 2004, by # # Carlo Wood, Run on IRC <[email protected]> # RSA-1024 0x624ACAD5 1997-01-26 Sign & Encrypt # Fingerprint16 = 32 EC A7 B6 AC DB 65 A6 F6 F6 55 DD 1C DC FF 61 # # Do sanity checks. # Directory check. if [ ! -f autogen.sh ]; then echo "Run ./autogen.sh from the directory it exists in." exit 1 fi AUTOMAKE=${AUTOMAKE:-automake} ACLOCAL=${ACLOCAL:-aclocal} AUTOCONF=${AUTOCONF:-autoconf} ($AUTOCONF --version) >/dev/null 2>/dev/null || (echo "You need GNU autoconf to install from CVS (ftp://ftp.gnu.org/gnu/autoconf/)"; exit 1) || exit 1 ($AUTOMAKE --version) >/dev/null 2>/dev/null || (echo "You need GNU automake 1.7 or higher to install from CVS (ftp://ftp.gnu.org/gnu/automake/)"; exit 1) || exit 1 # Determine the version of automake. automake_version=`$AUTOMAKE --version | head -n 1 | sed -e 's/[^12]*\([12]\.[0-9][^ ]*\).*/\1/'` automake_major=`echo $automake_version | cut -f1 -d.` automake_minor=`echo $automake_version | cut -f2 -d.` automake_version_number=`expr "$automake_major" \* 1000 \+ "$automake_minor"` # Require automake 1.7. if expr "1007" \> "$automake_version_number" >/dev/null; then $AUTOMAKE --version | head -n 1 echo "" echo "Fatal error: automake 1.7 or higher is required. Please set \$AUTOMAKE" echo "to point to a newer automake, or upgrade." echo "" exit 1 fi run() { echo "Running $1 ..." $1 } # This is needed when someone just upgraded automake and this cache is still generated by an old version. rm -rf autom4te.cache config.cache run "$ACLOCAL" run "$AUTOCONF" run "$AUTOMAKE --add-missing --foreign"
0
repos/asio
repos/asio/asio/tsify.pl
#!/usr/bin/perl -w use strict; use File::Path; # use Switch; our $output_dir = "tsified"; sub print_line { my ($output, $line, $from, $lineno) = @_; # Warn if the resulting line is >80 characters wide. if (length($line) > 80) { if ($from =~ /\.[chi]pp$/) { print("Warning: $from:$lineno: output >80 characters wide.\n"); } } # Write the output. print($output $line . "\n"); } sub source_contains_asio_thread_usage { my ($from) = @_; # Open the input file. open(my $input, "<$from") or die("Can't open $from for reading"); # Check file for use of asio::thread. while (my $line = <$input>) { chomp($line); if ($line =~ /asio::thread/) { close($input); return 1; } elsif ($line =~ /^ *thread /) { close($input); return 1; } } close($input); return 0; } sub source_contains_asio_include { my ($from) = @_; # Open the input file. open(my $input, "<$from") or die("Can't open $from for reading"); # Check file for inclusion of asio.hpp. while (my $line = <$input>) { chomp($line); if ($line =~ /# *include [<"]asio\.hpp[>"]/) { close($input); return 1; } } close($input); return 0; } sub copy_source_file { my ($from, $to) = @_; # Ensure the output directory exists. my $dir = $to; $dir =~ s/[^\/]*$//; mkpath($dir); # First determine whether the file makes any use of asio::thread. my $uses_asio_thread = source_contains_asio_thread_usage($from); my $includes_asio = source_contains_asio_include($from); my $is_asio_hpp = 0; $is_asio_hpp = 1 if ($from =~ /asio\.hpp/); my $needs_doc_link = 0; $needs_doc_link = 1 if ($is_asio_hpp); my $is_config_hpp = 0; $is_config_hpp = 1 if ($from =~ /asio\/detail\/config\.hpp/); my $is_error_hpp = 0; $is_error_hpp = 1 if ($from =~ /asio\/error\.hpp/); my $is_impl_src_hpp = 0; $is_impl_src_hpp = 1 if ($from =~ /asio\/impl\/src\.hpp/); my $is_test = 0; $is_test = 1 if ($from =~ /tests\/unit/); # Open the files. open(my $input, "<$from") or die("Can't open $from for reading"); open(my $output, ">$to") or die("Can't open $to for writing"); # State for stripping out deprecated, extension, and old services code. my $deprecated_state = 0; my $extension_state = 0; my $old_services_state = 0; # State for simplifying namespaces in examples. my $code_snippet_state = 0; # Copy the content. my $lineno = 1; while (my $line = <$input>) { chomp($line); # Strip out deprecated code. if ($deprecated_state == 0) { if ($line =~ /#\s*if\s*defined\(ASIO_NO_DEPRECATED\)/) { $deprecated_state = 1; next; } elsif ($line =~ /#\s*if\s*!defined\(ASIO_NO_DEPRECATED\)/) { $deprecated_state = -1; next; } } elsif ($deprecated_state == 1) { if ($line =~ /#\s*else\s*\/\/\s*!*defined\(ASIO_NO_DEPRECATED\)/) { $deprecated_state = -1; next; } elsif ($line =~ /#\s*endif\s*\/\/\s*!*defined\(ASIO_NO_DEPRECATED\)/) { $deprecated_state = 0; next; } else { $line =~ s/^# /#/; } } elsif ($deprecated_state == -1) { if ($line =~ /#\s*else\s*\/\/\s*!*defined\(ASIO_NO_DEPRECATED\)/) { $deprecated_state = 1; } elsif ($line =~ /#\s*endif\s*\/\/\s*!*defined\(ASIO_NO_DEPRECATED\)/) { $deprecated_state = -2; } next; } elsif ($deprecated_state == -2) { $deprecated_state = 0; next if ($line eq ""); } # Strip out code for extensions. if ($extension_state == 0) { if ($line =~ /#\s*if\s*!defined\(ASIO_NO_EXTENSIONS\)\s*$/) { $extension_state = -1; next; } } elsif ($extension_state == -1) { $extension_state = -2 if ($line =~ /#\s*endif\s*\/\/\s*!defined\(ASIO_NO_EXTENSIONS\)\s*$/); next; } elsif ($extension_state == -2) { $extension_state = 0; next if ($line eq ""); } # Strip out code for old services. if ($old_services_state == 0) { if ($line =~ /#\s*if\s*defined\(ASIO_ENABLE_OLD_SERVICES\)/) { $old_services_state = -1; next; } elsif ($line =~ /#\s*if\s*!defined\(ASIO_ENABLE_OLD_SERVICES\)/) { $old_services_state = 1; next; } } elsif ($old_services_state == 1) { if ($line =~ /#\s*else\s*\/\/\s*!*defined\(ASIO_ENABLE_OLD_SERVICES\)/) { $old_services_state = -1; next; } elsif ($line =~ /#\s*endif\s*\/\/\s*!*defined\(ASIO_ENABLE_OLD_SERVICES\)/) { $old_services_state = 0; next; } else { $line =~ s/^# /#/; } } elsif ($old_services_state == -1) { if ($line =~ /#\s*else\s*\/\/\s*!*defined\(ASIO_ENABLE_OLD_SERVICES\)/) { $old_services_state = 1; } elsif ($line =~ /#\s*endif\s*\/\/\s*!*defined\(ASIO_ENABLE_OLD_SERVICES\)/) { $old_services_state = -2; } next; } elsif ($old_services_state == -2) { $old_services_state = 0; next if ($line eq ""); } # Keep track of whether we are in an example. if ($code_snippet_state == 0) { if ($line =~ /\@code/) { $code_snippet_state = 1; } } # Unconditional replacements. $line =~ s/[\\@]ref boost_bind/std::bind()/g; if ($from =~ /.*\.txt$/) { $line =~ s/[\\@]ref async_read/std::experimental::net::v1::async_read()/g; $line =~ s/[\\@]ref async_write/std::experimental::net::v1::async_write()/g; } if ($line =~ /asio_detail_posix_thread_function/) { $line =~ s/asio_detail_posix_thread_function/networking_ts_detail_posix_thread_function/g; } if ($line =~ /asio_signal_handler/) { $line =~ s/asio_signal_handler/networking_ts_signal_handler/g; } if ($line =~ /ASIO_/ && !($line =~ /NET_TS_/)) { $line =~ s/ASIO_/NET_TS_/g; } if ($line =~ /asio_handler_/) { $line =~ s/asio_handler_/networking_ts_handler_/g; } if ($line =~ /asio_true_handler_/) { $line =~ s/asio_true_handler_/networking_ts_true_handler_/g; } # Lines skipped in asio/impl/src.hpp. if ($is_impl_src_hpp) { next if ( $line =~ /serial_port/ or $line =~ /\/local\// or $line =~ /\/generic\// or $line =~ /signal_set/ ); } # Conditional replacements. if ($line =~ /^(.* *)namespace asio \{/) { print_line($output, $1 . "namespace std {", $from, $lineno); print_line($output, $1 . "namespace experimental {", $from, $lineno); print_line($output, $1 . "namespace net {", $from, $lineno); print_line($output, $1 . "inline namespace v1 {", $from, $lineno); } elsif ($line =~ /^(.* *)} \/\/ namespace asio$/) { print_line($output, $1 . "} // inline namespace v1", $from, $lineno); print_line($output, $1 . "} // namespace net", $from, $lineno); print_line($output, $1 . "} // namespace experimental", $from, $lineno); print_line($output, $1 . "} // namespace std", $from, $lineno); } elsif ($line =~ /^(# *include )[<"](asio\.hpp)[>"]$/) { print_line($output, $1 . "<net>", $from, $lineno); if ($uses_asio_thread) { print_line($output, $1 . "<thread>", $from, $lineno) if (!$is_test); $uses_asio_thread = 0; } } elsif ($line =~ /^(# *include )[<"]boost\/.*[>"].*$/) { if (!$includes_asio && $uses_asio_thread) { print_line($output, $1 . "<thread>", $from, $lineno) if (!$is_test); $uses_asio_thread = 0; } print_line($output, $line, $from, $lineno); } elsif ($line =~ /^(# *include )[<"]asio\/thread\.hpp[>"]/) { if ($is_test) { print_line($output, $1 . "<experimental/__net_ts/detail/thread.hpp>", $from, $lineno); } else { # Line is removed. } } elsif ($line =~ /(# *include )[<"]asio\/error_code\.hpp[>"]/) { if ($is_asio_hpp) { # Line is removed. } else { print_line($output, $1 . "<cerrno>", $from, $lineno) if ($is_error_hpp); print_line($output, $1 . "<system_error>", $from, $lineno); } } elsif ($line =~ /# *include [<"]asio\/impl\/error_code\.[hi]pp[>"]/) { # Line is removed. } elsif ($line =~ /(# *include )[<"]asio\/system_error\.hpp[>"]/) { if ($is_asio_hpp) { # Line is removed. } else { print_line($output, $1 . "<system_error>", $from, $lineno); } } elsif ($line =~ /(^.*# *include )[<"]asio\/([^>"]*)[>"](.*)$/) { print_line($output, $1 . "<experimental/__net_ts/" . $2 . ">" . $3, $from, $lineno); } elsif ($line =~ /#.*defined\(.*ASIO_HAS_STD_SYSTEM_ERROR\)$/) { # Line is removed. } elsif ($line =~ /asio::thread\b/) { if ($is_test) { $line =~ s/asio::thread/std::experimental::net::v1::detail::thread/g; } else { $line =~ s/asio::thread/std::thread/g; } print_line($output, $line, $from, $lineno); } elsif ($line =~ /^( *)thread( .*)$/) { if ($is_test) { print_line($output, $1 . "std::experimental::net::v1::detail::thread" . $2, $from, $lineno); } else { print_line($output, $1 . "std::thread" . $2, $from, $lineno); } } elsif ($line =~ /asio::/ && !($line =~ /boost::asio::/)) { $line =~ s/asio::error_code/std::error_code/g; $line =~ s/asio::error_category/std::error_category/g; $line =~ s/asio::system_category/std::system_category/g; $line =~ s/asio::system_error/std::system_error/g; $line =~ s/asio::/std::experimental::net::v1::/g if $code_snippet_state == 0; $line =~ s/asio::/std::experimental::net::/g if $code_snippet_state == 1; print_line($output, $line, $from, $lineno); } elsif ($line =~ /using namespace asio/) { $line =~ s/using namespace asio/using namespace std::experimental::net::v1/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /[\\@]ref boost_bind/) { $line =~ s/[\\@]ref boost_bind/std::bind()/g; print_line($output, $line, $from, $lineno); } elsif ($line =~ /define.*DETAIL_CONFIG_HPP/) { print_line($output, $line, $from, $lineno); print_line($output, "", $from, $lineno); print_line($output, "#define NET_TS_STANDALONE 1", $from, $lineno); } else { print_line($output, $line, $from, $lineno); } # Keep track of whether we are in an example. if ($code_snippet_state == 1) { if ($line =~ /\@endcode/) { $code_snippet_state = 0; } } ++$lineno; } # Ok, we're done. close($input); close($output); } sub find_include_files { my @root_includes = ( "asio/ts/buffer.hpp", "asio/ts/executor.hpp", "asio/ts/internet.hpp", "asio/ts/io_context.hpp", "asio/ts/net.hpp", "asio/ts/netfwd.hpp", "asio/ts/socket.hpp", "asio/ts/timer.hpp"); my @excluded_includes = ( "asio/basic_deadline_timer.hpp", "asio/basic_streambuf.hpp", "asio/basic_streambuf_fwd.hpp", "asio/datagram_socket_service.hpp", "asio/deadline_timer.hpp", "asio/deadline_timer_service.hpp", "asio/io_context_strand.hpp", "asio/detail/strand_service.hpp", "asio/detail/impl/strand_service.hpp", "asio/detail/impl/strand_service.ipp", "asio/socket_acceptor_service.hpp", "asio/seq_packet_socket_service.hpp", "asio/stream_socket_service.hpp", "asio/time_traits.hpp", "asio/waitable_timer_service.hpp"); my @include_files = (); my %known_includes = (); foreach my $include (@root_includes) { $known_includes{$include} = 1; push(@include_files, "include/" . $include); } foreach my $include (@excluded_includes) { $known_includes{$include} = 1; } my @unprocessed_includes = sort keys %known_includes; while (scalar(@unprocessed_includes) > 0) { my $include = pop(@unprocessed_includes); open(my $input, "<include/$include") or die("Can't open include/$include for reading"); while (my $line = <$input>) { chomp($line); if ($line =~ /^\s*#\s*include\s*"(asio\/[^"]*)"/) { if (not defined($known_includes{$1})) { $known_includes{$1} = 1; push(@include_files, "include/" . $1); push(@unprocessed_includes, $1); } } } close($input); } return @include_files; } sub copy_include_files { my @files = find_include_files(); push(@files, "include/asio/impl/src.hpp"); foreach my $file (@files) { if ($file ne "include/asio/thread.hpp" and $file ne "include/asio/error_code.hpp" and $file ne "include/asio/system_error.hpp" and $file ne "include/asio/impl/error_code.hpp" and $file ne "include/asio/impl/error_code.ipp") { my $from = $file; my $to = $file; $to =~ s/^include\/asio\//$output_dir\/include\/experimental\/__net_ts\//; copy_source_file($from, $to); } } } sub create_top_level_includes { my @includes = ( "buffer", "executor", "internet", "io_context", "net", "netfwd", "socket", "timer"); our $output_dir; mkpath("$output_dir/include/experimental"); foreach my $include (@includes) { open(my $output, ">$output_dir/include/experimental/$include") or die("Can't open $output_dir/include/experimental/$include for writing"); my $guard = "NET_TS_" . uc($include) . "_INCLUDED"; print($output "//\n"); print($output "// experimental/$include\n"); print($output "// " . '~' x length("experimental/" . $include) . "\n"); print($output "//\n"); print($output "// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)\n"); print($output "//\n"); print($output "// Distributed under the Boost Software License, Version 1.0. (See accompanying\n"); print($output "// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n"); print($output "//\n"); print($output "\n"); print($output "#ifndef $guard\n"); print($output "#define $guard\n"); print($output "\n"); print($output "#include <experimental/__net_ts/ts/$include.hpp>\n"); print($output "\n"); print($output "#endif // $guard\n"); close($output); } } copy_include_files(); create_top_level_includes();
0
repos/asio
repos/asio/asio/asio.pc.in
prefix=@prefix@ exec_prefix=@exec_prefix@ includedir=@includedir@ Name: @PACKAGE_NAME@ Description: A cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach. Version: @PACKAGE_VERSION@ Cflags: -I${includedir} Lflags: Requires: Requires.private:
0
repos/asio
repos/asio/asio/LICENSE_1_0.txt
Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
repos/asio
repos/asio/asio/release.pl
#!/usr/bin/perl -w use strict; use Cwd qw(abs_path getcwd); use Date::Format; use File::Path; use File::Copy; use File::Basename; our $version_major; our $version_minor; our $version_sub_minor; our $asio_name; our $boost_asio_name; sub print_usage_and_exit { print("usage: ./release.pl <version>\n"); print(" or: ./release.pl --package-asio\n"); print("\n"); print("examples:\n"); print(" create new version and build packages for asio and boost.asio:\n"); print(" ./release.pl 1.2.0\n"); print(" create packages for asio only:\n"); print(" ./release.pl --package-asio\n"); exit(1); } sub determine_version($) { my $version_string = shift; if ($version_string =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)$/) { our $version_major = $1; our $version_minor = $2; our $version_sub_minor = $3; our $asio_name = "asio"; $asio_name .= "-$version_major"; $asio_name .= ".$version_minor"; $asio_name .= ".$version_sub_minor"; our $boost_asio_name = "boost_asio"; $boost_asio_name .= "_$version_major"; $boost_asio_name .= "_$version_minor"; $boost_asio_name .= "_$version_sub_minor"; } else { print_usage_and_exit(); } } sub determine_version_from_configure() { my $from = "configure.ac"; open(my $input, "<$from") or die("Can't open $from for reading"); while (my $line = <$input>) { chomp($line); if ($line =~ /^AC_INIT\(\[asio\],\[(.*)\]\)$/) { our $asio_name = "asio-$1"; our $boost_asio_name = "boost_asio_$1"; last; } } } sub update_configure_ac { # Open the files. my $from = "configure.ac"; my $to = $from . ".tmp"; open(my $input, "<$from") or die("Can't open $from for reading"); open(my $output, ">$to") or die("Can't open $to for writing"); # Copy the content. while (my $line = <$input>) { chomp($line); if ($line =~ /^AC_INIT\(\[asio\].*\)$/) { $line = "AC_INIT([asio],["; $line .= "$version_major.$version_minor.$version_sub_minor"; $line .= "])"; } print($output "$line\n"); } # Close the files and move the temporary output into position. close($input); close($output); move($to, $from); unlink($to); } sub update_readme { # Open the files. my $from = "README"; my $to = $from . ".tmp"; open(my $input, "<$from") or die("Can't open $from for reading"); open(my $output, ">$to") or die("Can't open $to for writing"); # Copy the content. while (my $line = <$input>) { chomp($line); if ($line =~ /^asio version/) { $line = "asio version "; $line .= "$version_major.$version_minor.$version_sub_minor"; } elsif ($line =~ /^Released/) { my @time = localtime; $line = "Released " . strftime("%A, %d %B %Y", @time) . "."; } print($output "$line\n"); } # Close the files and move the temporary output into position. close($input); close($output); move($to, $from); unlink($to); } sub update_asio_version_hpp { # Open the files. my $from = "include/asio/version.hpp"; my $to = $from . ".tmp"; open(my $input, "<$from") or die("Can't open $from for reading"); open(my $output, ">$to") or die("Can't open $to for writing"); # Copy the content. while (my $line = <$input>) { chomp($line); if ($line =~ /^#define ASIO_VERSION /) { my $version = $version_major * 100000; $version += $version_minor * 100; $version += $version_sub_minor + 0; $line = "#define ASIO_VERSION " . $version; $line .= " // $version_major.$version_minor.$version_sub_minor"; } print($output "$line\n"); } # Close the files and move the temporary output into position. close($input); close($output); move($to, $from); unlink($to); } sub update_boost_asio_version_hpp { # Open the files. my $from = "../boost/boost/asio/version.hpp"; my $to = $from . ".tmp"; open(my $input, "<$from") or die("Can't open $from for reading"); open(my $output, ">$to") or die("Can't open $to for writing"); # Copy the content. while (my $line = <$input>) { chomp($line); if ($line =~ /^#define BOOST_ASIO_VERSION /) { my $version = $version_major * 100000; $version += $version_minor * 100; $version += $version_sub_minor + 0; $line = "#define BOOST_ASIO_VERSION " . $version; $line .= " // $version_major.$version_minor.$version_sub_minor"; } print($output "$line\n"); } # Close the files and move the temporary output into position. close($input); close($output); move($to, $from); unlink($to); } sub build_asio_doc { $ENV{BOOST_ROOT} = abs_path("../boost"); system("rm -rf doc"); my $bjam = abs_path(glob("../boost/bjam")); chdir("src/doc"); system("$bjam clean"); system("rm -rf html"); system("$bjam"); chdir("../.."); mkdir("doc"); system("cp -vR src/doc/html/* doc"); } sub make_asio_packages { our $asio_name; system("./autogen.sh"); system("./configure"); system("make dist"); system("tar tfz $asio_name.tar.gz | sed -e 's/^[^\\/]*//' | sort -df > asio.manifest"); } sub build_boost_asio_doc { my $cwd = getcwd(); my $bjam = abs_path(glob("../boost/bjam")); chdir("../boost/doc"); system("rm -rf html/boost_asio"); chdir("../libs/asio/doc"); system("$bjam clean"); system("$bjam asio"); chdir($cwd); } our $boost_asio_readme = <<"EOF"; Copy the `boost', `doc' and `libs' directories into an existing boost 1.33.0, 1.33.1, 1.34, 1.34.1, 1.35 or 1.36 distribution. Before using Boost.Asio, the Boost.System library needs to be built. This can be done by running bjam in the libs/system/build directory. Consult the Boost Getting Started page (http://www.boost.org/more/getting_started.html) for more information on how to build the Boost libraries. EOF our $boost_system_jamfile = <<"EOF"; # Boost System Library Build Jamfile # (C) Copyright Beman Dawes 2002, 2006 # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or www.boost.org/LICENSE_1_0.txt) # See library home page at http://www.boost.org/libs/system subproject libs/system/build ; SOURCES = error_code ; lib boost_system : ../src/$(SOURCES).cpp : # build requirements <define>BOOST_SYSTEM_STATIC_LINK <sysinclude>$(BOOST_AUX_ROOT) <sysinclude>$(BOOST_ROOT) # common-variant-tag ensures that the library will # be named according to the rules used by the install # and auto-link features: common-variant-tag : debug release # build variants ; dll boost_system : ../src/$(SOURCES).cpp : # build requirements <define>BOOST_SYSTEM_DYN_LINK=1 # tell source we're building dll's <runtime-link>dynamic # build only for dynamic runtimes <sysinclude>$(BOOST_AUX_ROOT) <sysinclude>$(BOOST_ROOT) # common-variant-tag ensures that the library will # be named according to the rules used by the install # and auto-link features: common-variant-tag : debug release # build variants ; install system lib : <lib>boost_system <dll>boost_system ; stage stage/lib : <lib>boost_system <dll>boost_system : # copy to a path rooted at BOOST_ROOT: <locate>$(BOOST_ROOT) # make sure the names of the libraries are correctly named: common-variant-tag # add this target to the "stage" and "all" psuedo-targets: <target>stage <target>all : debug release ; # end EOF sub create_boost_asio_content { # Create directory structure. system("rm -rf $boost_asio_name"); mkdir("$boost_asio_name"); mkdir("$boost_asio_name/doc"); mkdir("$boost_asio_name/doc/html"); mkdir("$boost_asio_name/boost"); mkdir("$boost_asio_name/boost/config"); mkdir("$boost_asio_name/libs"); # Copy files. system("cp -vLR ../boost/doc/html/boost_asio.html $boost_asio_name/doc/html"); system("cp -vLR ../boost/doc/html/boost_asio $boost_asio_name/doc/html"); system("cp -vLR ../boost/boost/asio.hpp $boost_asio_name/boost"); system("cp -vLR ../boost/boost/asio $boost_asio_name/boost"); system("cp -vLR ../boost/boost/cerrno.hpp $boost_asio_name/boost"); system("cp -vLR ../boost/boost/config/warning_disable.hpp $boost_asio_name/boost/config"); system("cp -vLR ../boost/boost/system $boost_asio_name/boost"); system("cp -vLR ../boost/libs/asio $boost_asio_name/libs"); system("cp -vLR ../boost/libs/system $boost_asio_name/libs"); # Remove modular boost include directories. system("rm -rf $boost_asio_name/libs/asio/include"); system("rm -rf $boost_asio_name/libs/system/include"); # Add dummy definitions of BOOST_SYMBOL* to boost/system/config.hpp. my $from = "$boost_asio_name/boost/system/config.hpp"; my $to = "$boost_asio_name/boost/system/config.hpp.new"; open(my $input, "<$from") or die("Can't open $from for reading"); open(my $output, ">$to") or die("Can't open $to for writing"); while (my $line = <$input>) { print($output $line); if ($line =~ /<boost\/config\.hpp>/) { print($output "\n// These #defines added by the separate Boost.Asio package.\n"); print($output "#if !defined(BOOST_SYMBOL_IMPORT)\n"); print($output "# if defined(BOOST_HAS_DECLSPEC)\n"); print($output "# define BOOST_SYMBOL_IMPORT __declspec(dllimport)\n"); print($output "# else // defined(BOOST_HAS_DECLSPEC)\n"); print($output "# define BOOST_SYMBOL_IMPORT\n"); print($output "# endif // defined(BOOST_HAS_DECLSPEC)\n"); print($output "#endif // !defined(BOOST_SYMBOL_IMPORT)\n"); print($output "#if !defined(BOOST_SYMBOL_EXPORT)\n"); print($output "# if defined(BOOST_HAS_DECLSPEC)\n"); print($output "# define BOOST_SYMBOL_EXPORT __declspec(dllexport)\n"); print($output "# else // defined(BOOST_HAS_DECLSPEC)\n"); print($output "# define BOOST_SYMBOL_EXPORT\n"); print($output "# endif // defined(BOOST_HAS_DECLSPEC)\n"); print($output "#endif // !defined(BOOST_SYMBOL_EXPORT)\n"); print($output "#if !defined(BOOST_SYMBOL_VISIBLE)\n"); print($output "# define BOOST_SYMBOL_VISIBLE\n"); print($output "#endif // !defined(BOOST_SYMBOL_VISIBLE)\n\n"); } } close($input); close($output); system("mv $to $from"); # Create readme. $to = "$boost_asio_name/README.txt"; open($output, ">$to") or die("Can't open $to for writing"); print($output $boost_asio_readme); close($output); # Create Boost.System Jamfile. $to = "$boost_asio_name/libs/system/build/Jamfile"; open($output, ">$to") or die("Can't open $to for writing"); print($output $boost_system_jamfile); close($output); # Remove SVN and git files. system("find $boost_asio_name -name .svn -exec rm -rf {} \\;"); system("find $boost_asio_name -name .git -exec rm -rf {} \\;"); system("find $boost_asio_name -name .gitignore -exec rm -rf {} \\;"); system("find $boost_asio_name -name .gitattributes -exec rm -rf {} \\;"); } sub make_boost_asio_packages { our $boost_asio_name; system("tar --format=pax -chf - $boost_asio_name | gzip -c >$boost_asio_name.tar.gz"); system("tar --format=pax -chf - $boost_asio_name | bzip2 -9 -c >$boost_asio_name.tar.bz2"); system("rm -f $boost_asio_name.zip"); system("zip -rq $boost_asio_name.zip $boost_asio_name"); system("rm -rf $boost_asio_name"); system("tar tfz $boost_asio_name.tar.gz | sed -e 's/^[^\\/]*//' | sort -df > boost_asio.manifest"); } (scalar(@ARGV) == 1) or print_usage_and_exit(); my $new_version = 1; my $package_asio = 1; my $package_boost = 1; if ($ARGV[0] eq "--package-asio") { $new_version = 0; $package_boost = 0; } if ($new_version) { determine_version($ARGV[0]); update_configure_ac(); update_readme(); update_asio_version_hpp(); update_boost_asio_version_hpp(); } else { determine_version_from_configure(); } if ($package_asio) { #build_asio_doc(); make_asio_packages(); } if ($package_boost) { build_boost_asio_doc(); create_boost_asio_content(); make_boost_asio_packages(); }