19 |
20 | ## :open_book: Project Overview :
21 |
22 | D3D9 Overlay ImGui use D3D9 to create a DirectX window with ImGui, and this allow you to draw on top of games / application.
23 |
24 | You can easily use it as a DLL for internal cheat and EXE for external. Everything is setup you just need to choose between DLL or EXE. D3D9 Overlay ImGui create his own window, if you use it as a DLL you main process don't need to use DirectX.
25 |
26 | This project works in x86 and x64, DLL and EXE.
27 |
28 | #### Features :
29 |
30 | - Hide your cheats from OBS or any window capture app.
31 | - Create cheat with ImGui on games that don't use DirectX.
32 | - Allow creation of internal / external cheats.
33 | - Easy to build, everything is setup.
34 |
35 | #### Used librairies :
36 |
37 | - [DirectX SDK](https://www.microsoft.com/en-us/download/details.aspx?id=6812)
38 | - [ImGui](https://github.com/ocornut/imgui)
39 |
40 | ## :rocket: Getting Started
41 |
42 | > **Note**
43 | > Make sure that **DXSDK_DIR** is declared in your environment variables.
44 |
45 | To see your environment variables :
46 |
47 | > **Settings --> System --> About --> System Advanced Settings --> Environment Variables**
48 |
49 | ### Visual Studio :
50 |
51 | 1. Open the solution file (.sln).
52 | 2. Build the project in Release (x86 or x64)
53 |
54 | Every configuration in x86 / x64 (Debug and Realese) are already configured with librairies and includes.
55 |
56 | Everything is setup, you just need to choose between DLL or EXE.
57 |
58 | > **Warning**
59 | > If you have any linking error when compiling make sure that you have correctly install DirectX SDK.
60 |
61 | ## 🧪 Demonstration :
62 |
63 | **DLL - OBS DEMO**
64 |
65 | https://github.com/adamhlt/D3D9-Overlay-ImGui/assets/48086737/3256716b-a66c-4e04-ad53-43e6377aebff
66 |
67 | **EXE - Overlay Window Picker**
68 |
69 | https://github.com/adamhlt/D3D9-Overlay-ImGui/assets/48086737/b4e8c7e9-68a1-4b25-94fb-793b4704e693
70 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/ImGui/imgui_impl_win32.h:
--------------------------------------------------------------------------------
1 | // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications)
2 | // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3 |
4 | // Implemented features:
5 | // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
6 | // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
7 | // [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]
8 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
9 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
10 |
11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
13 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
14 | // Read online: https://github.com/ocornut/imgui/tree/master/docs
15 |
16 | #pragma once
17 | #include "imgui.h" // IMGUI_IMPL_API
18 |
19 | IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd);
20 | IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd);
21 | IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown();
22 | IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame();
23 |
24 | // Win32 message handler your application need to call.
25 | // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on from this helper.
26 | // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it.
27 | // - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE.
28 |
29 | #if 0
30 | extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
31 | #endif
32 |
33 | // DPI-related helpers (optional)
34 | // - Use to enable DPI awareness without having to create an application manifest.
35 | // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
36 | // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
37 | // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
38 | // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
39 | IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness();
40 | IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd
41 | IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor
42 |
43 | // Transparency related helpers (optional) [experimental]
44 | // - Use to enable alpha compositing transparency with the desktop.
45 | // - Use together with e.g. clearing your framebuffer with zero-alpha.
46 | IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd
47 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/D3D9 Overlay ImGui.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 | {5cac93aa-13ae-4d86-9427-02f183de314f}
18 |
19 |
20 |
21 |
22 | Fichiers sources
23 |
24 |
25 | Fichiers d%27en-tête\ImGui
26 |
27 |
28 | Fichiers d%27en-tête\ImGui
29 |
30 |
31 | Fichiers d%27en-tête\ImGui
32 |
33 |
34 | Fichiers d%27en-tête\ImGui
35 |
36 |
37 | Fichiers d%27en-tête\ImGui
38 |
39 |
40 | Fichiers d%27en-tête\ImGui
41 |
42 |
43 | Fichiers d%27en-tête\ImGui
44 |
45 |
46 | Fichiers sources
47 |
48 |
49 | Fichiers sources
50 |
51 |
52 |
53 |
54 | Fichiers d%27en-tête
55 |
56 |
57 | Fichiers d%27en-tête\ImGui
58 |
59 |
60 | Fichiers d%27en-tête\ImGui
61 |
62 |
63 | Fichiers d%27en-tête\ImGui
64 |
65 |
66 | Fichiers d%27en-tête\ImGui
67 |
68 |
69 | Fichiers d%27en-tête\ImGui
70 |
71 |
72 | Fichiers d%27en-tête\ImGui
73 |
74 |
75 | Fichiers d%27en-tête\ImGui
76 |
77 |
78 | Fichiers d%27en-tête\ImGui
79 |
80 |
81 | Fichiers d%27en-tête
82 |
83 |
84 | Fichiers d%27en-tête
85 |
86 |
87 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/D3D9 Overlay ImGui.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Release
10 | Win32
11 |
12 |
13 | Debug
14 | x64
15 |
16 |
17 | Release
18 | x64
19 |
20 |
21 |
22 | 17.0
23 | Win32Proj
24 | {090d4ef2-0230-48d9-ac81-98c3df9b9df8}
25 | D3D9OverlayImGui
26 | 10.0
27 |
28 |
29 |
30 | Application
31 | true
32 | v143
33 | Unicode
34 |
35 |
36 | Application
37 | false
38 | v143
39 | true
40 | Unicode
41 |
42 |
43 | Application
44 | true
45 | v143
46 | Unicode
47 |
48 |
49 | Application
50 | false
51 | v143
52 | true
53 | Unicode
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 | Level3
76 | true
77 | WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)
78 | true
79 | $(DXSDK_DIR)Include;
80 |
81 |
82 | Windows
83 | true
84 | $(DXSDK_DIR)Lib\x86\d3d9.lib;$(DXSDK_DIR)Lib\x86\d3dx9.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)
85 |
86 |
87 |
88 |
89 | Level3
90 | true
91 | true
92 | true
93 | WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)
94 | true
95 | $(DXSDK_DIR)Include;
96 |
97 |
98 | Windows
99 | true
100 | true
101 | true
102 | $(DXSDK_DIR)Lib\x64\d3d9.lib;$(DXSDK_DIR)Lib\x86\d3dx9.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)
103 |
104 |
105 |
106 |
107 | Level3
108 | true
109 | _DEBUG;_WINDOWS;%(PreprocessorDefinitions)
110 | true
111 | $(DXSDK_DIR)Include;
112 |
113 |
114 | Windows
115 | true
116 | $(DXSDK_DIR)Lib\x64\d3d9.lib;$(DXSDK_DIR)Lib\x64\d3dx9.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)
117 |
118 |
119 |
120 |
121 | Level3
122 | true
123 | true
124 | true
125 | NDEBUG;_WINDOWS;%(PreprocessorDefinitions)
126 | true
127 | $(DXSDK_DIR)Include;
128 |
129 |
130 | Windows
131 | true
132 | true
133 | true
134 | $(DXSDK_DIR)Lib\x64\d3d9.lib;$(DXSDK_DIR)Lib\x64\d3dx9.lib;$(CoreLibraryDependencies);%(AdditionalDependencies)
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/ImGui/imconfig.h:
--------------------------------------------------------------------------------
1 | //-----------------------------------------------------------------------------
2 | // COMPILE-TIME OPTIONS FOR DEAR IMGUI
3 | // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
4 | // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
5 | //-----------------------------------------------------------------------------
6 | // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
7 | // B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
8 | //-----------------------------------------------------------------------------
9 | // You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
10 | // files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
11 | // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
12 | // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.
13 | //-----------------------------------------------------------------------------
14 |
15 | #pragma once
16 |
17 | //---- Define assertion handler. Defaults to calling assert().
18 | // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
19 | //#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
20 | //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
21 |
22 | //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
23 | // Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
24 | // DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
25 | // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
26 | //#define IMGUI_API __declspec( dllexport )
27 | //#define IMGUI_API __declspec( dllimport )
28 |
29 | //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.
30 | //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
31 | //#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions.
32 |
33 | //---- Disable all of Dear ImGui or don't implement standard windows/tools.
34 | // It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
35 | //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
36 | //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
37 | //#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowStackToolWindow() will be empty (this was called IMGUI_DISABLE_METRICS_WINDOW before 1.88).
38 |
39 | //---- Don't implement some functions to reduce linkage requirements.
40 | //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
41 | //#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
42 | //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
43 | //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime).
44 | //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
45 | //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
46 | //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
47 | //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
48 | //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
49 | //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
50 | //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
51 |
52 | //---- Include imgui_user.h at the end of imgui.h as a convenience
53 | //#define IMGUI_INCLUDE_IMGUI_USER_H
54 |
55 | //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
56 | //#define IMGUI_USE_BGRA_PACKED_COLOR
57 |
58 | //---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
59 | //#define IMGUI_USE_WCHAR32
60 |
61 | //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
62 | // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
63 | //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
64 | //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
65 | //#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if enabled
66 | //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
67 | //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
68 |
69 | //---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
70 | // Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h.
71 | //#define IMGUI_USE_STB_SPRINTF
72 |
73 | //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
74 | // Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
75 | // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
76 | //#define IMGUI_ENABLE_FREETYPE
77 |
78 | //---- Use stb_truetype to build and rasterize the font atlas (default)
79 | // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
80 | //#define IMGUI_ENABLE_STB_TRUETYPE
81 |
82 | //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
83 | // This will be inlined as part of ImVec2 and ImVec4 class declarations.
84 | /*
85 | #define IM_VEC2_CLASS_EXTRA \
86 | constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
87 | operator MyVec2() const { return MyVec2(x,y); }
88 |
89 | #define IM_VEC4_CLASS_EXTRA \
90 | constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
91 | operator MyVec4() const { return MyVec4(x,y,z,w); }
92 | */
93 | //---- ...Or use Dear ImGui's own very basic math operators.
94 | //#define IMGUI_DEFINE_MATH_OPERATORS
95 |
96 | //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
97 | // Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
98 | // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
99 | // Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
100 | //#define ImDrawIdx unsigned int
101 |
102 | //---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
103 | //struct ImDrawList;
104 | //struct ImDrawCmd;
105 | //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
106 | //#define ImDrawCallback MyImDrawCallback
107 |
108 | //---- Debug Tools: Macro to break in Debugger
109 | // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
110 | //#define IM_DEBUG_BREAK IM_ASSERT(0)
111 | //#define IM_DEBUG_BREAK __debugbreak()
112 |
113 | //---- Debug Tools: Enable slower asserts
114 | //#define IMGUI_DEBUG_PARANOID
115 |
116 | //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
117 | /*
118 | namespace ImGui
119 | {
120 | void MyFunction(const char* name, const MyMatrix44& v);
121 | }
122 | */
123 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/UI.cpp:
--------------------------------------------------------------------------------
1 | #include "UI.h"
2 | #include "Drawing.h"
3 |
4 | LPDIRECT3DDEVICE9 UI::pD3DDevice = nullptr;
5 | LPDIRECT3D9 UI::pD3D = nullptr;
6 | D3DPRESENT_PARAMETERS UI::D3Dpp = {};
7 | UINT UI::g_ResizeHeight = 0;
8 | UINT UI::g_ResizeWidth = 0;
9 | bool UI::bInit = false;
10 | HWND UI::hTargetWindow = nullptr;
11 | BOOL UI::bTargetSet = FALSE;
12 | DWORD UI::dTargetPID = 0;
13 |
14 | HMODULE UI::hCurrentModule = nullptr;
15 |
16 | /**
17 | @brief : Function that create a D3D9 device.
18 | @param hWnd : HWND of the created window.
19 | @retval : true if the function succeed else false.
20 | **/
21 | bool UI::CreateDeviceD3D(const HWND hWnd)
22 | {
23 | if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == nullptr)
24 | return false;
25 |
26 | // Create the D3DDevice
27 | ZeroMemory(&D3Dpp, sizeof(D3Dpp));
28 | D3Dpp.Windowed = TRUE;
29 | D3Dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
30 | D3Dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
31 | D3Dpp.EnableAutoDepthStencil = TRUE;
32 | D3Dpp.AutoDepthStencilFormat = D3DFMT_D16;
33 | D3Dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
34 | if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &D3Dpp, &pD3DDevice) < 0)
35 | return false;
36 |
37 | return true;
38 | }
39 |
40 | #ifndef WM_DPICHANGED
41 | #define WM_DPICHANGED 0x02E0 // From Windows SDK 8.1+ headers
42 | #endif
43 |
44 | /**
45 | @brief : Window message handler (https://learn.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-wndproc).
46 | **/
47 | LRESULT WINAPI UI::WndProc(const HWND hWnd, const UINT msg, const WPARAM wParam, const LPARAM lParam)
48 | {
49 | if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
50 | return true;
51 |
52 | switch (msg)
53 | {
54 | case WM_SIZE:
55 | if (wParam == SIZE_MINIMIZED)
56 | return 0;
57 | g_ResizeWidth = (UINT)LOWORD(lParam); // Queue resize
58 | g_ResizeHeight = (UINT)HIWORD(lParam);
59 | return 0;
60 |
61 | case WM_SYSCOMMAND:
62 | if ((wParam & 0xfff0) == SC_KEYMENU)
63 | return 0;
64 | break;
65 |
66 | case WM_DESTROY:
67 | ::PostQuitMessage(0);
68 | return 0;
69 |
70 | default:
71 | break;
72 | }
73 | return ::DefWindowProc(hWnd, msg, wParam, lParam);
74 | }
75 |
76 | /**
77 | @brief : Function that create the overlay window and more.
78 | **/
79 | void UI::Render()
80 | {
81 | ImGui_ImplWin32_EnableDpiAwareness();
82 |
83 | // Get the main window of the process when overlay as DLL
84 | #ifdef _WINDLL
85 | if (hTargetWindow == nullptr)
86 | GetWindow();
87 | #endif
88 |
89 | WNDCLASSEX wc;
90 |
91 | wc.cbClsExtra = NULL;
92 | wc.cbSize = sizeof(WNDCLASSEX);
93 | wc.cbWndExtra = NULL;
94 | wc.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(0, 0, 0));
95 | wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
96 | wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
97 | wc.hIconSm = LoadIcon(nullptr, IDI_APPLICATION);
98 | wc.hInstance = GetModuleHandle(nullptr);
99 | wc.lpfnWndProc = WndProc;
100 | wc.lpszClassName = _T("D3D9 Overlay ImGui");
101 | wc.lpszMenuName = nullptr;
102 | wc.style = CS_VREDRAW | CS_HREDRAW;
103 |
104 | ::RegisterClassEx(&wc);
105 | const HWND hwnd = ::CreateWindowExW(WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE, wc.lpszClassName, _T("D3D9 Overlay ImGui"), WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), nullptr, nullptr, wc.hInstance, nullptr);
106 |
107 | SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);
108 | const MARGINS margin = { -1, 0, 0, 0 };
109 | DwmExtendFrameIntoClientArea(hwnd, &margin);
110 |
111 | if (!CreateDeviceD3D(hwnd))
112 | {
113 | CleanupDeviceD3D();
114 | ::UnregisterClass(wc.lpszClassName, wc.hInstance);
115 | return;
116 | }
117 |
118 | ::ShowWindow(hwnd, SW_SHOWDEFAULT);
119 | ::UpdateWindow(hwnd);
120 |
121 | IMGUI_CHECKVERSION();
122 | ImGui::CreateContext();
123 | ImGuiIO& io = ImGui::GetIO(); (void)io;
124 | io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
125 |
126 | ImGui::StyleColorsDark();
127 |
128 | // Scale the font size depending of the screen size.
129 | const HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
130 | MONITORINFO info = {};
131 | info.cbSize = sizeof(MONITORINFO);
132 | GetMonitorInfo(monitor, &info);
133 | const int monitor_height = info.rcMonitor.bottom - info.rcMonitor.top;
134 |
135 | if (monitor_height > 1080)
136 | {
137 | const float fScale = 2.0f;
138 | ImFontConfig cfg;
139 | cfg.SizePixels = 13 * fScale;
140 | ImGui::GetIO().Fonts->AddFontDefault(&cfg);
141 | }
142 |
143 | ImGui::GetIO().IniFilename = nullptr;
144 |
145 | ImGui_ImplWin32_Init(hwnd);
146 | ImGui_ImplDX9_Init(pD3DDevice);
147 |
148 | const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 0.0f);
149 |
150 | bInit = true;
151 |
152 | bool bDone = false;
153 |
154 | while (!bDone)
155 | {
156 | MSG msg;
157 | while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
158 | {
159 | ::TranslateMessage(&msg);
160 | ::DispatchMessage(&msg);
161 | if (msg.message == WM_QUIT)
162 | bDone = true;
163 | }
164 |
165 | if (GetAsyncKeyState(VK_END) & 1)
166 | bDone = true;
167 |
168 | // Check if the targeted window is still up.
169 | if (!IsWindowAlive() && bTargetSet)
170 | bDone = true;
171 |
172 | if (bDone)
173 | break;
174 |
175 | if (g_ResizeWidth != 0 && g_ResizeHeight != 0)
176 | {
177 | D3Dpp.BackBufferWidth = g_ResizeWidth;
178 | D3Dpp.BackBufferHeight = g_ResizeHeight;
179 | g_ResizeWidth = g_ResizeHeight = 0;
180 | ResetDevice();
181 | }
182 |
183 | // Move the window on top of the targeted window and handle resize.
184 | #ifdef _WINDLL
185 | if (hTargetWindow != nullptr)
186 | MoveWindow(hwnd);
187 | else
188 | continue;
189 | #else
190 | if (hTargetWindow != nullptr && bTargetSet)
191 | MoveWindow(hwnd);
192 | #endif
193 |
194 | // Clear overlay when the targeted window is not focus
195 | if (!IsWindowFocus(hwnd) && bTargetSet)
196 | {
197 | pD3DDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
198 | pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
199 | pD3DDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
200 | const D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x * clear_color.w * 255.0f), (int)(clear_color.y * clear_color.w * 255.0f), (int)(clear_color.z * clear_color.w * 255.0f), (int)(clear_color.w * 255.0f));
201 | pD3DDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
202 |
203 | if (pD3DDevice->BeginScene() >= 0)
204 | pD3DDevice->EndScene();
205 |
206 | const HRESULT result = pD3DDevice->Present(nullptr, nullptr, nullptr, nullptr);
207 |
208 | // Handle loss of D3D9 device
209 | if (result == D3DERR_DEVICELOST && pD3DDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
210 | ResetDevice();
211 |
212 | continue;
213 | }
214 |
215 | ImGui_ImplDX9_NewFrame();
216 | ImGui_ImplWin32_NewFrame();
217 | ImGui::NewFrame();
218 | {
219 | Drawing::Draw();
220 | }
221 | ImGui::EndFrame();
222 |
223 | // Overlay handle inputs when menu is showed.
224 | if (Drawing::isActive())
225 | SetWindowLong(hwnd, GWL_EXSTYLE, WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TOOLWINDOW);
226 | else
227 | SetWindowLong(hwnd, GWL_EXSTYLE, WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOOLWINDOW);
228 |
229 | ImGui::Render();
230 | ImGui::EndFrame();
231 |
232 | pD3DDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
233 | pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
234 | pD3DDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
235 | const D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x * clear_color.w * 255.0f), (int)(clear_color.y * clear_color.w * 255.0f), (int)(clear_color.z * clear_color.w * 255.0f), (int)(clear_color.w * 255.0f));
236 | pD3DDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
237 |
238 | // Draw figure with DirectX
239 | if (IsWindowTargeted())
240 | Drawing::DXDraw(pD3DDevice);
241 |
242 | if (pD3DDevice->BeginScene() >= 0)
243 | {
244 | ImGui::Render();
245 | ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
246 | pD3DDevice->EndScene();
247 | }
248 |
249 | const HRESULT result = pD3DDevice->Present(nullptr, nullptr, nullptr, nullptr);
250 |
251 | // Handle loss of D3D9 device
252 | if (result == D3DERR_DEVICELOST && pD3DDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
253 | ResetDevice();
254 | }
255 |
256 | bInit = false;
257 |
258 | ImGui_ImplDX9_Shutdown();
259 | ImGui_ImplWin32_Shutdown();
260 | ImGui::DestroyContext();
261 |
262 | CleanupDeviceD3D();
263 | ::DestroyWindow(hwnd);
264 | ::UnregisterClass(wc.lpszClassName, wc.hInstance);
265 |
266 | #ifdef _WINDLL
267 | CreateThread(nullptr, NULL, (LPTHREAD_START_ROUTINE)FreeLibrary, hCurrentModule, NULL, nullptr);
268 | #else
269 | TerminateProcess(GetModuleHandleA(nullptr), 0);
270 | #endif
271 | }
272 |
273 | /**
274 | @brief : Reset the current D3D9 device.
275 | **/
276 | void UI::ResetDevice()
277 | {
278 | ImGui_ImplDX9_InvalidateDeviceObjects();
279 | const HRESULT hr = pD3DDevice->Reset(&D3Dpp);
280 | if (hr == D3DERR_INVALIDCALL)
281 | IM_ASSERT(0);
282 | ImGui_ImplDX9_CreateDeviceObjects();
283 | }
284 |
285 | /**
286 | @brief : Release the D3D9 device and object.
287 | **/
288 | void UI::CleanupDeviceD3D()
289 | {
290 | if (pD3DDevice) { pD3DDevice->Release(); pD3DDevice = nullptr; }
291 | if (pD3D) { pD3D->Release(); pD3D = nullptr; }
292 | }
293 |
294 |
295 | /**
296 | @brief : Function that retrieve the main window of the process.
297 | This function is only called when the overlay is build as DLL.
298 | **/
299 | void UI::GetWindow()
300 | {
301 | EnumWindows(EnumWind, NULL);
302 | }
303 |
304 | /**
305 | @brief : Callback function that retrive the main window of the process.
306 | This function is only called when the overlay is build as DLL.
307 | (https://learn.microsoft.com/fr-fr/windows/win32/api/winuser/nf-winuser-enumwindows)
308 |
309 | **/
310 | BOOL CALLBACK UI::EnumWind(const HWND hWindow, const LPARAM lPrams)
311 | {
312 | DWORD procID;
313 | GetWindowThreadProcessId(hWindow, &procID);
314 | if (GetCurrentProcessId() != procID)
315 | return TRUE;
316 |
317 | if (!IsWindowValid(hWindow))
318 | return TRUE;
319 |
320 | SetTargetWindow(hWindow);
321 | return FALSE;
322 | }
323 |
324 | /**
325 | @brief : Function that move the overlay on top of the targeted window.
326 | @param hCurrentProcessWindow : Window of the overlay.
327 | **/
328 | void UI::MoveWindow(const HWND hCurrentProcessWindow)
329 | {
330 | RECT rect;
331 | if (hTargetWindow == nullptr)
332 | return;
333 |
334 | GetWindowRect(hTargetWindow, &rect);
335 |
336 | int lWindowWidth = rect.right - rect.left;
337 | int lWindowHeight = rect.bottom - rect.top;
338 |
339 | lWindowWidth -= 5;
340 | lWindowHeight -= 29;
341 |
342 | SetWindowPos(hCurrentProcessWindow, nullptr, rect.left, rect.top, lWindowWidth, lWindowHeight, SWP_SHOWWINDOW);
343 | }
344 |
345 | /**
346 | @brief : Function that check if the overlay window or the targeted window is focus.
347 | @param hCurrentProcessWindow : Window of the overlay.
348 | @retval : TRUE if one of the window is focus else FALSE.
349 | **/
350 | BOOL UI::IsWindowFocus(const HWND hCurrentProcessWindow)
351 | {
352 | char lpCurrentWindowUsedClass[125];
353 | char lpCurrentWindowClass[125];
354 | char lpOverlayWindowClass[125];
355 |
356 | const HWND hCurrentWindowUsed = GetForegroundWindow();
357 | if (GetClassNameA(hCurrentWindowUsed, lpCurrentWindowUsedClass, sizeof(lpCurrentWindowUsedClass)) == 0)
358 | return FALSE;
359 |
360 | if (GetClassNameA(hTargetWindow, lpCurrentWindowClass, sizeof(lpCurrentWindowClass)) == 0)
361 | return FALSE;
362 |
363 | if (GetClassNameA(hCurrentProcessWindow, lpOverlayWindowClass, sizeof(lpOverlayWindowClass)) == 0)
364 | return FALSE;
365 |
366 | if (strcmp(lpCurrentWindowUsedClass, lpCurrentWindowClass) != 0 && strcmp(lpCurrentWindowUsedClass, lpOverlayWindowClass) != 0)
367 | {
368 | SetWindowLong(hCurrentProcessWindow, GWL_EXSTYLE, WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOOLWINDOW);
369 | return FALSE;
370 | }
371 |
372 | return TRUE;
373 | }
374 |
375 | /**
376 | @brief : function that check if a target window is set.
377 | @retval : TRUE if a target window has been setted else FALSE.
378 | **/
379 | BOOL UI::IsWindowTargeted()
380 | {
381 | return bTargetSet;
382 | }
383 |
384 | /**
385 | @brief : Function that clear the current window list and enumerate all windows.
386 | @param vWindowList : pointer of the WindowItem vector.
387 | **/
388 | void UI::GetAllWindow(std::vector* vWindowList)
389 | {
390 | vWindowList->clear();
391 | EnumWindows(EnumAllWind, (LPARAM)vWindowList);
392 | }
393 |
394 | /**
395 | @brief : Callback function that retrive all the valid window and get processname, pid and window title.
396 | (https://learn.microsoft.com/fr-fr/windows/win32/api/winuser/nf-winuser-enumwindows)
397 | **/
398 | BOOL CALLBACK UI::EnumAllWind(const HWND hWindow, const LPARAM lPrams)
399 | {
400 | if (!IsWindowValid(hWindow))
401 | return TRUE;
402 |
403 | WindowItem CurrentWindowItem = {hWindow, 0, 0};
404 | DWORD procID;
405 |
406 | GetWindowTextA(hWindow, CurrentWindowItem.CurrentWindowTitle, sizeof(CurrentWindowItem.CurrentWindowTitle));
407 |
408 | if (strlen(CurrentWindowItem.CurrentWindowTitle) == 0)
409 | return TRUE;
410 |
411 | GetWindowThreadProcessId(hWindow, &procID);
412 | GetProcessName(CurrentWindowItem.CurrentProcessName, procID);
413 |
414 | const auto vWindowList = (std::vector*)lPrams;
415 |
416 | vWindowList->push_back(CurrentWindowItem);
417 |
418 | return TRUE;
419 | }
420 |
421 |
422 | /**
423 | @brief : Function that retrieve the process name from the PID.
424 | @param lpProcessName : pointer to the string that store the process name.
425 | @param dPID : PID of the process.
426 | **/
427 | void UI::GetProcessName(const LPSTR lpProcessName, const DWORD dPID)
428 | {
429 | char lpCurrentProcessName[125];
430 |
431 | PROCESSENTRY32 ProcList{};
432 | ProcList.dwSize = sizeof(ProcList);
433 |
434 | const HANDLE hProcList = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
435 | if (hProcList == INVALID_HANDLE_VALUE)
436 | return;
437 |
438 | if (!Process32First(hProcList, &ProcList))
439 | return;
440 |
441 |
442 | if (ProcList.th32ProcessID == dPID)
443 | {
444 | wcstombs_s(nullptr, lpCurrentProcessName, ProcList.szExeFile, sizeof(lpCurrentProcessName));
445 | strncpy_s(lpProcessName, sizeof(lpCurrentProcessName), lpCurrentProcessName, sizeof(lpCurrentProcessName));
446 | return;
447 | }
448 |
449 | while (Process32Next(hProcList, &ProcList))
450 | {
451 | if (ProcList.th32ProcessID == dPID)
452 | {
453 | wcstombs_s(nullptr, lpCurrentProcessName, ProcList.szExeFile, sizeof(lpCurrentProcessName));
454 | strncpy_s(lpProcessName, sizeof(lpCurrentProcessName), lpCurrentProcessName, sizeof(lpCurrentProcessName));
455 | return;
456 | }
457 | }
458 | }
459 |
460 | /**
461 | @brief : Function that check if a window is valid.
462 | @param hCurrentWindow : window to be tested.
463 | @retval : TRUE if the window is valid else FALSE.
464 | **/
465 | BOOL UI::IsWindowValid(const HWND hCurrentWindow)
466 | {
467 | DWORD styles, ex_styles;
468 | RECT rect;
469 |
470 | if (!IsWindowVisible(hCurrentWindow) ||
471 | (IsIconic(hCurrentWindow) || IsWindowCloaked(hCurrentWindow)))
472 | return FALSE;
473 |
474 | GetClientRect(hCurrentWindow, &rect);
475 | styles = (DWORD)GetWindowLongPtr(hCurrentWindow, GWL_STYLE);
476 | ex_styles = (DWORD)GetWindowLongPtr(hCurrentWindow, GWL_EXSTYLE);
477 |
478 | if (ex_styles & WS_EX_TOOLWINDOW)
479 | return FALSE;
480 | if (styles & WS_CHILD)
481 | return FALSE;
482 | if (rect.bottom == 0 || rect.right == 0)
483 | return FALSE;
484 |
485 | return TRUE;
486 | }
487 |
488 | /**
489 | @brief : Function that check if a window is cloacked.
490 | @param hCurrentWindow : window to be tested.
491 | @retval : TRUE if the window is cloacked else FALSE.
492 | **/
493 | BOOL UI::IsWindowCloaked(const HWND hCurrentWindow)
494 | {
495 | DWORD cloaked;
496 | const HRESULT hr = DwmGetWindowAttribute(hCurrentWindow, DWMWA_CLOAKED, &cloaked,
497 | sizeof(cloaked));
498 | return SUCCEEDED(hr) && cloaked;
499 | }
500 |
501 | /**
502 | @brief : Setter function used to define the target window from the window picker.
503 | This is used only when the overlay is build as an EXE.
504 | @param hWindow : target window.
505 | **/
506 | void UI::SetTargetWindow(const HWND hWindow)
507 | {
508 | hTargetWindow = hWindow;
509 | SetForegroundWindow(hTargetWindow);
510 | GetWindowThreadProcessId(hTargetWindow, &dTargetPID);
511 | bTargetSet = TRUE;
512 | }
513 |
514 | /**
515 | @brief : Function that look if the targeted window has been closed.
516 | @retval : TRUE if the function is still up else FALSE.
517 | **/
518 | BOOL UI::IsWindowAlive()
519 | {
520 | DWORD dCurrentPID;
521 |
522 | if (hTargetWindow == nullptr)
523 | return FALSE;
524 |
525 | if (!IsWindow(hTargetWindow))
526 | return FALSE;
527 |
528 | GetWindowThreadProcessId(hTargetWindow, &dCurrentPID);
529 |
530 | if (dCurrentPID != dTargetPID)
531 | return FALSE;
532 |
533 | return TRUE;
534 | }
535 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/ImGui/imgui_impl_dx9.cpp:
--------------------------------------------------------------------------------
1 | // dear imgui: Renderer Backend for DirectX9
2 | // This needs to be used along with a Platform Backend (e.g. Win32)
3 |
4 | // Implemented features:
5 | // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
7 |
8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
10 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
11 | // Read online: https://github.com/ocornut/imgui/tree/master/docs
12 |
13 | // CHANGELOG
14 | // (minor and older changes stripped away, please see git history for details)
15 | // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
16 | // 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).
17 | // 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1.
18 | // 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
19 | // 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states.
20 | // 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857).
21 | // 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file.
22 | // 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer.
23 | // 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
24 | // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
25 | // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects().
26 | // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288.
27 | // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
28 | // 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
29 | // 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
30 | // 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
31 | // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
32 | // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
33 |
34 | #include "imgui.h"
35 | #include "imgui_impl_dx9.h"
36 |
37 | // DirectX
38 | #include
39 |
40 | // DirectX data
41 | struct ImGui_ImplDX9_Data
42 | {
43 | LPDIRECT3DDEVICE9 pd3dDevice;
44 | LPDIRECT3DVERTEXBUFFER9 pVB;
45 | LPDIRECT3DINDEXBUFFER9 pIB;
46 | LPDIRECT3DTEXTURE9 FontTexture;
47 | int VertexBufferSize;
48 | int IndexBufferSize;
49 |
50 | ImGui_ImplDX9_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
51 | };
52 |
53 | struct CUSTOMVERTEX
54 | {
55 | float pos[3];
56 | D3DCOLOR col;
57 | float uv[2];
58 | };
59 | #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
60 |
61 | #ifdef IMGUI_USE_BGRA_PACKED_COLOR
62 | #define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL)
63 | #else
64 | #define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16))
65 | #endif
66 |
67 | // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
68 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
69 | static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData()
70 | {
71 | return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
72 | }
73 |
74 | // Functions
75 | static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
76 | {
77 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
78 |
79 | // Setup viewport
80 | D3DVIEWPORT9 vp;
81 | vp.X = vp.Y = 0;
82 | vp.Width = (DWORD)draw_data->DisplaySize.x;
83 | vp.Height = (DWORD)draw_data->DisplaySize.y;
84 | vp.MinZ = 0.0f;
85 | vp.MaxZ = 1.0f;
86 | bd->pd3dDevice->SetViewport(&vp);
87 |
88 | // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling.
89 | bd->pd3dDevice->SetPixelShader(nullptr);
90 | bd->pd3dDevice->SetVertexShader(nullptr);
91 | bd->pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
92 | bd->pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
93 | bd->pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
94 | bd->pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
95 | bd->pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
96 | bd->pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
97 | bd->pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
98 | bd->pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
99 | bd->pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
100 | bd->pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
101 | bd->pd3dDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
102 | bd->pd3dDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
103 | bd->pd3dDevice->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
104 | bd->pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
105 | bd->pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
106 | bd->pd3dDevice->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
107 | bd->pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
108 | bd->pd3dDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
109 | bd->pd3dDevice->SetRenderState(D3DRS_CLIPPING, TRUE);
110 | bd->pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
111 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
112 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
113 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
114 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
115 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
116 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
117 | bd->pd3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
118 | bd->pd3dDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
119 | bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
120 | bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
121 |
122 | // Setup orthographic projection matrix
123 | // 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.
124 | // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
125 | {
126 | float L = draw_data->DisplayPos.x + 0.5f;
127 | float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
128 | float T = draw_data->DisplayPos.y + 0.5f;
129 | float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
130 | 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 } } };
131 | D3DMATRIX mat_projection =
132 | { { {
133 | 2.0f/(R-L), 0.0f, 0.0f, 0.0f,
134 | 0.0f, 2.0f/(T-B), 0.0f, 0.0f,
135 | 0.0f, 0.0f, 0.5f, 0.0f,
136 | (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f
137 | } } };
138 | bd->pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
139 | bd->pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
140 | bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
141 | }
142 | }
143 |
144 | // Render function.
145 | void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
146 | {
147 | // Avoid rendering when minimized
148 | if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
149 | return;
150 |
151 | // Create and grow buffers if needed
152 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
153 | if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
154 | {
155 | if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
156 | bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
157 | if (bd->pd3dDevice->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0)
158 | return;
159 | }
160 | if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
161 | {
162 | if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
163 | bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
164 | 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)
165 | return;
166 | }
167 |
168 | // Backup the DX9 state
169 | IDirect3DStateBlock9* d3d9_state_block = nullptr;
170 | if (bd->pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
171 | return;
172 | if (d3d9_state_block->Capture() < 0)
173 | {
174 | d3d9_state_block->Release();
175 | return;
176 | }
177 |
178 | // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
179 | D3DMATRIX last_world, last_view, last_projection;
180 | bd->pd3dDevice->GetTransform(D3DTS_WORLD, &last_world);
181 | bd->pd3dDevice->GetTransform(D3DTS_VIEW, &last_view);
182 | bd->pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection);
183 |
184 | // Allocate buffers
185 | CUSTOMVERTEX* vtx_dst;
186 | ImDrawIdx* idx_dst;
187 | if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
188 | {
189 | d3d9_state_block->Release();
190 | return;
191 | }
192 | if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
193 | {
194 | bd->pVB->Unlock();
195 | d3d9_state_block->Release();
196 | return;
197 | }
198 |
199 | // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
200 | // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and
201 | // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR
202 | // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
203 | for (int n = 0; n < draw_data->CmdListsCount; n++)
204 | {
205 | const ImDrawList* cmd_list = draw_data->CmdLists[n];
206 | const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
207 | for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
208 | {
209 | vtx_dst->pos[0] = vtx_src->pos.x;
210 | vtx_dst->pos[1] = vtx_src->pos.y;
211 | vtx_dst->pos[2] = 0.0f;
212 | vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col);
213 | vtx_dst->uv[0] = vtx_src->uv.x;
214 | vtx_dst->uv[1] = vtx_src->uv.y;
215 | vtx_dst++;
216 | vtx_src++;
217 | }
218 | memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
219 | idx_dst += cmd_list->IdxBuffer.Size;
220 | }
221 | bd->pVB->Unlock();
222 | bd->pIB->Unlock();
223 | bd->pd3dDevice->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
224 | bd->pd3dDevice->SetIndices(bd->pIB);
225 | bd->pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
226 |
227 | // Setup desired DX state
228 | ImGui_ImplDX9_SetupRenderState(draw_data);
229 |
230 | // Render command lists
231 | // (Because we merged all buffers into a single one, we maintain our own offset into them)
232 | int global_vtx_offset = 0;
233 | int global_idx_offset = 0;
234 | ImVec2 clip_off = draw_data->DisplayPos;
235 | for (int n = 0; n < draw_data->CmdListsCount; n++)
236 | {
237 | const ImDrawList* cmd_list = draw_data->CmdLists[n];
238 | for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
239 | {
240 | const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
241 | if (pcmd->UserCallback != nullptr)
242 | {
243 | // User callback, registered via ImDrawList::AddCallback()
244 | // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
245 | if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
246 | ImGui_ImplDX9_SetupRenderState(draw_data);
247 | else
248 | pcmd->UserCallback(cmd_list, pcmd);
249 | }
250 | else
251 | {
252 | // Project scissor/clipping rectangles into framebuffer space
253 | ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
254 | ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
255 | if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
256 | continue;
257 |
258 | // Apply Scissor/clipping rectangle, Bind texture, Draw
259 | const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
260 | const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID();
261 | bd->pd3dDevice->SetTexture(0, texture);
262 | bd->pd3dDevice->SetScissorRect(&r);
263 | bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
264 | }
265 | }
266 | global_idx_offset += cmd_list->IdxBuffer.Size;
267 | global_vtx_offset += cmd_list->VtxBuffer.Size;
268 | }
269 |
270 | // Restore the DX9 transform
271 | bd->pd3dDevice->SetTransform(D3DTS_WORLD, &last_world);
272 | bd->pd3dDevice->SetTransform(D3DTS_VIEW, &last_view);
273 | bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection);
274 |
275 | // Restore the DX9 state
276 | d3d9_state_block->Apply();
277 | d3d9_state_block->Release();
278 | }
279 |
280 | bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
281 | {
282 | ImGuiIO& io = ImGui::GetIO();
283 | IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
284 |
285 | // Setup backend capabilities flags
286 | ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)();
287 | io.BackendRendererUserData = (void*)bd;
288 | io.BackendRendererName = "imgui_impl_dx9";
289 | io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
290 |
291 | bd->pd3dDevice = device;
292 | bd->pd3dDevice->AddRef();
293 |
294 | return true;
295 | }
296 |
297 | void ImGui_ImplDX9_Shutdown()
298 | {
299 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
300 | IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
301 | ImGuiIO& io = ImGui::GetIO();
302 |
303 | ImGui_ImplDX9_InvalidateDeviceObjects();
304 | if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
305 | io.BackendRendererName = nullptr;
306 | io.BackendRendererUserData = nullptr;
307 | io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
308 | IM_DELETE(bd);
309 | }
310 |
311 | static bool ImGui_ImplDX9_CreateFontsTexture()
312 | {
313 | // Build texture atlas
314 | ImGuiIO& io = ImGui::GetIO();
315 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
316 | unsigned char* pixels;
317 | int width, height, bytes_per_pixel;
318 | io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
319 |
320 | // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
321 | #ifndef IMGUI_USE_BGRA_PACKED_COLOR
322 | if (io.Fonts->TexPixelsUseColors)
323 | {
324 | ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel);
325 | for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++)
326 | *dst = IMGUI_COL_TO_DX9_ARGB(*src);
327 | pixels = (unsigned char*)dst_start;
328 | }
329 | #endif
330 |
331 | // Upload texture to graphics system
332 | bd->FontTexture = nullptr;
333 | if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0)
334 | return false;
335 | D3DLOCKED_RECT tex_locked_rect;
336 | if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK)
337 | return false;
338 | for (int y = 0; y < height; y++)
339 | 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);
340 | bd->FontTexture->UnlockRect(0);
341 |
342 | // Store our identifier
343 | io.Fonts->SetTexID((ImTextureID)bd->FontTexture);
344 |
345 | #ifndef IMGUI_USE_BGRA_PACKED_COLOR
346 | if (io.Fonts->TexPixelsUseColors)
347 | ImGui::MemFree(pixels);
348 | #endif
349 |
350 | return true;
351 | }
352 |
353 | bool ImGui_ImplDX9_CreateDeviceObjects()
354 | {
355 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
356 | if (!bd || !bd->pd3dDevice)
357 | return false;
358 | if (!ImGui_ImplDX9_CreateFontsTexture())
359 | return false;
360 | return true;
361 | }
362 |
363 | void ImGui_ImplDX9_InvalidateDeviceObjects()
364 | {
365 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
366 | if (!bd || !bd->pd3dDevice)
367 | return;
368 | if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
369 | if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
370 | 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.
371 | }
372 |
373 | void ImGui_ImplDX9_NewFrame()
374 | {
375 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
376 | IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX9_Init()?");
377 |
378 | if (!bd->FontTexture)
379 | ImGui_ImplDX9_CreateDeviceObjects();
380 | }
381 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/ImGui/imstb_rectpack.h:
--------------------------------------------------------------------------------
1 | // [DEAR IMGUI]
2 | // This is a slightly modified version of stb_rect_pack.h 1.01.
3 | // Grep for [DEAR IMGUI] to find the changes.
4 | //
5 | // stb_rect_pack.h - v1.01 - public domain - rectangle packing
6 | // Sean Barrett 2014
7 | //
8 | // Useful for e.g. packing rectangular textures into an atlas.
9 | // Does not do rotation.
10 | //
11 | // Before #including,
12 | //
13 | // #define STB_RECT_PACK_IMPLEMENTATION
14 | //
15 | // in the file that you want to have the implementation.
16 | //
17 | // Not necessarily the awesomest packing method, but better than
18 | // the totally naive one in stb_truetype (which is primarily what
19 | // this is meant to replace).
20 | //
21 | // Has only had a few tests run, may have issues.
22 | //
23 | // More docs to come.
24 | //
25 | // No memory allocations; uses qsort() and assert() from stdlib.
26 | // Can override those by defining STBRP_SORT and STBRP_ASSERT.
27 | //
28 | // This library currently uses the Skyline Bottom-Left algorithm.
29 | //
30 | // Please note: better rectangle packers are welcome! Please
31 | // implement them to the same API, but with a different init
32 | // function.
33 | //
34 | // Credits
35 | //
36 | // Library
37 | // Sean Barrett
38 | // Minor features
39 | // Martins Mozeiko
40 | // github:IntellectualKitty
41 | //
42 | // Bugfixes / warning fixes
43 | // Jeremy Jaussaud
44 | // Fabian Giesen
45 | //
46 | // Version history:
47 | //
48 | // 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
49 | // 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
50 | // 0.99 (2019-02-07) warning fixes
51 | // 0.11 (2017-03-03) return packing success/fail result
52 | // 0.10 (2016-10-25) remove cast-away-const to avoid warnings
53 | // 0.09 (2016-08-27) fix compiler warnings
54 | // 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
55 | // 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
56 | // 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
57 | // 0.05: added STBRP_ASSERT to allow replacing assert
58 | // 0.04: fixed minor bug in STBRP_LARGE_RECTS support
59 | // 0.01: initial release
60 | //
61 | // LICENSE
62 | //
63 | // See end of file for license information.
64 |
65 | //////////////////////////////////////////////////////////////////////////////
66 | //
67 | // INCLUDE SECTION
68 | //
69 |
70 | #ifndef STB_INCLUDE_STB_RECT_PACK_H
71 | #define STB_INCLUDE_STB_RECT_PACK_H
72 |
73 | #define STB_RECT_PACK_VERSION 1
74 |
75 | #ifdef STBRP_STATIC
76 | #define STBRP_DEF static
77 | #else
78 | #define STBRP_DEF extern
79 | #endif
80 |
81 | #ifdef __cplusplus
82 | extern "C" {
83 | #endif
84 |
85 | typedef struct stbrp_context stbrp_context;
86 | typedef struct stbrp_node stbrp_node;
87 | typedef struct stbrp_rect stbrp_rect;
88 |
89 | typedef int stbrp_coord;
90 |
91 | #define STBRP__MAXVAL 0x7fffffff
92 | // Mostly for internal use, but this is the maximum supported coordinate value.
93 |
94 | STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
95 | // Assign packed locations to rectangles. The rectangles are of type
96 | // 'stbrp_rect' defined below, stored in the array 'rects', and there
97 | // are 'num_rects' many of them.
98 | //
99 | // Rectangles which are successfully packed have the 'was_packed' flag
100 | // set to a non-zero value and 'x' and 'y' store the minimum location
101 | // on each axis (i.e. bottom-left in cartesian coordinates, top-left
102 | // if you imagine y increasing downwards). Rectangles which do not fit
103 | // have the 'was_packed' flag set to 0.
104 | //
105 | // You should not try to access the 'rects' array from another thread
106 | // while this function is running, as the function temporarily reorders
107 | // the array while it executes.
108 | //
109 | // To pack into another rectangle, you need to call stbrp_init_target
110 | // again. To continue packing into the same rectangle, you can call
111 | // this function again. Calling this multiple times with multiple rect
112 | // arrays will probably produce worse packing results than calling it
113 | // a single time with the full rectangle array, but the option is
114 | // available.
115 | //
116 | // The function returns 1 if all of the rectangles were successfully
117 | // packed and 0 otherwise.
118 |
119 | struct stbrp_rect
120 | {
121 | // reserved for your use:
122 | int id;
123 |
124 | // input:
125 | stbrp_coord w, h;
126 |
127 | // output:
128 | stbrp_coord x, y;
129 | int was_packed; // non-zero if valid packing
130 |
131 | }; // 16 bytes, nominally
132 |
133 |
134 | STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
135 | // Initialize a rectangle packer to:
136 | // pack a rectangle that is 'width' by 'height' in dimensions
137 | // using temporary storage provided by the array 'nodes', which is 'num_nodes' long
138 | //
139 | // You must call this function every time you start packing into a new target.
140 | //
141 | // There is no "shutdown" function. The 'nodes' memory must stay valid for
142 | // the following stbrp_pack_rects() call (or calls), but can be freed after
143 | // the call (or calls) finish.
144 | //
145 | // Note: to guarantee best results, either:
146 | // 1. make sure 'num_nodes' >= 'width'
147 | // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
148 | //
149 | // If you don't do either of the above things, widths will be quantized to multiples
150 | // of small integers to guarantee the algorithm doesn't run out of temporary storage.
151 | //
152 | // If you do #2, then the non-quantized algorithm will be used, but the algorithm
153 | // may run out of temporary storage and be unable to pack some rectangles.
154 |
155 | STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
156 | // Optionally call this function after init but before doing any packing to
157 | // change the handling of the out-of-temp-memory scenario, described above.
158 | // If you call init again, this will be reset to the default (false).
159 |
160 |
161 | STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
162 | // Optionally select which packing heuristic the library should use. Different
163 | // heuristics will produce better/worse results for different data sets.
164 | // If you call init again, this will be reset to the default.
165 |
166 | enum
167 | {
168 | STBRP_HEURISTIC_Skyline_default=0,
169 | STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
170 | STBRP_HEURISTIC_Skyline_BF_sortHeight
171 | };
172 |
173 |
174 | //////////////////////////////////////////////////////////////////////////////
175 | //
176 | // the details of the following structures don't matter to you, but they must
177 | // be visible so you can handle the memory allocations for them
178 |
179 | struct stbrp_node
180 | {
181 | stbrp_coord x,y;
182 | stbrp_node *next;
183 | };
184 |
185 | struct stbrp_context
186 | {
187 | int width;
188 | int height;
189 | int align;
190 | int init_mode;
191 | int heuristic;
192 | int num_nodes;
193 | stbrp_node *active_head;
194 | stbrp_node *free_head;
195 | stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
196 | };
197 |
198 | #ifdef __cplusplus
199 | }
200 | #endif
201 |
202 | #endif
203 |
204 | //////////////////////////////////////////////////////////////////////////////
205 | //
206 | // IMPLEMENTATION SECTION
207 | //
208 |
209 | #ifdef STB_RECT_PACK_IMPLEMENTATION
210 | #ifndef STBRP_SORT
211 | #include
212 | #define STBRP_SORT qsort
213 | #endif
214 |
215 | #ifndef STBRP_ASSERT
216 | #include
217 | #define STBRP_ASSERT assert
218 | #endif
219 |
220 | #ifdef _MSC_VER
221 | #define STBRP__NOTUSED(v) (void)(v)
222 | #define STBRP__CDECL __cdecl
223 | #else
224 | #define STBRP__NOTUSED(v) (void)sizeof(v)
225 | #define STBRP__CDECL
226 | #endif
227 |
228 | enum
229 | {
230 | STBRP__INIT_skyline = 1
231 | };
232 |
233 | STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
234 | {
235 | switch (context->init_mode) {
236 | case STBRP__INIT_skyline:
237 | STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
238 | context->heuristic = heuristic;
239 | break;
240 | default:
241 | STBRP_ASSERT(0);
242 | }
243 | }
244 |
245 | STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
246 | {
247 | if (allow_out_of_mem)
248 | // if it's ok to run out of memory, then don't bother aligning them;
249 | // this gives better packing, but may fail due to OOM (even though
250 | // the rectangles easily fit). @TODO a smarter approach would be to only
251 | // quantize once we've hit OOM, then we could get rid of this parameter.
252 | context->align = 1;
253 | else {
254 | // if it's not ok to run out of memory, then quantize the widths
255 | // so that num_nodes is always enough nodes.
256 | //
257 | // I.e. num_nodes * align >= width
258 | // align >= width / num_nodes
259 | // align = ceil(width/num_nodes)
260 |
261 | context->align = (context->width + context->num_nodes-1) / context->num_nodes;
262 | }
263 | }
264 |
265 | STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
266 | {
267 | int i;
268 |
269 | for (i=0; i < num_nodes-1; ++i)
270 | nodes[i].next = &nodes[i+1];
271 | nodes[i].next = NULL;
272 | context->init_mode = STBRP__INIT_skyline;
273 | context->heuristic = STBRP_HEURISTIC_Skyline_default;
274 | context->free_head = &nodes[0];
275 | context->active_head = &context->extra[0];
276 | context->width = width;
277 | context->height = height;
278 | context->num_nodes = num_nodes;
279 | stbrp_setup_allow_out_of_mem(context, 0);
280 |
281 | // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
282 | context->extra[0].x = 0;
283 | context->extra[0].y = 0;
284 | context->extra[0].next = &context->extra[1];
285 | context->extra[1].x = (stbrp_coord) width;
286 | context->extra[1].y = (1<<30);
287 | context->extra[1].next = NULL;
288 | }
289 |
290 | // find minimum y position if it starts at x1
291 | static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
292 | {
293 | stbrp_node *node = first;
294 | int x1 = x0 + width;
295 | int min_y, visited_width, waste_area;
296 |
297 | STBRP__NOTUSED(c);
298 |
299 | STBRP_ASSERT(first->x <= x0);
300 |
301 | #if 0
302 | // skip in case we're past the node
303 | while (node->next->x <= x0)
304 | ++node;
305 | #else
306 | STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
307 | #endif
308 |
309 | STBRP_ASSERT(node->x <= x0);
310 |
311 | min_y = 0;
312 | waste_area = 0;
313 | visited_width = 0;
314 | while (node->x < x1) {
315 | if (node->y > min_y) {
316 | // raise min_y higher.
317 | // we've accounted for all waste up to min_y,
318 | // but we'll now add more waste for everything we've visted
319 | waste_area += visited_width * (node->y - min_y);
320 | min_y = node->y;
321 | // the first time through, visited_width might be reduced
322 | if (node->x < x0)
323 | visited_width += node->next->x - x0;
324 | else
325 | visited_width += node->next->x - node->x;
326 | } else {
327 | // add waste area
328 | int under_width = node->next->x - node->x;
329 | if (under_width + visited_width > width)
330 | under_width = width - visited_width;
331 | waste_area += under_width * (min_y - node->y);
332 | visited_width += under_width;
333 | }
334 | node = node->next;
335 | }
336 |
337 | *pwaste = waste_area;
338 | return min_y;
339 | }
340 |
341 | typedef struct
342 | {
343 | int x,y;
344 | stbrp_node **prev_link;
345 | } stbrp__findresult;
346 |
347 | static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
348 | {
349 | int best_waste = (1<<30), best_x, best_y = (1 << 30);
350 | stbrp__findresult fr;
351 | stbrp_node **prev, *node, *tail, **best = NULL;
352 |
353 | // align to multiple of c->align
354 | width = (width + c->align - 1);
355 | width -= width % c->align;
356 | STBRP_ASSERT(width % c->align == 0);
357 |
358 | // if it can't possibly fit, bail immediately
359 | if (width > c->width || height > c->height) {
360 | fr.prev_link = NULL;
361 | fr.x = fr.y = 0;
362 | return fr;
363 | }
364 |
365 | node = c->active_head;
366 | prev = &c->active_head;
367 | while (node->x + width <= c->width) {
368 | int y,waste;
369 | y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
370 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
371 | // bottom left
372 | if (y < best_y) {
373 | best_y = y;
374 | best = prev;
375 | }
376 | } else {
377 | // best-fit
378 | if (y + height <= c->height) {
379 | // can only use it if it first vertically
380 | if (y < best_y || (y == best_y && waste < best_waste)) {
381 | best_y = y;
382 | best_waste = waste;
383 | best = prev;
384 | }
385 | }
386 | }
387 | prev = &node->next;
388 | node = node->next;
389 | }
390 |
391 | best_x = (best == NULL) ? 0 : (*best)->x;
392 |
393 | // if doing best-fit (BF), we also have to try aligning right edge to each node position
394 | //
395 | // e.g, if fitting
396 | //
397 | // ____________________
398 | // |____________________|
399 | //
400 | // into
401 | //
402 | // | |
403 | // | ____________|
404 | // |____________|
405 | //
406 | // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
407 | //
408 | // This makes BF take about 2x the time
409 |
410 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
411 | tail = c->active_head;
412 | node = c->active_head;
413 | prev = &c->active_head;
414 | // find first node that's admissible
415 | while (tail->x < width)
416 | tail = tail->next;
417 | while (tail) {
418 | int xpos = tail->x - width;
419 | int y,waste;
420 | STBRP_ASSERT(xpos >= 0);
421 | // find the left position that matches this
422 | while (node->next->x <= xpos) {
423 | prev = &node->next;
424 | node = node->next;
425 | }
426 | STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
427 | y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
428 | if (y + height <= c->height) {
429 | if (y <= best_y) {
430 | if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
431 | best_x = xpos;
432 | //STBRP_ASSERT(y <= best_y); [DEAR IMGUI]
433 | best_y = y;
434 | best_waste = waste;
435 | best = prev;
436 | }
437 | }
438 | }
439 | tail = tail->next;
440 | }
441 | }
442 |
443 | fr.prev_link = best;
444 | fr.x = best_x;
445 | fr.y = best_y;
446 | return fr;
447 | }
448 |
449 | static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
450 | {
451 | // find best position according to heuristic
452 | stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
453 | stbrp_node *node, *cur;
454 |
455 | // bail if:
456 | // 1. it failed
457 | // 2. the best node doesn't fit (we don't always check this)
458 | // 3. we're out of memory
459 | if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
460 | res.prev_link = NULL;
461 | return res;
462 | }
463 |
464 | // on success, create new node
465 | node = context->free_head;
466 | node->x = (stbrp_coord) res.x;
467 | node->y = (stbrp_coord) (res.y + height);
468 |
469 | context->free_head = node->next;
470 |
471 | // insert the new node into the right starting point, and
472 | // let 'cur' point to the remaining nodes needing to be
473 | // stiched back in
474 |
475 | cur = *res.prev_link;
476 | if (cur->x < res.x) {
477 | // preserve the existing one, so start testing with the next one
478 | stbrp_node *next = cur->next;
479 | cur->next = node;
480 | cur = next;
481 | } else {
482 | *res.prev_link = node;
483 | }
484 |
485 | // from here, traverse cur and free the nodes, until we get to one
486 | // that shouldn't be freed
487 | while (cur->next && cur->next->x <= res.x + width) {
488 | stbrp_node *next = cur->next;
489 | // move the current node to the free list
490 | cur->next = context->free_head;
491 | context->free_head = cur;
492 | cur = next;
493 | }
494 |
495 | // stitch the list back in
496 | node->next = cur;
497 |
498 | if (cur->x < res.x + width)
499 | cur->x = (stbrp_coord) (res.x + width);
500 |
501 | #ifdef _DEBUG
502 | cur = context->active_head;
503 | while (cur->x < context->width) {
504 | STBRP_ASSERT(cur->x < cur->next->x);
505 | cur = cur->next;
506 | }
507 | STBRP_ASSERT(cur->next == NULL);
508 |
509 | {
510 | int count=0;
511 | cur = context->active_head;
512 | while (cur) {
513 | cur = cur->next;
514 | ++count;
515 | }
516 | cur = context->free_head;
517 | while (cur) {
518 | cur = cur->next;
519 | ++count;
520 | }
521 | STBRP_ASSERT(count == context->num_nodes+2);
522 | }
523 | #endif
524 |
525 | return res;
526 | }
527 |
528 | static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
529 | {
530 | const stbrp_rect *p = (const stbrp_rect *) a;
531 | const stbrp_rect *q = (const stbrp_rect *) b;
532 | if (p->h > q->h)
533 | return -1;
534 | if (p->h < q->h)
535 | return 1;
536 | return (p->w > q->w) ? -1 : (p->w < q->w);
537 | }
538 |
539 | static int STBRP__CDECL rect_original_order(const void *a, const void *b)
540 | {
541 | const stbrp_rect *p = (const stbrp_rect *) a;
542 | const stbrp_rect *q = (const stbrp_rect *) b;
543 | return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
544 | }
545 |
546 | STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
547 | {
548 | int i, all_rects_packed = 1;
549 |
550 | // we use the 'was_packed' field internally to allow sorting/unsorting
551 | for (i=0; i < num_rects; ++i) {
552 | rects[i].was_packed = i;
553 | }
554 |
555 | // sort according to heuristic
556 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
557 |
558 | for (i=0; i < num_rects; ++i) {
559 | if (rects[i].w == 0 || rects[i].h == 0) {
560 | rects[i].x = rects[i].y = 0; // empty rect needs no space
561 | } else {
562 | stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
563 | if (fr.prev_link) {
564 | rects[i].x = (stbrp_coord) fr.x;
565 | rects[i].y = (stbrp_coord) fr.y;
566 | } else {
567 | rects[i].x = rects[i].y = STBRP__MAXVAL;
568 | }
569 | }
570 | }
571 |
572 | // unsort
573 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
574 |
575 | // set was_packed flags and all_rects_packed status
576 | for (i=0; i < num_rects; ++i) {
577 | rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
578 | if (!rects[i].was_packed)
579 | all_rects_packed = 0;
580 | }
581 |
582 | // return the all_rects_packed status
583 | return all_rects_packed;
584 | }
585 | #endif
586 |
587 | /*
588 | ------------------------------------------------------------------------------
589 | This software is available under 2 licenses -- choose whichever you prefer.
590 | ------------------------------------------------------------------------------
591 | ALTERNATIVE A - MIT License
592 | Copyright (c) 2017 Sean Barrett
593 | Permission is hereby granted, free of charge, to any person obtaining a copy of
594 | this software and associated documentation files (the "Software"), to deal in
595 | the Software without restriction, including without limitation the rights to
596 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
597 | of the Software, and to permit persons to whom the Software is furnished to do
598 | so, subject to the following conditions:
599 | The above copyright notice and this permission notice shall be included in all
600 | copies or substantial portions of the Software.
601 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
602 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
603 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
604 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
605 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
606 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
607 | SOFTWARE.
608 | ------------------------------------------------------------------------------
609 | ALTERNATIVE B - Public Domain (www.unlicense.org)
610 | This is free and unencumbered software released into the public domain.
611 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
612 | software, either in source code form or as a compiled binary, for any purpose,
613 | commercial or non-commercial, and by any means.
614 | In jurisdictions that recognize copyright laws, the author or authors of this
615 | software dedicate any and all copyright interest in the software to the public
616 | domain. We make this dedication for the benefit of the public at large and to
617 | the detriment of our heirs and successors. We intend this dedication to be an
618 | overt act of relinquishment in perpetuity of all present and future rights to
619 | this software under copyright law.
620 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
621 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
622 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
623 | AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
624 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
625 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
626 | ------------------------------------------------------------------------------
627 | */
628 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Source/D3D9 Overlay ImGui/ImGui/imgui_impl_win32.cpp:
--------------------------------------------------------------------------------
1 | // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications)
2 | // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3 |
4 | // Implemented features:
5 | // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
6 | // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
7 | // [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]
8 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
9 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
10 |
11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
13 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
14 | // Read online: https://github.com/ocornut/imgui/tree/master/docs
15 |
16 | #include "imgui.h"
17 | #include "imgui_impl_win32.h"
18 | #ifndef WIN32_LEAN_AND_MEAN
19 | #define WIN32_LEAN_AND_MEAN
20 | #endif
21 | #include
22 | #include // GET_X_LPARAM(), GET_Y_LPARAM()
23 | #include
24 | #include
25 |
26 | // Configuration flags to add in your imconfig.h file:
27 | //#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.
28 |
29 | // Using XInput for gamepad (will load DLL dynamically)
30 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
31 | #include
32 | typedef DWORD (WINAPI *PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*);
33 | typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*);
34 | #endif
35 |
36 | // CHANGELOG
37 | // (minor and older changes stripped away, please see git history for details)
38 | // 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218)
39 | // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702)
40 | // 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)
41 | // 2023-02-02: Inputs: Flipping WM_MOUSEHWHEEL (horizontal mouse-wheel) value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463)
42 | // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
43 | // 2022-09-28: Inputs: Convert WM_CHAR values with MultiByteToWideChar() when window class was registered as MBCS (not Unicode).
44 | // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
45 | // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
46 | // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
47 | // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
48 | // 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.
49 | // 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.
50 | // 2022-01-12: Inputs: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted.
51 | // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
52 | // 2021-12-16: Inputs: Fill VK_LCONTROL/VK_RCONTROL/VK_LSHIFT/VK_RSHIFT/VK_LMENU/VK_RMENU for completeness.
53 | // 2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages.
54 | // 2021-08-02: Inputs: Fixed keyboard modifiers being reported when host window doesn't have focus.
55 | // 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).
56 | // 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).
57 | // 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).
58 | // 2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS).
59 | // 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi).
60 | // 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.
61 | // 2021-01-25: Inputs: Dynamically loading XInput DLL.
62 | // 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed.
63 | // 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs)
64 | // 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions.
65 | // 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT.
66 | // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
67 | // 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter().
68 | // 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent.
69 | // 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages.
70 | // 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
71 | // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
72 | // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
73 | // 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads).
74 | // 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples.
75 | // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
76 | // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling).
77 | // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
78 | // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
79 | // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
80 | // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
81 | // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
82 | // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
83 | // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
84 | // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
85 | // 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set.
86 |
87 | struct ImGui_ImplWin32_Data
88 | {
89 | HWND hWnd;
90 | HWND MouseHwnd;
91 | int MouseTrackedArea; // 0: not tracked, 1: client are, 2: non-client area
92 | int MouseButtonsDown;
93 | INT64 Time;
94 | INT64 TicksPerSecond;
95 | ImGuiMouseCursor LastMouseCursor;
96 |
97 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
98 | bool HasGamepad;
99 | bool WantUpdateHasGamepad;
100 | HMODULE XInputDLL;
101 | PFN_XInputGetCapabilities XInputGetCapabilities;
102 | PFN_XInputGetState XInputGetState;
103 | #endif
104 |
105 | ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); }
106 | };
107 |
108 | // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
109 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
110 | // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
111 | // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
112 | static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData()
113 | {
114 | return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
115 | }
116 |
117 | // Functions
118 | static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc)
119 | {
120 | ImGuiIO& io = ImGui::GetIO();
121 | IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
122 |
123 | INT64 perf_frequency, perf_counter;
124 | if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency))
125 | return false;
126 | if (!::QueryPerformanceCounter((LARGE_INTEGER*)&perf_counter))
127 | return false;
128 |
129 | // Setup backend capabilities flags
130 | ImGui_ImplWin32_Data* bd = IM_NEW(ImGui_ImplWin32_Data)();
131 | io.BackendPlatformUserData = (void*)bd;
132 | io.BackendPlatformName = "imgui_impl_win32";
133 | io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
134 | io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
135 |
136 | bd->hWnd = (HWND)hwnd;
137 | bd->TicksPerSecond = perf_frequency;
138 | bd->Time = perf_counter;
139 | bd->LastMouseCursor = ImGuiMouseCursor_COUNT;
140 |
141 | // Set platform dependent data in viewport
142 | ImGui::GetMainViewport()->PlatformHandleRaw = (void*)hwnd;
143 | IM_UNUSED(platform_has_own_dc); // Used in 'docking' branch
144 |
145 | // Dynamically load XInput library
146 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
147 | bd->WantUpdateHasGamepad = true;
148 | const char* xinput_dll_names[] =
149 | {
150 | "xinput1_4.dll", // Windows 8+
151 | "xinput1_3.dll", // DirectX SDK
152 | "xinput9_1_0.dll", // Windows Vista, Windows 7
153 | "xinput1_2.dll", // DirectX SDK
154 | "xinput1_1.dll" // DirectX SDK
155 | };
156 | for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++)
157 | if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n]))
158 | {
159 | bd->XInputDLL = dll;
160 | bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities");
161 | bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState");
162 | break;
163 | }
164 | #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
165 |
166 | return true;
167 | }
168 |
169 | IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd)
170 | {
171 | return ImGui_ImplWin32_InitEx(hwnd, false);
172 | }
173 |
174 | IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd)
175 | {
176 | // OpenGL needs CS_OWNDC
177 | return ImGui_ImplWin32_InitEx(hwnd, true);
178 | }
179 |
180 | void ImGui_ImplWin32_Shutdown()
181 | {
182 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
183 | IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
184 | ImGuiIO& io = ImGui::GetIO();
185 |
186 | // Unload XInput library
187 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
188 | if (bd->XInputDLL)
189 | ::FreeLibrary(bd->XInputDLL);
190 | #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
191 |
192 | io.BackendPlatformName = nullptr;
193 | io.BackendPlatformUserData = nullptr;
194 | io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad);
195 | IM_DELETE(bd);
196 | }
197 |
198 | static bool ImGui_ImplWin32_UpdateMouseCursor()
199 | {
200 | ImGuiIO& io = ImGui::GetIO();
201 | if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
202 | return false;
203 |
204 | ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
205 | if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
206 | {
207 | // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
208 | ::SetCursor(nullptr);
209 | }
210 | else
211 | {
212 | // Show OS mouse cursor
213 | LPTSTR win32_cursor = IDC_ARROW;
214 | switch (imgui_cursor)
215 | {
216 | case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
217 | case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
218 | case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
219 | case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
220 | case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
221 | case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
222 | case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
223 | case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break;
224 | case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break;
225 | }
226 | ::SetCursor(::LoadCursor(nullptr, win32_cursor));
227 | }
228 | return true;
229 | }
230 |
231 | static bool IsVkDown(int vk)
232 | {
233 | return (::GetKeyState(vk) & 0x8000) != 0;
234 | }
235 |
236 | static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1)
237 | {
238 | ImGuiIO& io = ImGui::GetIO();
239 | io.AddKeyEvent(key, down);
240 | io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code)
241 | IM_UNUSED(native_scancode);
242 | }
243 |
244 | static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds()
245 | {
246 | // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one.
247 | if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT))
248 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT);
249 | if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT))
250 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT);
251 |
252 | // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW).
253 | if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN))
254 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN);
255 | if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN))
256 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN);
257 | }
258 |
259 | static void ImGui_ImplWin32_UpdateKeyModifiers()
260 | {
261 | ImGuiIO& io = ImGui::GetIO();
262 | io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL));
263 | io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT));
264 | io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU));
265 | io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_APPS));
266 | }
267 |
268 | static void ImGui_ImplWin32_UpdateMouseData()
269 | {
270 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
271 | ImGuiIO& io = ImGui::GetIO();
272 | IM_ASSERT(bd->hWnd != 0);
273 |
274 | HWND focused_window = ::GetForegroundWindow();
275 | const bool is_app_focused = (focused_window == bd->hWnd);
276 | if (is_app_focused)
277 | {
278 | // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
279 | if (io.WantSetMousePos)
280 | {
281 | POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
282 | if (::ClientToScreen(bd->hWnd, &pos))
283 | ::SetCursorPos(pos.x, pos.y);
284 | }
285 |
286 | // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured)
287 | // This also fills a short gap when clicking non-client area: WM_NCMOUSELEAVE -> modal OS move -> gap -> WM_NCMOUSEMOVE
288 | if (!io.WantSetMousePos && bd->MouseTrackedArea == 0)
289 | {
290 | POINT pos;
291 | if (::GetCursorPos(&pos) && ::ScreenToClient(bd->hWnd, &pos))
292 | io.AddMousePosEvent((float)pos.x, (float)pos.y);
293 | }
294 | }
295 | }
296 |
297 | // Gamepad navigation mapping
298 | static void ImGui_ImplWin32_UpdateGamepads()
299 | {
300 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
301 | ImGuiIO& io = ImGui::GetIO();
302 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
303 | //if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
304 | // return;
305 |
306 | // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow.
307 | // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE.
308 | if (bd->WantUpdateHasGamepad)
309 | {
310 | XINPUT_CAPABILITIES caps = {};
311 | bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false;
312 | bd->WantUpdateHasGamepad = false;
313 | }
314 |
315 | io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
316 | XINPUT_STATE xinput_state;
317 | XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad;
318 | if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS)
319 | return;
320 | io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
321 |
322 | #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V)
323 | #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); }
324 | #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)); }
325 | MAP_BUTTON(ImGuiKey_GamepadStart, XINPUT_GAMEPAD_START);
326 | MAP_BUTTON(ImGuiKey_GamepadBack, XINPUT_GAMEPAD_BACK);
327 | MAP_BUTTON(ImGuiKey_GamepadFaceLeft, XINPUT_GAMEPAD_X);
328 | MAP_BUTTON(ImGuiKey_GamepadFaceRight, XINPUT_GAMEPAD_B);
329 | MAP_BUTTON(ImGuiKey_GamepadFaceUp, XINPUT_GAMEPAD_Y);
330 | MAP_BUTTON(ImGuiKey_GamepadFaceDown, XINPUT_GAMEPAD_A);
331 | MAP_BUTTON(ImGuiKey_GamepadDpadLeft, XINPUT_GAMEPAD_DPAD_LEFT);
332 | MAP_BUTTON(ImGuiKey_GamepadDpadRight, XINPUT_GAMEPAD_DPAD_RIGHT);
333 | MAP_BUTTON(ImGuiKey_GamepadDpadUp, XINPUT_GAMEPAD_DPAD_UP);
334 | MAP_BUTTON(ImGuiKey_GamepadDpadDown, XINPUT_GAMEPAD_DPAD_DOWN);
335 | MAP_BUTTON(ImGuiKey_GamepadL1, XINPUT_GAMEPAD_LEFT_SHOULDER);
336 | MAP_BUTTON(ImGuiKey_GamepadR1, XINPUT_GAMEPAD_RIGHT_SHOULDER);
337 | MAP_ANALOG(ImGuiKey_GamepadL2, gamepad.bLeftTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255);
338 | MAP_ANALOG(ImGuiKey_GamepadR2, gamepad.bRightTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255);
339 | MAP_BUTTON(ImGuiKey_GamepadL3, XINPUT_GAMEPAD_LEFT_THUMB);
340 | MAP_BUTTON(ImGuiKey_GamepadR3, XINPUT_GAMEPAD_RIGHT_THUMB);
341 | MAP_ANALOG(ImGuiKey_GamepadLStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
342 | MAP_ANALOG(ImGuiKey_GamepadLStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
343 | MAP_ANALOG(ImGuiKey_GamepadLStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
344 | MAP_ANALOG(ImGuiKey_GamepadLStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
345 | MAP_ANALOG(ImGuiKey_GamepadRStickLeft, gamepad.sThumbRX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
346 | MAP_ANALOG(ImGuiKey_GamepadRStickRight, gamepad.sThumbRX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
347 | MAP_ANALOG(ImGuiKey_GamepadRStickUp, gamepad.sThumbRY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
348 | MAP_ANALOG(ImGuiKey_GamepadRStickDown, gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
349 | #undef MAP_BUTTON
350 | #undef MAP_ANALOG
351 | #endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
352 | }
353 |
354 | void ImGui_ImplWin32_NewFrame()
355 | {
356 | ImGuiIO& io = ImGui::GetIO();
357 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
358 | IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplWin32_Init()?");
359 |
360 | // Setup display size (every frame to accommodate for window resizing)
361 | RECT rect = { 0, 0, 0, 0 };
362 | ::GetClientRect(bd->hWnd, &rect);
363 | io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
364 |
365 | // Setup time step
366 | INT64 current_time = 0;
367 | ::QueryPerformanceCounter((LARGE_INTEGER*)¤t_time);
368 | io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond;
369 | bd->Time = current_time;
370 |
371 | // Update OS mouse position
372 | ImGui_ImplWin32_UpdateMouseData();
373 |
374 | // Process workarounds for known Windows key handling issues
375 | ImGui_ImplWin32_ProcessKeyEventsWorkarounds();
376 |
377 | // Update OS mouse cursor with the cursor requested by imgui
378 | ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
379 | if (bd->LastMouseCursor != mouse_cursor)
380 | {
381 | bd->LastMouseCursor = mouse_cursor;
382 | ImGui_ImplWin32_UpdateMouseCursor();
383 | }
384 |
385 | // Update game controllers (if enabled and available)
386 | ImGui_ImplWin32_UpdateGamepads();
387 | }
388 |
389 | // 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)
390 | #define IM_VK_KEYPAD_ENTER (VK_RETURN + 256)
391 |
392 | // Map VK_xxx to ImGuiKey_xxx.
393 | static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam)
394 | {
395 | switch (wParam)
396 | {
397 | case VK_TAB: return ImGuiKey_Tab;
398 | case VK_LEFT: return ImGuiKey_LeftArrow;
399 | case VK_RIGHT: return ImGuiKey_RightArrow;
400 | case VK_UP: return ImGuiKey_UpArrow;
401 | case VK_DOWN: return ImGuiKey_DownArrow;
402 | case VK_PRIOR: return ImGuiKey_PageUp;
403 | case VK_NEXT: return ImGuiKey_PageDown;
404 | case VK_HOME: return ImGuiKey_Home;
405 | case VK_END: return ImGuiKey_End;
406 | case VK_INSERT: return ImGuiKey_Insert;
407 | case VK_DELETE: return ImGuiKey_Delete;
408 | case VK_BACK: return ImGuiKey_Backspace;
409 | case VK_SPACE: return ImGuiKey_Space;
410 | case VK_RETURN: return ImGuiKey_Enter;
411 | case VK_ESCAPE: return ImGuiKey_Escape;
412 | case VK_OEM_7: return ImGuiKey_Apostrophe;
413 | case VK_OEM_COMMA: return ImGuiKey_Comma;
414 | case VK_OEM_MINUS: return ImGuiKey_Minus;
415 | case VK_OEM_PERIOD: return ImGuiKey_Period;
416 | case VK_OEM_2: return ImGuiKey_Slash;
417 | case VK_OEM_1: return ImGuiKey_Semicolon;
418 | case VK_OEM_PLUS: return ImGuiKey_Equal;
419 | case VK_OEM_4: return ImGuiKey_LeftBracket;
420 | case VK_OEM_5: return ImGuiKey_Backslash;
421 | case VK_OEM_6: return ImGuiKey_RightBracket;
422 | case VK_OEM_3: return ImGuiKey_GraveAccent;
423 | case VK_CAPITAL: return ImGuiKey_CapsLock;
424 | case VK_SCROLL: return ImGuiKey_ScrollLock;
425 | case VK_NUMLOCK: return ImGuiKey_NumLock;
426 | case VK_SNAPSHOT: return ImGuiKey_PrintScreen;
427 | case VK_PAUSE: return ImGuiKey_Pause;
428 | case VK_NUMPAD0: return ImGuiKey_Keypad0;
429 | case VK_NUMPAD1: return ImGuiKey_Keypad1;
430 | case VK_NUMPAD2: return ImGuiKey_Keypad2;
431 | case VK_NUMPAD3: return ImGuiKey_Keypad3;
432 | case VK_NUMPAD4: return ImGuiKey_Keypad4;
433 | case VK_NUMPAD5: return ImGuiKey_Keypad5;
434 | case VK_NUMPAD6: return ImGuiKey_Keypad6;
435 | case VK_NUMPAD7: return ImGuiKey_Keypad7;
436 | case VK_NUMPAD8: return ImGuiKey_Keypad8;
437 | case VK_NUMPAD9: return ImGuiKey_Keypad9;
438 | case VK_DECIMAL: return ImGuiKey_KeypadDecimal;
439 | case VK_DIVIDE: return ImGuiKey_KeypadDivide;
440 | case VK_MULTIPLY: return ImGuiKey_KeypadMultiply;
441 | case VK_SUBTRACT: return ImGuiKey_KeypadSubtract;
442 | case VK_ADD: return ImGuiKey_KeypadAdd;
443 | case IM_VK_KEYPAD_ENTER: return ImGuiKey_KeypadEnter;
444 | case VK_LSHIFT: return ImGuiKey_LeftShift;
445 | case VK_LCONTROL: return ImGuiKey_LeftCtrl;
446 | case VK_LMENU: return ImGuiKey_LeftAlt;
447 | case VK_LWIN: return ImGuiKey_LeftSuper;
448 | case VK_RSHIFT: return ImGuiKey_RightShift;
449 | case VK_RCONTROL: return ImGuiKey_RightCtrl;
450 | case VK_RMENU: return ImGuiKey_RightAlt;
451 | case VK_RWIN: return ImGuiKey_RightSuper;
452 | case VK_APPS: return ImGuiKey_Menu;
453 | case '0': return ImGuiKey_0;
454 | case '1': return ImGuiKey_1;
455 | case '2': return ImGuiKey_2;
456 | case '3': return ImGuiKey_3;
457 | case '4': return ImGuiKey_4;
458 | case '5': return ImGuiKey_5;
459 | case '6': return ImGuiKey_6;
460 | case '7': return ImGuiKey_7;
461 | case '8': return ImGuiKey_8;
462 | case '9': return ImGuiKey_9;
463 | case 'A': return ImGuiKey_A;
464 | case 'B': return ImGuiKey_B;
465 | case 'C': return ImGuiKey_C;
466 | case 'D': return ImGuiKey_D;
467 | case 'E': return ImGuiKey_E;
468 | case 'F': return ImGuiKey_F;
469 | case 'G': return ImGuiKey_G;
470 | case 'H': return ImGuiKey_H;
471 | case 'I': return ImGuiKey_I;
472 | case 'J': return ImGuiKey_J;
473 | case 'K': return ImGuiKey_K;
474 | case 'L': return ImGuiKey_L;
475 | case 'M': return ImGuiKey_M;
476 | case 'N': return ImGuiKey_N;
477 | case 'O': return ImGuiKey_O;
478 | case 'P': return ImGuiKey_P;
479 | case 'Q': return ImGuiKey_Q;
480 | case 'R': return ImGuiKey_R;
481 | case 'S': return ImGuiKey_S;
482 | case 'T': return ImGuiKey_T;
483 | case 'U': return ImGuiKey_U;
484 | case 'V': return ImGuiKey_V;
485 | case 'W': return ImGuiKey_W;
486 | case 'X': return ImGuiKey_X;
487 | case 'Y': return ImGuiKey_Y;
488 | case 'Z': return ImGuiKey_Z;
489 | case VK_F1: return ImGuiKey_F1;
490 | case VK_F2: return ImGuiKey_F2;
491 | case VK_F3: return ImGuiKey_F3;
492 | case VK_F4: return ImGuiKey_F4;
493 | case VK_F5: return ImGuiKey_F5;
494 | case VK_F6: return ImGuiKey_F6;
495 | case VK_F7: return ImGuiKey_F7;
496 | case VK_F8: return ImGuiKey_F8;
497 | case VK_F9: return ImGuiKey_F9;
498 | case VK_F10: return ImGuiKey_F10;
499 | case VK_F11: return ImGuiKey_F11;
500 | case VK_F12: return ImGuiKey_F12;
501 | default: return ImGuiKey_None;
502 | }
503 | }
504 |
505 | // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
506 | #ifndef WM_MOUSEHWHEEL
507 | #define WM_MOUSEHWHEEL 0x020E
508 | #endif
509 | #ifndef DBT_DEVNODES_CHANGED
510 | #define DBT_DEVNODES_CHANGED 0x0007
511 | #endif
512 |
513 | // Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
514 | // Call from your application's message handler. Keep calling your message handler unless this function returns TRUE.
515 | // When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
516 | // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
517 | // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
518 | // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
519 | // 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.
520 | // 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.
521 | #if 0
522 | // Copy this line into your .cpp file to forward declare the function.
523 | extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
524 | #endif
525 |
526 | // See https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages
527 | // Prefer to call this at the top of the message handler to avoid the possibility of other Win32 calls interfering with this.
528 | static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
529 | {
530 | LPARAM extra_info = ::GetMessageExtraInfo();
531 | if ((extra_info & 0xFFFFFF80) == 0xFF515700)
532 | return ImGuiMouseSource_Pen;
533 | if ((extra_info & 0xFFFFFF80) == 0xFF515780)
534 | return ImGuiMouseSource_TouchScreen;
535 | return ImGuiMouseSource_Mouse;
536 | }
537 |
538 | IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
539 | {
540 | if (ImGui::GetCurrentContext() == nullptr)
541 | return 0;
542 |
543 | ImGuiIO& io = ImGui::GetIO();
544 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
545 |
546 | switch (msg)
547 | {
548 | case WM_MOUSEMOVE:
549 | case WM_NCMOUSEMOVE:
550 | {
551 | // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events
552 | ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo();
553 | const int area = (msg == WM_MOUSEMOVE) ? 1 : 2;
554 | bd->MouseHwnd = hwnd;
555 | if (bd->MouseTrackedArea != area)
556 | {
557 | TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 };
558 | TRACKMOUSEEVENT tme_track = { sizeof(tme_track), (DWORD)((area == 2) ? (TME_LEAVE | TME_NONCLIENT) : TME_LEAVE), hwnd, 0 };
559 | if (bd->MouseTrackedArea != 0)
560 | ::TrackMouseEvent(&tme_cancel);
561 | ::TrackMouseEvent(&tme_track);
562 | bd->MouseTrackedArea = area;
563 | }
564 | POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) };
565 | if (msg == WM_NCMOUSEMOVE && ::ScreenToClient(hwnd, &mouse_pos) == FALSE) // WM_NCMOUSEMOVE are provided in absolute coordinates.
566 | break;
567 | io.AddMouseSourceEvent(mouse_source);
568 | io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y);
569 | break;
570 | }
571 | case WM_MOUSELEAVE:
572 | case WM_NCMOUSELEAVE:
573 | {
574 | const int area = (msg == WM_MOUSELEAVE) ? 1 : 2;
575 | if (bd->MouseTrackedArea == area)
576 | {
577 | if (bd->MouseHwnd == hwnd)
578 | bd->MouseHwnd = nullptr;
579 | bd->MouseTrackedArea = 0;
580 | io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
581 | }
582 | break;
583 | }
584 | case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
585 | case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
586 | case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
587 | case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK:
588 | {
589 | ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo();
590 | int button = 0;
591 | if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; }
592 | if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; }
593 | if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; }
594 | if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
595 | if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr)
596 | ::SetCapture(hwnd);
597 | bd->MouseButtonsDown |= 1 << button;
598 | io.AddMouseSourceEvent(mouse_source);
599 | io.AddMouseButtonEvent(button, true);
600 | return 0;
601 | }
602 | case WM_LBUTTONUP:
603 | case WM_RBUTTONUP:
604 | case WM_MBUTTONUP:
605 | case WM_XBUTTONUP:
606 | {
607 | ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo();
608 | int button = 0;
609 | if (msg == WM_LBUTTONUP) { button = 0; }
610 | if (msg == WM_RBUTTONUP) { button = 1; }
611 | if (msg == WM_MBUTTONUP) { button = 2; }
612 | if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
613 | bd->MouseButtonsDown &= ~(1 << button);
614 | if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd)
615 | ::ReleaseCapture();
616 | io.AddMouseSourceEvent(mouse_source);
617 | io.AddMouseButtonEvent(button, false);
618 | return 0;
619 | }
620 | case WM_MOUSEWHEEL:
621 | io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA);
622 | return 0;
623 | case WM_MOUSEHWHEEL:
624 | io.AddMouseWheelEvent(-(float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f);
625 | return 0;
626 | case WM_KEYDOWN:
627 | case WM_KEYUP:
628 | case WM_SYSKEYDOWN:
629 | case WM_SYSKEYUP:
630 | {
631 | const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN);
632 | if (wParam < 256)
633 | {
634 | // Submit modifiers
635 | ImGui_ImplWin32_UpdateKeyModifiers();
636 |
637 | // Obtain virtual key code
638 | // (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.)
639 | int vk = (int)wParam;
640 | if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED))
641 | vk = IM_VK_KEYPAD_ENTER;
642 |
643 | // Submit key event
644 | const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk);
645 | const int scancode = (int)LOBYTE(HIWORD(lParam));
646 | if (key != ImGuiKey_None)
647 | ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode);
648 |
649 | // Submit individual left/right modifier events
650 | if (vk == VK_SHIFT)
651 | {
652 | // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds()
653 | if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); }
654 | if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); }
655 | }
656 | else if (vk == VK_CONTROL)
657 | {
658 | if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); }
659 | if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); }
660 | }
661 | else if (vk == VK_MENU)
662 | {
663 | if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); }
664 | if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); }
665 | }
666 | }
667 | return 0;
668 | }
669 | case WM_SETFOCUS:
670 | case WM_KILLFOCUS:
671 | io.AddFocusEvent(msg == WM_SETFOCUS);
672 | return 0;
673 | case WM_CHAR:
674 | if (::IsWindowUnicode(hwnd))
675 | {
676 | // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
677 | if (wParam > 0 && wParam < 0x10000)
678 | io.AddInputCharacterUTF16((unsigned short)wParam);
679 | }
680 | else
681 | {
682 | wchar_t wch = 0;
683 | ::MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1);
684 | io.AddInputCharacter(wch);
685 | }
686 | return 0;
687 | case WM_SETCURSOR:
688 | // This is required to restore cursor when transitioning from e.g resize borders to client area.
689 | if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
690 | return 1;
691 | return 0;
692 | case WM_DEVICECHANGE:
693 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
694 | if ((UINT)wParam == DBT_DEVNODES_CHANGED)
695 | bd->WantUpdateHasGamepad = true;
696 | #endif
697 | return 0;
698 | }
699 | return 0;
700 | }
701 |
702 |
703 | //--------------------------------------------------------------------------------------------------------
704 | // DPI-related helpers (optional)
705 | //--------------------------------------------------------------------------------------------------------
706 | // - Use to enable DPI awareness without having to create an application manifest.
707 | // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
708 | // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
709 | // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
710 | // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
711 | //---------------------------------------------------------------------------------------------------------
712 | // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable.
713 | // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
714 | // If you are trying to implement your own backend for your own engine, you may ignore that noise.
715 | //---------------------------------------------------------------------------------------------------------
716 |
717 | // Perform our own check with RtlVerifyVersionInfo() instead of using functions from as they
718 | // require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200
719 | static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD)
720 | {
721 | typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG);
722 | static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr;
723 | if (RtlVerifyVersionInfoFn == nullptr)
724 | if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll"))
725 | RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo");
726 | if (RtlVerifyVersionInfoFn == nullptr)
727 | return FALSE;
728 |
729 | RTL_OSVERSIONINFOEXW versionInfo = { };
730 | ULONGLONG conditionMask = 0;
731 | versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
732 | versionInfo.dwMajorVersion = major;
733 | versionInfo.dwMinorVersion = minor;
734 | VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
735 | VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
736 | return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE;
737 | }
738 |
739 | #define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA
740 | #define _IsWindows8OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8
741 | #define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE
742 | #define _IsWindows10OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10
743 |
744 | #ifndef DPI_ENUMS_DECLARED
745 | typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
746 | typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
747 | #endif
748 | #ifndef _DPI_AWARENESS_CONTEXTS_
749 | DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
750 | #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3
751 | #endif
752 | #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
753 | #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
754 | #endif
755 | typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+
756 | typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+
757 | typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update)
758 |
759 | // Helper function to enable DPI awareness without setting up a manifest
760 | void ImGui_ImplWin32_EnableDpiAwareness()
761 | {
762 | if (_IsWindows10OrGreater())
763 | {
764 | static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
765 | if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
766 | {
767 | SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
768 | return;
769 | }
770 | }
771 | if (_IsWindows8Point1OrGreater())
772 | {
773 | static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
774 | if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
775 | {
776 | SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
777 | return;
778 | }
779 | }
780 | #if _WIN32_WINNT >= 0x0600
781 | ::SetProcessDPIAware();
782 | #endif
783 | }
784 |
785 | #if defined(_MSC_VER) && !defined(NOGDI)
786 | #pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32'
787 | #endif
788 |
789 | float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
790 | {
791 | UINT xdpi = 96, ydpi = 96;
792 | if (_IsWindows8Point1OrGreater())
793 | {
794 | static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
795 | static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr;
796 | if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr)
797 | GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor");
798 | if (GetDpiForMonitorFn != nullptr)
799 | {
800 | GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
801 | IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
802 | return xdpi / 96.0f;
803 | }
804 | }
805 | #ifndef NOGDI
806 | const HDC dc = ::GetDC(nullptr);
807 | xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
808 | ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
809 | IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
810 | ::ReleaseDC(nullptr, dc);
811 | #endif
812 | return xdpi / 96.0f;
813 | }
814 |
815 | float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
816 | {
817 | HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
818 | return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
819 | }
820 |
821 | //---------------------------------------------------------------------------------------------------------
822 | // Transparency related helpers (optional)
823 | //--------------------------------------------------------------------------------------------------------
824 |
825 | #if defined(_MSC_VER)
826 | #pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi'
827 | #endif
828 |
829 | // [experimental]
830 | // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c
831 | // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW)
832 | void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd)
833 | {
834 | if (!_IsWindowsVistaOrGreater())
835 | return;
836 |
837 | BOOL composition;
838 | if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition)
839 | return;
840 |
841 | BOOL opaque;
842 | DWORD color;
843 | if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque))
844 | {
845 | HRGN region = ::CreateRectRgn(0, 0, -1, -1);
846 | DWM_BLURBEHIND bb = {};
847 | bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
848 | bb.hRgnBlur = region;
849 | bb.fEnable = TRUE;
850 | ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
851 | ::DeleteObject(region);
852 | }
853 | else
854 | {
855 | DWM_BLURBEHIND bb = {};
856 | bb.dwFlags = DWM_BB_ENABLE;
857 | ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
858 | }
859 | }
860 |
861 | //---------------------------------------------------------------------------------------------------------
862 |
--------------------------------------------------------------------------------