From eaee727d9ece1b87e68fd30628e6bfff29ef5c2e Mon Sep 17 00:00:00 2001 From: Andrej Redeky Date: Wed, 11 Dec 2024 19:18:24 +0100 Subject: [PATCH] Revert "Merge pull request #970 from dragonzkiller/master" This reverts commit 4aea40082ef6a59dc37a92e2cd9038c4dbf1936f, reversing changes made to ae1cd01ae32adf8890702f45406a8b15f87d283f. --- src/Utils.cpp | 3 +- src/d3d12/D3D12_Functions.cpp | 10 +- src/imgui_impl/dx12.cpp | 789 ++++----------- src/imgui_impl/dx12.h | 45 +- src/imgui_impl/imgui_user_config.h | 2 - src/imgui_impl/win32.cpp | 1422 ++++------------------------ src/imgui_impl/win32.h | 60 +- src/overlay/widgets/Bindings.cpp | 2 +- src/overlay/widgets/Settings.cpp | 17 +- src/sol_imgui/README.md | 71 +- src/sol_imgui/sol_imgui.h | 221 +---- xmake.lua | 4 +- 12 files changed, 533 insertions(+), 2113 deletions(-) diff --git a/src/Utils.cpp b/src/Utils.cpp index 32646cad..2e33efc7 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -177,8 +177,7 @@ bool IsLuaCData(const sol::object& acpObject) float GetAlignedItemWidth(const int64_t acItemsCount) { - return (ImGui::GetContentRegionAvail().x - static_cast(acItemsCount - 1) * ImGui::GetStyle().ItemSpacing.x) / - static_cast(acItemsCount); + return (ImGui::GetWindowContentRegionWidth() - static_cast(acItemsCount - 1) * ImGui::GetStyle().ItemSpacing.x) / static_cast(acItemsCount); } float GetCenteredOffsetForText(const char* acpText) diff --git a/src/d3d12/D3D12_Functions.cpp b/src/d3d12/D3D12_Functions.cpp index ca23e2d6..fe3908d0 100644 --- a/src/d3d12/D3D12_Functions.cpp +++ b/src/d3d12/D3D12_Functions.cpp @@ -19,6 +19,8 @@ bool D3D12::ResetState(const bool acClearDownlevelBackbuffers, const bool acDest { for (auto i = 0; i < drawData.CmdListsCount; ++i) IM_DELETE(drawData.CmdLists[i]); + delete[] drawData.CmdLists; + drawData.CmdLists = nullptr; drawData.Clear(); } @@ -495,16 +497,16 @@ void D3D12::PrepareUpdate() for (auto i = 0; i < drawData.CmdListsCount; ++i) IM_DELETE(drawData.CmdLists[i]); + delete[] drawData.CmdLists; + drawData.CmdLists = nullptr; drawData.Clear(); drawData = *ImGui::GetDrawData(); - ImVector copiedDrawLists; - copiedDrawLists.resize(drawData.CmdListsCount); - + auto** copiedDrawLists = new ImDrawList*[drawData.CmdListsCount]; for (auto i = 0; i < drawData.CmdListsCount; ++i) copiedDrawLists[i] = drawData.CmdLists[i]->CloneOutput(); - drawData.CmdLists = std::move(copiedDrawLists); + drawData.CmdLists = copiedDrawLists; std::swap(m_imguiDrawDataBuffers[1], m_imguiDrawDataBuffers[2]); } diff --git a/src/imgui_impl/dx12.cpp b/src/imgui_impl/dx12.cpp index e9deb1c1..394196c6 100644 --- a/src/imgui_impl/dx12.cpp +++ b/src/imgui_impl/dx12.cpp @@ -2,193 +2,86 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. -// FIXME: The transition from removing a viewport and moving the window in an existing hosted viewport tends to flicker. +// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about +// ImTextureID! [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. -// To build this on 32-bit systems: -// - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the -// 'example_win32_direct12/example_win32_direct12.vcxproj' project file) -// - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID -// ImU64' and as many other options as you like. -// - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) -// - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in the example_win32_direct12/build_win32.bat file) - -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. -// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// Learn about Dear ImGui: -// - FAQ https://dearimgui.com/faq -// - Getting Started https://dearimgui.com/getting-started -// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). -// - Introduction, links and more at the top of imgui.cpp +// This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your +// imconfig.h file. + +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. -// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. -// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). -// 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) -// 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer. -// 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically. -// 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning. -// 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID. -// 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function. -// 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. -// 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. -// 2019-03-29: Misc: Various minor tidying up. -// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). -// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer +// warning. 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID. +// 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() +// function. 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable +// ImGuiBackendFlags_RendererHasVtxOffset flag. 2019-04-30: DirectX12: Added support for special +// ImDrawCallback_ResetRenderState callback to reset render state. 2019-03-29: Misc: Various minor tidying up. +// 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using +// D3DCompile(). 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData(). // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example. -// 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport). -// 2018-02-22: Merged into master with all Win32 code synchronized to other examples. +// 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping +// rectangle (to ease support for future multi-viewport). 2018-02-22: Merged into master with all Win32 code +// synchronized to other examples. #include -#include "imgui.h" -#ifndef IMGUI_DISABLE #include "dx12.h" // DirectX -#include -#include -#include #ifdef _MSC_VER #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. #endif // DirectX data -struct ImGui_ImplDX12_Data -{ - ID3D12Device* pd3dDevice; - ID3D12RootSignature* pRootSignature; - ID3D12PipelineState* pPipelineState; - DXGI_FORMAT RTVFormat; - ID3D12Resource* pFontTextureResource; - D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle; - D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle; - ID3D12DescriptorHeap* pd3dSrvDescHeap; - UINT numFramesInFlight; - - ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); } -}; - -// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts -// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. -static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData() -{ - return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; -} - -// Buffers used during the rendering of a frame -struct ImGui_ImplDX12_RenderBuffers +static ID3D12Device* g_pd3dDevice = NULL; +static ID3D12RootSignature* g_pRootSignature = NULL; +static ID3D12PipelineState* g_pPipelineState = NULL; +static DXGI_FORMAT g_RTVFormat = DXGI_FORMAT_UNKNOWN; +static ID3D12Resource* g_pFontTextureResource = NULL; +static D3D12_CPU_DESCRIPTOR_HANDLE g_hFontSrvCpuDescHandle = {}; +static D3D12_GPU_DESCRIPTOR_HANDLE g_hFontSrvGpuDescHandle = {}; + +struct FrameResources { ID3D12Resource* IndexBuffer; ID3D12Resource* VertexBuffer; int IndexBufferSize; int VertexBufferSize; }; +static FrameResources* g_pFrameResources = NULL; +static UINT g_numFramesInFlight = 0; +static UINT g_frameIndex = UINT_MAX; -// Buffers used for secondary viewports created by the multi-viewports systems -struct ImGui_ImplDX12_FrameContext +template static void SafeRelease(T*& apRes) { - ID3D12CommandAllocator* CommandAllocator; - ID3D12Resource* RenderTarget; - D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors; -}; - -// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. -// Main viewport created by application will only use the Resources field. -// Secondary viewports created by this backend will use all the fields (including Window fields), -struct ImGui_ImplDX12_ViewportData -{ - // Window - ID3D12CommandQueue* CommandQueue; - ID3D12GraphicsCommandList* CommandList; - ID3D12DescriptorHeap* RtvDescHeap; - IDXGISwapChain3* SwapChain; - ID3D12Fence* Fence; - UINT64 FenceSignaledValue; - HANDLE FenceEvent; - UINT NumFramesInFlight; - ImGui_ImplDX12_FrameContext* FrameCtx; - - // Render buffers - UINT FrameIndex; - ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers; - - ImGui_ImplDX12_ViewportData(UINT num_frames_in_flight) - { - CommandQueue = nullptr; - CommandList = nullptr; - RtvDescHeap = nullptr; - SwapChain = nullptr; - Fence = nullptr; - FenceSignaledValue = 0; - FenceEvent = nullptr; - NumFramesInFlight = num_frames_in_flight; - FrameCtx = new ImGui_ImplDX12_FrameContext[NumFramesInFlight]; - FrameIndex = UINT_MAX; - FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[NumFramesInFlight]; - - for (UINT i = 0; i < NumFramesInFlight; ++i) - { - FrameCtx[i].CommandAllocator = nullptr; - FrameCtx[i].RenderTarget = nullptr; - - // Create buffers with a default size (they will later be grown as needed) - FrameRenderBuffers[i].IndexBuffer = nullptr; - FrameRenderBuffers[i].VertexBuffer = nullptr; - FrameRenderBuffers[i].VertexBufferSize = 5000; - FrameRenderBuffers[i].IndexBufferSize = 10000; - } - } - ~ImGui_ImplDX12_ViewportData() - { - IM_ASSERT(CommandQueue == nullptr && CommandList == nullptr); - IM_ASSERT(RtvDescHeap == nullptr); - IM_ASSERT(SwapChain == nullptr); - IM_ASSERT(Fence == nullptr); - IM_ASSERT(FenceEvent == nullptr); - - for (UINT i = 0; i < NumFramesInFlight; ++i) - { - IM_ASSERT(FrameCtx[i].CommandAllocator == nullptr && FrameCtx[i].RenderTarget == nullptr); - IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == nullptr && FrameRenderBuffers[i].VertexBuffer == nullptr); - } - - delete[] FrameCtx; - FrameCtx = nullptr; - delete[] FrameRenderBuffers; - FrameRenderBuffers = nullptr; - } -}; + if (apRes) + apRes->Release(); + apRes = NULL; +} -struct VERTEX_CONSTANT_BUFFER_DX12 +struct VERTEX_CONSTANT_BUFFER { float mvp[4][4]; }; -// Forward Declarations -static void ImGui_ImplDX12_InitPlatformInterface(); -static void ImGui_ImplDX12_ShutdownPlatformInterface(); - -// Functions -static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr) +static void ImGui_ImplDX12_SetupRenderState(ImDrawData* apDrawData, ID3D12GraphicsCommandList* apCommandLists, FrameResources* apFrameResource) { - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - // Setup orthographic projection matrix into our constant buffer - // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). - VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer; + // Our visible imgui space lies from draw_data->DisplayPos (top left) to + // draw_data->DisplayPos+data_data->DisplaySize (bottom right). + VERTEX_CONSTANT_BUFFER vertex_constant_buffer; { - float L = draw_data->DisplayPos.x; - float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; - float T = draw_data->DisplayPos.y; - float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + float L = apDrawData->DisplayPos.x; + float R = apDrawData->DisplayPos.x + apDrawData->DisplaySize.x; + float T = apDrawData->DisplayPos.y; + float B = apDrawData->DisplayPos.y + apDrawData->DisplaySize.y; float mvp[4][4] = { {2.0f / (R - L), 0.0f, 0.0f, 0.0f}, {0.0f, 2.0f / (T - B), 0.0f, 0.0f}, @@ -201,62 +94,55 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic // Setup viewport D3D12_VIEWPORT vp; memset(&vp, 0, sizeof(D3D12_VIEWPORT)); - vp.Width = draw_data->DisplaySize.x; - vp.Height = draw_data->DisplaySize.y; + vp.Width = apDrawData->DisplaySize.x; + vp.Height = apDrawData->DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0.0f; - ctx->RSSetViewports(1, &vp); + apCommandLists->RSSetViewports(1, &vp); // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; D3D12_VERTEX_BUFFER_VIEW vbv; memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW)); - vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset; - vbv.SizeInBytes = fr->VertexBufferSize * stride; + vbv.BufferLocation = apFrameResource->VertexBuffer->GetGPUVirtualAddress() + offset; + vbv.SizeInBytes = apFrameResource->VertexBufferSize * stride; vbv.StrideInBytes = stride; - ctx->IASetVertexBuffers(0, 1, &vbv); + apCommandLists->IASetVertexBuffers(0, 1, &vbv); D3D12_INDEX_BUFFER_VIEW ibv; memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW)); - ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress(); - ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx); + ibv.BufferLocation = apFrameResource->IndexBuffer->GetGPUVirtualAddress(); + ibv.SizeInBytes = apFrameResource->IndexBufferSize * sizeof(ImDrawIdx); ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT; - ctx->IASetIndexBuffer(&ibv); - ctx->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - ctx->SetPipelineState(bd->pPipelineState); - ctx->SetGraphicsRootSignature(bd->pRootSignature); - ctx->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); + apCommandLists->IASetIndexBuffer(&ibv); + apCommandLists->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + apCommandLists->SetPipelineState(g_pPipelineState); + apCommandLists->SetGraphicsRootSignature(g_pRootSignature); + apCommandLists->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0); // Setup blend factor const float blend_factor[4] = {0.f, 0.f, 0.f, 0.f}; - ctx->OMSetBlendFactor(blend_factor); -} - -template static inline void SafeRelease(T*& res) -{ - if (res) - res->Release(); - res = nullptr; + apCommandLists->OMSetBlendFactor(blend_factor); } // Render function -void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx) +void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommandList* apCommandLists) { // Avoid rendering when minimized - if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) + if (apDrawData->DisplaySize.x <= 0.0f || apDrawData->DisplaySize.y <= 0.0f) return; - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)draw_data->OwnerViewport->RendererUserData; - vd->FrameIndex++; - ImGui_ImplDX12_RenderBuffers* fr = &vd->FrameRenderBuffers[vd->FrameIndex % bd->numFramesInFlight]; + // FIXME: I'm assuming that this only gets called once per frame! + // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. + g_frameIndex = g_frameIndex + 1; + FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight]; // Create and grow vertex/index buffers if needed - if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount) + if (fr->VertexBuffer == NULL || fr->VertexBufferSize < apDrawData->TotalVtxCount) { SafeRelease(fr->VertexBuffer); - fr->VertexBufferSize = draw_data->TotalVtxCount + 5000; + fr->VertexBufferSize = apDrawData->TotalVtxCount + 5000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; @@ -273,13 +159,13 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) + if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) return; } - if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount) + if (fr->IndexBuffer == NULL || fr->IndexBufferSize < apDrawData->TotalIdxCount) { SafeRelease(fr->IndexBuffer); - fr->IndexBufferSize = draw_data->TotalIdxCount + 10000; + fr->IndexBufferSize = apDrawData->TotalIdxCount + 10000; D3D12_HEAP_PROPERTIES props; memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES)); props.Type = D3D12_HEAP_TYPE_UPLOAD; @@ -296,7 +182,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) + if (g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) return; } @@ -310,9 +196,9 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource; - for (int n = 0; n < draw_data->CmdListsCount; n++) + for (int n = 0; n < apDrawData->CmdListsCount; n++) { - const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawList* cmd_list = apDrawData->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; @@ -322,43 +208,40 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL fr->IndexBuffer->Unmap(0, &range); // Setup desired DX state - ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); + ImGui_ImplDX12_SetupRenderState(apDrawData, apCommandLists, fr); // Render command lists // (Because we merged all buffers into a single one, we maintain our own offset into them) int global_vtx_offset = 0; int global_idx_offset = 0; - ImVec2 clip_off = draw_data->DisplayPos; - for (int n = 0; n < draw_data->CmdListsCount; n++) + ImVec2 clip_off = apDrawData->DisplayPos; + for (int n = 0; n < apDrawData->CmdListsCount; n++) { - const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawList* cmd_list = apDrawData->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != nullptr) + if (pcmd->UserCallback != NULL) { // User callback, registered via ImDrawList::AddCallback() - // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer + // to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - ImGui_ImplDX12_SetupRenderState(draw_data, ctx, fr); + ImGui_ImplDX12_SetupRenderState(apDrawData, apCommandLists, fr); else pcmd->UserCallback(cmd_list, pcmd); } else { - // Project scissor/clipping rectangles into framebuffer space - ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); - ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); - if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) - continue; - - // Apply Scissor/clipping rectangle, Bind texture, Draw - const D3D12_RECT r = {(LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y}; - D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {}; - texture_handle.ptr = (UINT64)pcmd->GetTexID(); - ctx->SetGraphicsRootDescriptorTable(1, texture_handle); - ctx->RSSetScissorRects(1, &r); - ctx->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); + // Apply Scissor, Bind texture, Draw + const D3D12_RECT r = { + (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y)}; + if (r.right > r.left && r.bottom > r.top) + { + apCommandLists->SetGraphicsRootDescriptorTable(1, *(D3D12_GPU_DESCRIPTOR_HANDLE*)&pcmd->TextureId); + apCommandLists->RSSetScissorRects(1, &r); + apCommandLists->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); + } } } global_idx_offset += cmd_list->IdxBuffer.Size; @@ -370,7 +253,6 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); @@ -397,8 +279,8 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - ID3D12Resource* pTexture = nullptr; - bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture)); + ID3D12Resource* pTexture = NULL; + g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture)); UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); UINT uploadSize = height * uploadPitch; @@ -418,11 +300,11 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - ID3D12Resource* uploadBuffer = nullptr; - HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); + ID3D12Resource* uploadBuffer = NULL; + HRESULT hr = g_pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer)); IM_ASSERT(SUCCEEDED(hr)); - void* mapped = nullptr; + void* mapped = NULL; D3D12_RANGE range = {0, uploadSize}; hr = uploadBuffer->Map(0, &range, &mapped); IM_ASSERT(SUCCEEDED(hr)); @@ -452,31 +334,22 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - ID3D12Fence* fence = nullptr; - hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + ID3D12Fence* fence = NULL; + hr = g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); IM_ASSERT(SUCCEEDED(hr)); HANDLE event = CreateEvent(0, 0, 0, 0); - IM_ASSERT(event != nullptr); - - D3D12_COMMAND_QUEUE_DESC queueDesc = {}; - queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; - queueDesc.NodeMask = 1; + IM_ASSERT(event != NULL); - //ID3D12CommandQueue* cmdQueue = nullptr; - //hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue)); - //IM_ASSERT(SUCCEEDED(hr)); - - ID3D12CommandAllocator* cmdAlloc = nullptr; - hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); + ID3D12CommandAllocator* cmdAlloc = NULL; + hr = g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); IM_ASSERT(SUCCEEDED(hr)); - ID3D12GraphicsCommandList* cmdList = nullptr; - hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList)); + ID3D12GraphicsCommandList* cmdList = NULL; + hr = g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList)); IM_ASSERT(SUCCEEDED(hr)); - cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr); + cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL); cmdList->ResourceBarrier(1, &barrier); hr = cmdList->Close(); @@ -491,7 +364,6 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue cmdList->Release(); cmdAlloc->Release(); - //cmdQueue->Release(); CloseHandle(event); fence->Release(); uploadBuffer->Release(); @@ -504,30 +376,21 @@ static void ImGui_ImplDX12_CreateFontsTexture(ID3D12CommandQueue* apCommandQueue srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, bd->hFontSrvCpuDescHandle); - SafeRelease(bd->pFontTextureResource); - bd->pFontTextureResource = pTexture; + g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, g_hFontSrvCpuDescHandle); + SafeRelease(g_pFontTextureResource); + g_pFontTextureResource = pTexture; } // Store our identifier - // READ THIS IF THE STATIC_ASSERT() TRIGGERS: - // - Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. - // - This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. - // [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in the - // 'example_win32_direct12/example_win32_direct12.vcxproj' project file) [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add - // 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. [Solution 3] IDE/msbuild: edit - // imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe - // command-line (this is what we do in the example_win32_direct12/build_win32.bat file) - static_assert(sizeof(ImTextureID) >= sizeof(bd->hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); - io.Fonts->SetTexID((ImTextureID)bd->hFontSrvGpuDescHandle.ptr); + static_assert(sizeof(ImTextureID) >= sizeof(g_hFontSrvGpuDescHandle.ptr), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); + io.Fonts->TexID = (ImTextureID)g_hFontSrvGpuDescHandle.ptr; } bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) { - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - if (!bd || !bd->pd3dDevice) + if (!g_pd3dDevice) return false; - if (bd->pPipelineState) + if (g_pPipelineState) ImGui_ImplDX12_InvalidateDeviceObjects(); // Create the root signature @@ -552,8 +415,6 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) param[1].DescriptorTable.pDescriptorRanges = &descRange; param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest - // sampling. D3D12_STATIC_SAMPLER_DESC staticSampler = {}; staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_WRAP; @@ -577,55 +438,61 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS | D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS; - // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that. - static HINSTANCE d3d12_dll = ::GetModuleHandle(_T("d3d12.dll")); - if (d3d12_dll == nullptr) + static HINSTANCE d3d12_dll = ::GetModuleHandle(TEXT("d3d12.dll")); + if (d3d12_dll == NULL) { - // Attempt to load d3d12.dll from local directories. This will only succeed if - // (1) the current OS is Windows 7, and - // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories. - // See https://github.com/ocornut/imgui/pull/3696 for details. - const TCHAR* localD3d12Paths[] = { - _T(".\\d3d12.dll"), _T(".\\d3d12on7\\d3d12.dll"), _T(".\\12on7\\d3d12.dll")}; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample - for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++) - if ((d3d12_dll = ::LoadLibrary(localD3d12Paths[i])) != nullptr) + // Attempt to load d3d12.dll from local directories in decreasing order of likelihood. This will only + // succeed if (1) the current OS is Windows 7, and (2) there exists a version of d3d12.dll for Windows 7 + // (D3D12On7) in one of the following directories. + static const TCHAR* localD3d12Paths[] = { + TEXT(".\\d3d12on7\\d3d12.dll"), // used by some games + TEXT(".\\12on7\\d3d12.dll") // used in the Microsoft D3D12On7 sample + }; + + for (unsigned int i = 0; i < _countof(localD3d12Paths); i++) + { + d3d12_dll = LoadLibrary(localD3d12Paths[i]); + if (d3d12_dll != NULL) break; + } - // If failed, we are on Windows >= 10. - if (d3d12_dll == nullptr) - d3d12_dll = ::LoadLibrary(_T("d3d12.dll")); + // If failed, we should be on Windows 10. + if (d3d12_dll == NULL) + d3d12_dll = ::LoadLibrary(TEXT("d3d12.dll")); - if (d3d12_dll == nullptr) + if (d3d12_dll == NULL) return false; } PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); - if (D3D12SerializeRootSignatureFn == nullptr) + if (D3D12SerializeRootSignatureFn == NULL) return false; - ID3DBlob* blob = nullptr; - if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK) + ID3DBlob* blob = NULL; + if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK) return false; - bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature)); + g_pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature)); blob->Release(); } - // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) - // If you would like to use this DX12 sample code but remove this dependency you can: - // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution] - // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. + // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of + // d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) If you would like to use this DX12 sample code but remove this + // dependency you can: + // 1) compile once, save the compiled shader blobs into a file or source code and pass them to + // CreateVertexShader()/CreatePixelShader() [preferred solution] 2) use code to detect any version of the DLL and + // grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc; memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC)); psoDesc.NodeMask = 1; psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - psoDesc.pRootSignature = bd->pRootSignature; + psoDesc.pRootSignature = g_pRootSignature; psoDesc.SampleMask = UINT_MAX; psoDesc.NumRenderTargets = 1; - psoDesc.RTVFormats[0] = bd->RTVFormat; + psoDesc.RTVFormats[0] = g_RTVFormat; psoDesc.SampleDesc.Count = 1; psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; @@ -661,15 +528,16 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) return output;\ }"; - if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr))) - return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_5_0", 0, 0, &vertexShaderBlob, NULL))) + return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const + // char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! psoDesc.VS = {vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize()}; // Create the input layout static D3D12_INPUT_ELEMENT_DESC local_layout[] = { - {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, - {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, - {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, }; psoDesc.InputLayout = {local_layout, 3}; } @@ -691,10 +559,11 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) return out_col; \ }"; - if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr))) + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &pixelShaderBlob, NULL))) { vertexShaderBlob->Release(); - return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const + // char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! } psoDesc.PS = {pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize()}; } @@ -707,8 +576,8 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; - desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; - desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_ZERO; desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; } @@ -741,7 +610,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) desc.BackFace = desc.FrontFace; } - HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState)); + HRESULT result_pipeline_state = g_pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPipelineState)); vertexShaderBlob->Release(); pixelShaderBlob->Release(); if (result_pipeline_state != S_OK) @@ -752,334 +621,72 @@ bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue) return true; } -static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers) -{ - SafeRelease(render_buffers->IndexBuffer); - SafeRelease(render_buffers->VertexBuffer); - render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0; -} - void ImGui_ImplDX12_InvalidateDeviceObjects() { - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - if (!bd || !bd->pd3dDevice) + if (!g_pd3dDevice) return; + SafeRelease(g_pRootSignature); + SafeRelease(g_pPipelineState); + SafeRelease(g_pFontTextureResource); + ImGuiIO& io = ImGui::GetIO(); - SafeRelease(bd->pRootSignature); - SafeRelease(bd->pPipelineState); - SafeRelease(bd->pFontTextureResource); - io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. + io.Fonts->TexID = NULL; // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. + + for (UINT i = 0; i < g_numFramesInFlight; i++) + { + FrameResources* fr = &g_pFrameResources[i]; + SafeRelease(fr->IndexBuffer); + SafeRelease(fr->VertexBuffer); + } } bool ImGui_ImplDX12_Init( - ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, - D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) + ID3D12Device* apDevice, int aNumFramesInFlight, DXGI_FORMAT aRTVFormat, ID3D12DescriptorHeap* apSRVHeapDesc, D3D12_CPU_DESCRIPTOR_HANDLE aFontSRVDescCPU, + D3D12_GPU_DESCRIPTOR_HANDLE aFontSRVDescGPU) { - ImGuiIO& io = ImGui::GetIO(); - IMGUI_CHECKVERSION(); - IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); - // Setup backend capabilities flags - ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)(); - io.BackendRendererUserData = (void*)bd; + ImGuiIO& io = ImGui::GetIO(); io.BackendRendererName = "imgui_impl_dx12"; - io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. - io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional) - if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) - ImGui_ImplDX12_InitPlatformInterface(); - - bd->pd3dDevice = device; - bd->RTVFormat = rtv_format; - bd->hFontSrvCpuDescHandle = font_srv_cpu_desc_handle; - bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle; - bd->numFramesInFlight = num_frames_in_flight; - bd->pd3dSrvDescHeap = cbv_srv_heap; - - // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport, - // Since this is created and managed by the application, we will only use the ->Resources[] fields. - ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight); + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing + // for large meshes. + + g_pd3dDevice = apDevice; + g_RTVFormat = aRTVFormat; + g_hFontSrvCpuDescHandle = aFontSRVDescCPU; + g_hFontSrvGpuDescHandle = aFontSRVDescGPU; + g_pFrameResources = new FrameResources[aNumFramesInFlight]; + g_numFramesInFlight = aNumFramesInFlight; + g_frameIndex = UINT_MAX; + IM_UNUSED(apSRVHeapDesc); // Unused in master branch (will be used by multi-viewports) + + // Create buffers with a default size (they will later be grown as needed) + for (int i = 0; i < aNumFramesInFlight; i++) + { + FrameResources* fr = &g_pFrameResources[i]; + fr->IndexBuffer = NULL; + fr->VertexBuffer = NULL; + fr->IndexBufferSize = 10000; + fr->VertexBufferSize = 5000; + } return true; } void ImGui_ImplDX12_Shutdown() { - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); - ImGuiIO& io = ImGui::GetIO(); - - // Manually delete main viewport render resources in-case we haven't initialized for viewports - ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)main_viewport->RendererUserData) - { - // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[] - for (UINT i = 0; i < bd->numFramesInFlight; i++) - ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]); - IM_DELETE(vd); - main_viewport->RendererUserData = nullptr; - } - - // Clean up windows and device objects - ImGui_ImplDX12_ShutdownPlatformInterface(); ImGui_ImplDX12_InvalidateDeviceObjects(); - - io.BackendRendererName = nullptr; - io.BackendRendererUserData = nullptr; - io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports); - IM_DELETE(bd); + delete[] g_pFrameResources; + g_pFrameResources = NULL; + g_pd3dDevice = NULL; + g_hFontSrvCpuDescHandle.ptr = 0; + g_hFontSrvGpuDescHandle.ptr = 0; + g_numFramesInFlight = 0; + g_frameIndex = UINT_MAX; } void ImGui_ImplDX12_NewFrame(ID3D12CommandQueue* apCommandQueue) { - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?"); - - if (!bd->pPipelineState || !ImGui::GetIO().Fonts->IsBuilt()) + if (!g_pPipelineState || !ImGui::GetIO().Fonts->IsBuilt()) ImGui_ImplDX12_CreateDeviceObjects(apCommandQueue); } - -//-------------------------------------------------------------------------------------------------------- -// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT -// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. -// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. -//-------------------------------------------------------------------------------------------------------- - -static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport) -{ - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - ImGui_ImplDX12_ViewportData* vd = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight); - viewport->RendererUserData = vd; - - // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*). - // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND. - HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle; - IM_ASSERT(hwnd != 0); - - vd->FrameIndex = UINT_MAX; - - // Create command queue. - D3D12_COMMAND_QUEUE_DESC queue_desc = {}; - queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; - queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - - HRESULT res = S_OK; - res = bd->pd3dDevice->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&vd->CommandQueue)); - IM_ASSERT(res == S_OK); - - // Create command allocator. - for (UINT i = 0; i < bd->numFramesInFlight; ++i) - { - res = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&vd->FrameCtx[i].CommandAllocator)); - IM_ASSERT(res == S_OK); - } - - // Create command list. - res = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, vd->FrameCtx[0].CommandAllocator, nullptr, IID_PPV_ARGS(&vd->CommandList)); - IM_ASSERT(res == S_OK); - vd->CommandList->Close(); - - // Create fence. - res = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&vd->Fence)); - IM_ASSERT(res == S_OK); - - vd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); - IM_ASSERT(vd->FenceEvent != nullptr); - - // Create swap chain - // FIXME-VIEWPORT: May want to copy/inherit swap chain settings from the user/application. - DXGI_SWAP_CHAIN_DESC1 sd1; - ZeroMemory(&sd1, sizeof(sd1)); - sd1.BufferCount = bd->numFramesInFlight; - sd1.Width = (UINT)viewport->Size.x; - sd1.Height = (UINT)viewport->Size.y; - sd1.Format = bd->RTVFormat; - sd1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - sd1.SampleDesc.Count = 1; - sd1.SampleDesc.Quality = 0; - sd1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; - sd1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; - sd1.Scaling = DXGI_SCALING_NONE; - sd1.Stereo = FALSE; - - IDXGIFactory4* dxgi_factory = nullptr; - res = ::CreateDXGIFactory1(IID_PPV_ARGS(&dxgi_factory)); - IM_ASSERT(res == S_OK); - - IDXGISwapChain1* swap_chain = nullptr; - res = dxgi_factory->CreateSwapChainForHwnd(vd->CommandQueue, hwnd, &sd1, nullptr, nullptr, &swap_chain); - IM_ASSERT(res == S_OK); - - dxgi_factory->Release(); - - // Or swapChain.As(&mSwapChain) - IM_ASSERT(vd->SwapChain == nullptr); - swap_chain->QueryInterface(IID_PPV_ARGS(&vd->SwapChain)); - swap_chain->Release(); - - // Create the render targets - if (vd->SwapChain) - { - D3D12_DESCRIPTOR_HEAP_DESC desc = {}; - desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; - desc.NumDescriptors = bd->numFramesInFlight; - desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; - desc.NodeMask = 1; - - HRESULT hr = bd->pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&vd->RtvDescHeap)); - IM_ASSERT(hr == S_OK); - - SIZE_T rtv_descriptor_size = bd->pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); - D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = vd->RtvDescHeap->GetCPUDescriptorHandleForHeapStart(); - for (UINT i = 0; i < bd->numFramesInFlight; i++) - { - vd->FrameCtx[i].RenderTargetCpuDescriptors = rtv_handle; - rtv_handle.ptr += rtv_descriptor_size; - } - - ID3D12Resource* back_buffer; - for (UINT i = 0; i < bd->numFramesInFlight; i++) - { - IM_ASSERT(vd->FrameCtx[i].RenderTarget == nullptr); - vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer)); - bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors); - vd->FrameCtx[i].RenderTarget = back_buffer; - } - } - - for (UINT i = 0; i < bd->numFramesInFlight; i++) - ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]); -} - -static void ImGui_WaitForPendingOperations(ImGui_ImplDX12_ViewportData* vd) -{ - HRESULT hr = S_FALSE; - if (vd && vd->CommandQueue && vd->Fence && vd->FenceEvent) - { - hr = vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue); - IM_ASSERT(hr == S_OK); - ::WaitForSingleObject(vd->FenceEvent, 0); // Reset any forgotten waits - hr = vd->Fence->SetEventOnCompletion(vd->FenceSignaledValue, vd->FenceEvent); - IM_ASSERT(hr == S_OK); - ::WaitForSingleObject(vd->FenceEvent, INFINITE); - } -} - -static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport) -{ - // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it. - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData) - { - ImGui_WaitForPendingOperations(vd); - - SafeRelease(vd->CommandQueue); - SafeRelease(vd->CommandList); - SafeRelease(vd->SwapChain); - SafeRelease(vd->RtvDescHeap); - SafeRelease(vd->Fence); - ::CloseHandle(vd->FenceEvent); - vd->FenceEvent = nullptr; - - for (UINT i = 0; i < bd->numFramesInFlight; i++) - { - SafeRelease(vd->FrameCtx[i].RenderTarget); - SafeRelease(vd->FrameCtx[i].CommandAllocator); - ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]); - } - IM_DELETE(vd); - } - viewport->RendererUserData = nullptr; -} - -static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) -{ - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData; - - ImGui_WaitForPendingOperations(vd); - - for (UINT i = 0; i < bd->numFramesInFlight; i++) - SafeRelease(vd->FrameCtx[i].RenderTarget); - - if (vd->SwapChain) - { - ID3D12Resource* back_buffer = nullptr; - vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0); - for (UINT i = 0; i < bd->numFramesInFlight; i++) - { - vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer)); - bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors); - vd->FrameCtx[i].RenderTarget = back_buffer; - } - } -} - -static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*) -{ - ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData; - - ImGui_ImplDX12_FrameContext* frame_context = &vd->FrameCtx[vd->FrameIndex % bd->numFramesInFlight]; - UINT back_buffer_idx = vd->SwapChain->GetCurrentBackBufferIndex(); - - const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - D3D12_RESOURCE_BARRIER barrier = {}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrier.Transition.pResource = vd->FrameCtx[back_buffer_idx].RenderTarget; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - - // Draw - ID3D12GraphicsCommandList* cmd_list = vd->CommandList; - - frame_context->CommandAllocator->Reset(); - cmd_list->Reset(frame_context->CommandAllocator, nullptr); - cmd_list->ResourceBarrier(1, &barrier); - cmd_list->OMSetRenderTargets(1, &vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, FALSE, nullptr); - if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear)) - cmd_list->ClearRenderTargetView(vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, (float*)&clear_color, 0, nullptr); - cmd_list->SetDescriptorHeaps(1, &bd->pd3dSrvDescHeap); - - ImGui_ImplDX12_RenderDrawData(viewport->DrawData, cmd_list); - - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; - cmd_list->ResourceBarrier(1, &barrier); - cmd_list->Close(); - - vd->CommandQueue->Wait(vd->Fence, vd->FenceSignaledValue); - vd->CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmd_list); - vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue); -} - -static void ImGui_ImplDX12_SwapBuffers(ImGuiViewport* viewport, void*) -{ - ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData; - - vd->SwapChain->Present(0, 0); - while (vd->Fence->GetCompletedValue() < vd->FenceSignaledValue) - ::SwitchToThread(); -} - -void ImGui_ImplDX12_InitPlatformInterface() -{ - ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - platform_io.Renderer_CreateWindow = ImGui_ImplDX12_CreateWindow; - platform_io.Renderer_DestroyWindow = ImGui_ImplDX12_DestroyWindow; - platform_io.Renderer_SetWindowSize = ImGui_ImplDX12_SetWindowSize; - platform_io.Renderer_RenderWindow = ImGui_ImplDX12_RenderWindow; - platform_io.Renderer_SwapBuffers = ImGui_ImplDX12_SwapBuffers; -} - -void ImGui_ImplDX12_ShutdownPlatformInterface() -{ - ImGui::DestroyPlatformWindows(); -} - -//----------------------------------------------------------------------------- - -#endif // #ifndef IMGUI_DISABLE diff --git a/src/imgui_impl/dx12.h b/src/imgui_impl/dx12.h index 8872029b..899afbdc 100644 --- a/src/imgui_impl/dx12.h +++ b/src/imgui_impl/dx12.h @@ -2,25 +2,20 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about +// ImTextureID! [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. -// See imgui_impl_dx12.cpp file for details. +// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. +// This define is set in the example .vcxproj file and need to be replicated in your app or by adding it to your +// imconfig.h file. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. -// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// Learn about Dear ImGui: -// - FAQ https://dearimgui.com/faq -// - Getting Started https://dearimgui.com/getting-started -// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). -// - Introduction, links and more at the top of imgui.cpp +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once -#include "imgui.h" // IMGUI_IMPL_API -#ifndef IMGUI_DISABLE -#include // DXGI_FORMAT +#include "imgui.h" // IMGUI_IMPL_API struct ID3D12Device; struct ID3D12DescriptorHeap; @@ -28,20 +23,18 @@ struct ID3D12GraphicsCommandList; struct D3D12_CPU_DESCRIPTOR_HANDLE; struct D3D12_GPU_DESCRIPTOR_HANDLE; -// Follow "Getting Started" link and check examples/ folder to learn about using backends! - // cmd_list is the command list that the implementation will use to render imgui draw lists. // Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate // render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle. -// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture. -IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, - D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle); -IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(ID3D12CommandQueue* apCommandQueue); -IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list); +// font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal +// font texture. +IMGUI_IMPL_API bool ImGui_ImplDX12_Init( + ID3D12Device* apDevice, int aNumFramesInFlight, DXGI_FORMAT aRTVFormat, ID3D12DescriptorHeap* apSRVHeapDesc, D3D12_CPU_DESCRIPTOR_HANDLE aFontSRVDescCPU, + D3D12_GPU_DESCRIPTOR_HANDLE aFontSRVDescGPU); +IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(ID3D12CommandQueue* apCommandQueue); +IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* apDrawData, ID3D12GraphicsCommandList* apCommandLists); // Use if you want to reset your rendering device without losing Dear ImGui state. -IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); -IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue); - -#endif // #ifndef IMGUI_DISABLE \ No newline at end of file +IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); +IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(ID3D12CommandQueue* apCommandQueue); diff --git a/src/imgui_impl/imgui_user_config.h b/src/imgui_impl/imgui_user_config.h index c020a6e8..6298b9c7 100644 --- a/src/imgui_impl/imgui_user_config.h +++ b/src/imgui_impl/imgui_user_config.h @@ -3,8 +3,6 @@ // global declaration "Enable ImGui Assertions" extern bool g_ImGuiAssertionsEnabled; -#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - // runtime assertions which can be enabled/disabled inside CET options void ImGuiAssert(wchar_t const* acpMessage, wchar_t const* acpFile, unsigned aLine); diff --git a/src/imgui_impl/win32.cpp b/src/imgui_impl/win32.cpp index bba52488..9ccb8370 100644 --- a/src/imgui_impl/win32.cpp +++ b/src/imgui_impl/win32.cpp @@ -1,258 +1,117 @@ -// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) -// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. -// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). -// [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= -// ImGuiConfigFlags_NavEnableGamepad'. [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. [X] Platform: -// Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= +// ImGuiConfigFlags_NoMouseCursorChange'. [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. +// ImGui::IsKeyPressed(VK_SPACE). [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= +// ImGuiConfigFlags_NavEnableGamepad'. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. -// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// Learn about Dear ImGui: -// - FAQ https://dearimgui.com/faq -// - Getting Started https://dearimgui.com/getting-started -// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). -// - Introduction, links and more at the top of imgui.cpp +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs -// Configuration flags to add in your imconfig file: -// #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less -// relevant. +#include + +#include "win32.h" + +#include "CET.h" +#include "Utils.h" // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface. -// 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768) -// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. -// 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL). -// 2023-09-07: Inputs: Added support for keyboard codepage conversion for when application is compiled in MBCS mode and using a non-Unicode window. -// 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218) -// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702) -// 2023-02-15: Inputs: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse position over non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162) -// 2023-02-02: Inputs: Flipping WM_MOUSEHWHEEL (horizontal mouse-wheel) value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463) -// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. -// 2022-09-28: Inputs: Convert WM_CHAR values with MultiByteToWideChar() when window class was registered as MBCS (not Unicode). -// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). -// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. -// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. -// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). -// 2022-01-17: Inputs: always update key mods next and before a key event (not in NewFrame) to fix input queue with very low framerates. -// 2022-01-12: Inputs: Update mouse inputs using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass -// it to future input queue API. 2022-01-12: Inputs: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. 2022-01-10: -// Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. 2021-12-16: Inputs: Fill -// VK_LCONTROL/VK_RCONTROL/VK_LSHIFT/VK_RSHIFT/VK_LMENU/VK_RMENU for completeness. 2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages. 2021-08-02: Inputs: -// Fixed keyboard modifiers being reported when host window doesn't have focus. 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not -// focused (using TrackMouseEvent() to receive WM_MOUSELEAVE events). 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with -// multiple-contexts (all g_XXXX access changed to bd->XXXX). 2021-06-08: Fixed ImGui_ImplWin32_EnableDpiAwareness() and ImGui_ImplWin32_GetDpiScaleForMonitor() to handle -// Windows 8.1/10 features without a manifest (per-monitor DPI, and properly calls SetProcessDpiAwareness() on 8.1). 2021-03-23: Inputs: Clearing keyboard down array when losing -// focus (WM_KILLFOCUS). 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi). -// 2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1. -// 2021-01-25: Inputs: Dynamically loading XInput DLL. // 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed. -// 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs) -// 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. -// 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT. -// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. -// 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter(). -// 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. -// 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. -// 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application). -// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. -// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. -// 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads). -// 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples. -// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. -// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). -// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. -// 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). -// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. +// 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for +// more complete CJK inputs) 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), +// ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. 2019-12-05: Inputs: +// Added support for ImGuiMouseCursor_NotAllowed mouse cursor. 2019-05-11: Inputs: Don't filter value from WM_CHAR +// before calling AddInputCharacter(). 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of +// GetActiveWindow() to be compatible with windows created in a different thread or parent. 2019-01-17: Inputs: Added +// support for mouse buttons 4 and 5 via WM_XBUTTON* messages. 2019-01-15: Inputs: Added support for XInput gamepads +// (if ImGuiConfigFlags_NavEnableGamepad is set by user application). 2018-11-30: Misc: Setting up +// io.BackendPlatformName so it can be displayed in the About Window. 2018-06-29: Inputs: Added support for the +// ImGuiMouseCursor_Hand cursor. 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position +// messages (typically sent by track-pads). 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old +// combined DX9/DX10/DX11/DX12 examples. 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and +// ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. 2018-02-20: Inputs: Added +// support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). 2018-02-06: Inputs: +// Added mapping for ImGuiKey_Space. 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse +// (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). 2018-02-06: Misc: Removed call to +// ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read. -// 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging. -// 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set. - -#include - -// CET Headers -#include "CET.h" -#include "Utils.h" +// 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when +// dragging. 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set. + +// Win32 Data +static HWND g_hWnd = NULL; +static INT64 g_Time = 0; +static INT64 g_TicksPerSecond = 0; +static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT; static std::string g_LayoutPath = ""; -#include "imgui.h" -#ifndef IMGUI_DISABLE -#include "win32.h" -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include // GET_X_LPARAM(), GET_Y_LPARAM() -#include -#include - -// Using XInput for gamepad (will load DLL dynamically) -#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD -#include -typedef DWORD(WINAPI* PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*); -typedef DWORD(WINAPI* PFN_XInputGetState)(DWORD, XINPUT_STATE*); -#endif - -// Clang/GCC warnings with -Weverything -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) -#endif -#if defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) -#endif - -// Forward Declarations -static void ImGui_ImplWin32_InitPlatformInterface(bool platform_has_own_dc); -static void ImGui_ImplWin32_ShutdownPlatformInterface(); -static void ImGui_ImplWin32_UpdateMonitors(); - -struct ImGui_ImplWin32_Data -{ - HWND hWnd; - HWND MouseHwnd; - int MouseTrackedArea; // 0: not tracked, 1: client are, 2: non-client area - int MouseButtonsDown; - INT64 Time; - INT64 TicksPerSecond; - ImGuiMouseCursor LastMouseCursor; - UINT32 KeyboardCodePage; - bool WantUpdateMonitors; - -#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - bool HasGamepad; - bool WantUpdateHasGamepad; - HMODULE XInputDLL; - PFN_XInputGetCapabilities XInputGetCapabilities; - PFN_XInputGetState XInputGetState; -#endif - - ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } -}; - -// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts -// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. -// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. -// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. -static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData() -{ - return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; -} - // Functions -static void ImGui_ImplWin32_UpdateKeyboardCodePage() +bool ImGui_ImplWin32_Init(HWND ahWnd) { - // Retrieve keyboard code page, required for handling of non-Unicode Windows. - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - HKL keyboard_layout = ::GetKeyboardLayout(0); - LCID keyboard_lcid = MAKELCID(HIWORD(keyboard_layout), SORT_DEFAULT); - if (::GetLocaleInfoA(keyboard_lcid, (LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE), (LPSTR)&bd->KeyboardCodePage, sizeof(bd->KeyboardCodePage)) == 0) - bd->KeyboardCodePage = CP_ACP; // Fallback to default ANSI code page when fails. -} - -static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) -{ - ImGuiIO& io = ImGui::GetIO(); - IMGUI_CHECKVERSION(); - IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); - - INT64 perf_frequency, perf_counter; - if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency)) + if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&g_TicksPerSecond)) return false; - if (!::QueryPerformanceCounter((LARGE_INTEGER*)&perf_counter)) + if (!::QueryPerformanceCounter((LARGE_INTEGER*)&g_Time)) return false; // Setup backend capabilities flags - ImGui_ImplWin32_Data* bd = IM_NEW(ImGui_ImplWin32_Data)(); - io.BackendPlatformUserData = (void*)bd; + g_hWnd = ahWnd; + ImGuiIO& io = ImGui::GetIO(); + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; io.BackendPlatformName = "imgui_impl_win32"; - io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) - io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) - io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional) - io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional) + io.ImeWindowHandle = ahWnd; - // CET specific - // Enable Keyboard Nav and setup INI path - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; - g_LayoutPath = UTF16ToUTF8(GetAbsolutePath(L"layout.ini", CET::Get().GetPaths().CETRoot(), true).native()).c_str(); + // Setup ini path + g_LayoutPath = UTF16ToUTF8(GetAbsolutePath(L"layout.ini", CET::Get().GetPaths().CETRoot(), true).native()); io.IniFilename = g_LayoutPath.c_str(); - bd->hWnd = (HWND)hwnd; - bd->WantUpdateMonitors = true; - bd->TicksPerSecond = perf_frequency; - bd->Time = perf_counter; - bd->LastMouseCursor = ImGuiMouseCursor_COUNT; - ImGui_ImplWin32_UpdateKeyboardCodePage(); - - // Our mouse update function expect PlatformHandle to be filled for the main viewport - ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)bd->hWnd; - if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) - ImGui_ImplWin32_InitPlatformInterface(platform_has_own_dc); - - // Dynamically load XInput library -#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - bd->WantUpdateHasGamepad = true; - const TCHAR* xinput_dll_names[] = { - _T("xinput1_4.dll"), // Windows 8+ - _T("xinput1_3.dll"), // DirectX SDK - _T("xinput9_1_0.dll"), // Windows Vista, Windows 7 - _T("xinput1_2.dll"), // DirectX SDK - _T("xinput1_1.dll") // DirectX SDK - }; - for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++) - if (HMODULE dll = ::LoadLibrary(xinput_dll_names[n])) - { - bd->XInputDLL = dll; - bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities"); - bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState"); - break; - } -#endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during + // the application lifetime. + io.KeyMap[ImGuiKey_Tab] = VK_TAB; + io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; + io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; + io.KeyMap[ImGuiKey_UpArrow] = VK_UP; + io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN; + io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR; + io.KeyMap[ImGuiKey_PageDown] = VK_NEXT; + io.KeyMap[ImGuiKey_Home] = VK_HOME; + io.KeyMap[ImGuiKey_End] = VK_END; + io.KeyMap[ImGuiKey_Insert] = VK_INSERT; + io.KeyMap[ImGuiKey_Delete] = VK_DELETE; + io.KeyMap[ImGuiKey_Backspace] = VK_BACK; + io.KeyMap[ImGuiKey_Space] = VK_SPACE; + io.KeyMap[ImGuiKey_Enter] = VK_RETURN; + io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; + io.KeyMap[ImGuiKey_KeyPadEnter] = VK_RETURN; + io.KeyMap[ImGuiKey_LeftCtrl] = VK_CONTROL; + io.KeyMap[ImGuiKey_LeftShift] = VK_SHIFT; + io.KeyMap[ImGuiKey_A] = 'A'; + io.KeyMap[ImGuiKey_C] = 'C'; + io.KeyMap[ImGuiKey_V] = 'V'; + io.KeyMap[ImGuiKey_X] = 'X'; + io.KeyMap[ImGuiKey_Y] = 'Y'; + io.KeyMap[ImGuiKey_Z] = 'Z'; + io.KeyMap[ImGuiKey_G] = 'G'; + io.KeyMap[ImGuiKey_S] = 'S'; + io.KeyMap[ImGuiKey_D] = 'D'; + io.KeyMap[ImGuiKey_R] = 'R'; + io.KeyMap[ImGuiKey_H] = 'H'; return true; } -IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd) -{ - return ImGui_ImplWin32_InitEx(hwnd, false); -} - -IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd) -{ - // OpenGL needs CS_OWNDC - return ImGui_ImplWin32_InitEx(hwnd, true); -} - void ImGui_ImplWin32_Shutdown() { - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); - ImGuiIO& io = ImGui::GetIO(); - - ImGui_ImplWin32_ShutdownPlatformInterface(); - - // Unload XInput library -#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - if (bd->XInputDLL) - ::FreeLibrary(bd->XInputDLL); -#endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - - io.BackendPlatformName = nullptr; - io.BackendPlatformUserData = nullptr; - io.BackendFlags &= - ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | - ImGuiBackendFlags_HasMouseHoveredViewport); - IM_DELETE(bd); + g_hWnd = (HWND)0; } static bool ImGui_ImplWin32_UpdateMouseCursor() @@ -265,7 +124,7 @@ static bool ImGui_ImplWin32_UpdateMouseCursor() if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor - ::SetCursor(nullptr); + ::SetCursor(NULL); } else { @@ -283,461 +142,98 @@ static bool ImGui_ImplWin32_UpdateMouseCursor() case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; } - ::SetCursor(::LoadCursor(nullptr, win32_cursor)); + ::SetCursor(::LoadCursor(NULL, win32_cursor)); } return true; } -static bool IsVkDown(int vk) -{ - return (::GetKeyState(vk) & 0x8000) != 0; -} - -static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1) +static void ImGui_ImplWin32_UpdateMousePos(SIZE aOutSize) { ImGuiIO& io = ImGui::GetIO(); - io.AddKeyEvent(key, down); - io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code) - IM_UNUSED(native_scancode); -} -static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds() -{ - // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one. - if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT)) - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT); - if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT)) - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT); - - // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW). - if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN)) - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN); - if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN)) - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN); -} - -static void ImGui_ImplWin32_UpdateKeyModifiers() -{ - ImGuiIO& io = ImGui::GetIO(); - io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL)); - io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT)); - io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU)); - io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_LWIN) || IsVkDown(VK_RWIN)); -} - -// This code supports multi-viewports (multiple OS Windows mapped into different Dear ImGui viewports) -// Because of that, it is a little more complicated than your typical single-viewport binding code! -static void ImGui_ImplWin32_UpdateMouseData(SIZE aOutSize) -{ - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(bd->hWnd != 0); - - POINT mouse_screen_pos; - bool has_mouse_screen_pos = ::GetCursorPos(&mouse_screen_pos) != 0; - - HWND focused_window = ::GetForegroundWindow(); - const bool is_app_focused = - (focused_window && (focused_window == bd->hWnd || ::IsChild(focused_window, bd->hWnd) || ImGui::FindViewportByPlatformHandle((void*)focused_window))); - if (is_app_focused) + // Set OS mouse position if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by + // user) + if (io.WantSetMousePos) { - // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) - // When multi-viewports are enabled, all Dear ImGui positions are same as OS positions. - if (io.WantSetMousePos) - { - POINT pos = {(int)io.MousePos.x, (int)io.MousePos.y}; - if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0) - ::ClientToScreen(focused_window, &pos); + POINT pos = {(int)io.MousePos.x, (int)io.MousePos.y}; + if (::ClientToScreen(g_hWnd, &pos)) ::SetCursorPos(pos.x, pos.y); - } - - // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured) - // This also fills a short gap when clicking non-client area: WM_NCMOUSELEAVE -> modal OS move -> gap -> WM_NCMOUSEMOVE - if (!io.WantSetMousePos && bd->MouseTrackedArea == 0 && has_mouse_screen_pos) - { - // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) - // (This is the position you can get with ::GetCursorPos() + ::ScreenToClient() or WM_MOUSEMOVE.) - // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) - // (This is the position you can get with ::GetCursorPos() or WM_MOUSEMOVE + ::ClientToScreen(). In theory adding viewport->Pos to a client position would also be the - // same.) - POINT mouse_pos = mouse_screen_pos; - if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)) - ::ScreenToClient(bd->hWnd, &mouse_pos); - - static float xScale = 1.0; - static float yScale = 1.0; - if(aOutSize.cx && aOutSize.cy) - { - RECT clientRect; - ::GetClientRect(bd->hWnd, &clientRect); - xScale = static_cast(aOutSize.cx) / (clientRect.right - clientRect.left); - yScale = static_cast(aOutSize.cy) / (clientRect.bottom - clientRect.top); - } - io.AddMousePosEvent((float)mouse_pos.x * xScale, (float)mouse_pos.y * yScale); - } - } - - // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering. - // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic. - // - [X] Win32 backend correctly ignore viewports with the _NoInputs flag (here using ::WindowFromPoint with WM_NCHITTEST + HTTRANSPARENT in WndProc does that) - // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window - // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported - // by the backend, and use its flawed heuristic to guess the viewport behind. - // - [X] Win32 backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target). - ImGuiID mouse_viewport_id = 0; - if (has_mouse_screen_pos) - if (HWND hovered_hwnd = ::WindowFromPoint(mouse_screen_pos)) - if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hovered_hwnd)) - mouse_viewport_id = viewport->ID; - io.AddMouseViewportEvent(mouse_viewport_id); -} - -// Gamepad navigation mapping -static void ImGui_ImplWin32_UpdateGamepads() -{ -#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - // if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. - // return; - - // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow. - // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE. - if (bd->WantUpdateHasGamepad) - { - XINPUT_CAPABILITIES caps = {}; - bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false; - bd->WantUpdateHasGamepad = false; } - io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; - XINPUT_STATE xinput_state; - XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad; - if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) - return; - io.BackendFlags |= ImGuiBackendFlags_HasGamepad; - -#define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) -#define MAP_BUTTON(KEY_NO, BUTTON_ENUM) \ - { \ - io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); \ - } -#define MAP_ANALOG(KEY_NO, VALUE, V0, V1) \ - { \ - float vn = (float)(VALUE - V0) / (float)(V1 - V0); \ - io.AddKeyAnalogEvent(KEY_NO, vn > 0.10f, IM_SATURATE(vn)); \ - } - MAP_BUTTON(ImGuiKey_GamepadStart, XINPUT_GAMEPAD_START); - MAP_BUTTON(ImGuiKey_GamepadBack, XINPUT_GAMEPAD_BACK); - MAP_BUTTON(ImGuiKey_GamepadFaceLeft, XINPUT_GAMEPAD_X); - MAP_BUTTON(ImGuiKey_GamepadFaceRight, XINPUT_GAMEPAD_B); - MAP_BUTTON(ImGuiKey_GamepadFaceUp, XINPUT_GAMEPAD_Y); - MAP_BUTTON(ImGuiKey_GamepadFaceDown, XINPUT_GAMEPAD_A); - MAP_BUTTON(ImGuiKey_GamepadDpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); - MAP_BUTTON(ImGuiKey_GamepadDpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); - MAP_BUTTON(ImGuiKey_GamepadDpadUp, XINPUT_GAMEPAD_DPAD_UP); - MAP_BUTTON(ImGuiKey_GamepadDpadDown, XINPUT_GAMEPAD_DPAD_DOWN); - MAP_BUTTON(ImGuiKey_GamepadL1, XINPUT_GAMEPAD_LEFT_SHOULDER); - MAP_BUTTON(ImGuiKey_GamepadR1, XINPUT_GAMEPAD_RIGHT_SHOULDER); - MAP_ANALOG(ImGuiKey_GamepadL2, gamepad.bLeftTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); - MAP_ANALOG(ImGuiKey_GamepadR2, gamepad.bRightTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); - MAP_BUTTON(ImGuiKey_GamepadL3, XINPUT_GAMEPAD_LEFT_THUMB); - MAP_BUTTON(ImGuiKey_GamepadR3, XINPUT_GAMEPAD_RIGHT_THUMB); - MAP_ANALOG(ImGuiKey_GamepadLStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); - MAP_ANALOG(ImGuiKey_GamepadLStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); - MAP_ANALOG(ImGuiKey_GamepadLStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); - MAP_ANALOG(ImGuiKey_GamepadLStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); - MAP_ANALOG(ImGuiKey_GamepadRStickLeft, gamepad.sThumbRX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); - MAP_ANALOG(ImGuiKey_GamepadRStickRight, gamepad.sThumbRX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); - MAP_ANALOG(ImGuiKey_GamepadRStickUp, gamepad.sThumbRY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); - MAP_ANALOG(ImGuiKey_GamepadRStickDown, gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); -#undef MAP_BUTTON -#undef MAP_ANALOG -#endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD -} - -static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM) -{ - MONITORINFO info = {}; - info.cbSize = sizeof(MONITORINFO); - if (!::GetMonitorInfo(monitor, &info)) - return TRUE; - ImGuiPlatformMonitor imgui_monitor; - imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top); - imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top)); - imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top); - imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top)); - imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); - imgui_monitor.PlatformHandle = (void*)monitor; - if (imgui_monitor.DpiScale <= 0.0f) - return TRUE; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902. - ImGuiPlatformIO& io = ImGui::GetPlatformIO(); - if (info.dwFlags & MONITORINFOF_PRIMARY) - io.Monitors.push_front(imgui_monitor); - else - io.Monitors.push_back(imgui_monitor); - return TRUE; -} + // Set mouse position + io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + POINT pos; + if (HWND active_window = ::GetForegroundWindow()) + if (active_window == g_hWnd || ::IsChild(active_window, g_hWnd)) + if (::GetCursorPos(&pos) && ::ScreenToClient(g_hWnd, &pos)) + if (!aOutSize.cx || !aOutSize.cy) + io.MousePos = ImVec2((float)pos.x, (float)pos.y); + else + { + RECT clientRect; + ::GetClientRect(g_hWnd, &clientRect); -static void ImGui_ImplWin32_UpdateMonitors() -{ - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - ImGui::GetPlatformIO().Monitors.resize(0); - ::EnumDisplayMonitors(nullptr, nullptr, ImGui_ImplWin32_UpdateMonitors_EnumFunc, 0); - bd->WantUpdateMonitors = false; + // scale, just to make sure coords are correct (fixes issues in fullscreen) + auto xScale = static_cast(aOutSize.cx) / (clientRect.right - clientRect.left); + auto yScale = static_cast(aOutSize.cy) / (clientRect.bottom - clientRect.top); + io.MousePos = ImVec2(pos.x * xScale, pos.y * yScale); + } } void ImGui_ImplWin32_NewFrame(SIZE aOutSize) { - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - IM_ASSERT(bd != nullptr && "Context or backend not initialized? Did you call ImGui_ImplWin32_Init()?"); ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT( + io.Fonts->IsBuilt() && "Font atlas not built! It is generally built by the renderer backend. Missing call to " + "renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()."); // Setup display size (every frame to accommodate for window resizing) - // RECT rect = {0, 0, 0, 0}; - // ::GetClientRect(bd->hWnd, &rect); - io.DisplaySize = ImVec2(static_cast(aOutSize.cx), static_cast(aOutSize.cy)); - if (bd->WantUpdateMonitors) - ImGui_ImplWin32_UpdateMonitors(); + io.DisplaySize = {static_cast(aOutSize.cx), static_cast(aOutSize.cy)}; // Setup time step INT64 current_time = 0; ::QueryPerformanceCounter((LARGE_INTEGER*)¤t_time); - io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond; - bd->Time = current_time; + io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond; + g_Time = current_time; - // Update OS mouse position - ImGui_ImplWin32_UpdateMouseData(aOutSize); + // Read keyboard modifiers inputs + io.KeyCtrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0; + io.KeyShift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0; + io.KeyAlt = (::GetKeyState(VK_MENU) & 0x8000) != 0; + io.KeySuper = false; + // io.KeysDown[], io.MousePos, io.MouseDown[], io.MouseWheel: filled by the WndProc handler below. - // Process workarounds for known Windows key handling issues - ImGui_ImplWin32_ProcessKeyEventsWorkarounds(); + // Update OS mouse position + ImGui_ImplWin32_UpdateMousePos(aOutSize); // Update OS mouse cursor with the cursor requested by imgui ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); - if (bd->LastMouseCursor != mouse_cursor) + if (g_LastMouseCursor != mouse_cursor) { - bd->LastMouseCursor = mouse_cursor; + g_LastMouseCursor = mouse_cursor; ImGui_ImplWin32_UpdateMouseCursor(); } - - // Update game controllers (if enabled and available) - ImGui_ImplWin32_UpdateGamepads(); } -// There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED, we assign it an arbitrary value to make code more readable (VK_ codes go up to 255) -#define IM_VK_KEYPAD_ENTER (VK_RETURN + 256) - -// Map VK_xxx to ImGuiKey_xxx. -static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam) -{ - switch (wParam) - { - case VK_TAB: return ImGuiKey_Tab; - case VK_LEFT: return ImGuiKey_LeftArrow; - case VK_RIGHT: return ImGuiKey_RightArrow; - case VK_UP: return ImGuiKey_UpArrow; - case VK_DOWN: return ImGuiKey_DownArrow; - case VK_PRIOR: return ImGuiKey_PageUp; - case VK_NEXT: return ImGuiKey_PageDown; - case VK_HOME: return ImGuiKey_Home; - case VK_END: return ImGuiKey_End; - case VK_INSERT: return ImGuiKey_Insert; - case VK_DELETE: return ImGuiKey_Delete; - case VK_BACK: return ImGuiKey_Backspace; - case VK_SPACE: return ImGuiKey_Space; - case VK_RETURN: return ImGuiKey_Enter; - case VK_ESCAPE: return ImGuiKey_Escape; - case VK_OEM_7: return ImGuiKey_Apostrophe; - case VK_OEM_COMMA: return ImGuiKey_Comma; - case VK_OEM_MINUS: return ImGuiKey_Minus; - case VK_OEM_PERIOD: return ImGuiKey_Period; - case VK_OEM_2: return ImGuiKey_Slash; - case VK_OEM_1: return ImGuiKey_Semicolon; - case VK_OEM_PLUS: return ImGuiKey_Equal; - case VK_OEM_4: return ImGuiKey_LeftBracket; - case VK_OEM_5: return ImGuiKey_Backslash; - case VK_OEM_6: return ImGuiKey_RightBracket; - case VK_OEM_3: return ImGuiKey_GraveAccent; - case VK_CAPITAL: return ImGuiKey_CapsLock; - case VK_SCROLL: return ImGuiKey_ScrollLock; - case VK_NUMLOCK: return ImGuiKey_NumLock; - case VK_SNAPSHOT: return ImGuiKey_PrintScreen; - case VK_PAUSE: return ImGuiKey_Pause; - case VK_NUMPAD0: return ImGuiKey_Keypad0; - case VK_NUMPAD1: return ImGuiKey_Keypad1; - case VK_NUMPAD2: return ImGuiKey_Keypad2; - case VK_NUMPAD3: return ImGuiKey_Keypad3; - case VK_NUMPAD4: return ImGuiKey_Keypad4; - case VK_NUMPAD5: return ImGuiKey_Keypad5; - case VK_NUMPAD6: return ImGuiKey_Keypad6; - case VK_NUMPAD7: return ImGuiKey_Keypad7; - case VK_NUMPAD8: return ImGuiKey_Keypad8; - case VK_NUMPAD9: return ImGuiKey_Keypad9; - case VK_DECIMAL: return ImGuiKey_KeypadDecimal; - case VK_DIVIDE: return ImGuiKey_KeypadDivide; - case VK_MULTIPLY: return ImGuiKey_KeypadMultiply; - case VK_SUBTRACT: return ImGuiKey_KeypadSubtract; - case VK_ADD: return ImGuiKey_KeypadAdd; - case IM_VK_KEYPAD_ENTER: return ImGuiKey_KeypadEnter; - case VK_LSHIFT: return ImGuiKey_LeftShift; - case VK_LCONTROL: return ImGuiKey_LeftCtrl; - case VK_LMENU: return ImGuiKey_LeftAlt; - case VK_LWIN: return ImGuiKey_LeftSuper; - case VK_RSHIFT: return ImGuiKey_RightShift; - case VK_RCONTROL: return ImGuiKey_RightCtrl; - case VK_RMENU: return ImGuiKey_RightAlt; - case VK_RWIN: return ImGuiKey_RightSuper; - case VK_APPS: return ImGuiKey_Menu; - case '0': return ImGuiKey_0; - case '1': return ImGuiKey_1; - case '2': return ImGuiKey_2; - case '3': return ImGuiKey_3; - case '4': return ImGuiKey_4; - case '5': return ImGuiKey_5; - case '6': return ImGuiKey_6; - case '7': return ImGuiKey_7; - case '8': return ImGuiKey_8; - case '9': return ImGuiKey_9; - case 'A': return ImGuiKey_A; - case 'B': return ImGuiKey_B; - case 'C': return ImGuiKey_C; - case 'D': return ImGuiKey_D; - case 'E': return ImGuiKey_E; - case 'F': return ImGuiKey_F; - case 'G': return ImGuiKey_G; - case 'H': return ImGuiKey_H; - case 'I': return ImGuiKey_I; - case 'J': return ImGuiKey_J; - case 'K': return ImGuiKey_K; - case 'L': return ImGuiKey_L; - case 'M': return ImGuiKey_M; - case 'N': return ImGuiKey_N; - case 'O': return ImGuiKey_O; - case 'P': return ImGuiKey_P; - case 'Q': return ImGuiKey_Q; - case 'R': return ImGuiKey_R; - case 'S': return ImGuiKey_S; - case 'T': return ImGuiKey_T; - case 'U': return ImGuiKey_U; - case 'V': return ImGuiKey_V; - case 'W': return ImGuiKey_W; - case 'X': return ImGuiKey_X; - case 'Y': return ImGuiKey_Y; - case 'Z': return ImGuiKey_Z; - case VK_F1: return ImGuiKey_F1; - case VK_F2: return ImGuiKey_F2; - case VK_F3: return ImGuiKey_F3; - case VK_F4: return ImGuiKey_F4; - case VK_F5: return ImGuiKey_F5; - case VK_F6: return ImGuiKey_F6; - case VK_F7: return ImGuiKey_F7; - case VK_F8: return ImGuiKey_F8; - case VK_F9: return ImGuiKey_F9; - case VK_F10: return ImGuiKey_F10; - case VK_F11: return ImGuiKey_F11; - case VK_F12: return ImGuiKey_F12; - case VK_F13: return ImGuiKey_F13; - case VK_F14: return ImGuiKey_F14; - case VK_F15: return ImGuiKey_F15; - case VK_F16: return ImGuiKey_F16; - case VK_F17: return ImGuiKey_F17; - case VK_F18: return ImGuiKey_F18; - case VK_F19: return ImGuiKey_F19; - case VK_F20: return ImGuiKey_F20; - case VK_F21: return ImGuiKey_F21; - case VK_F22: return ImGuiKey_F22; - case VK_F23: return ImGuiKey_F23; - case VK_F24: return ImGuiKey_F24; - case VK_BROWSER_BACK: return ImGuiKey_AppBack; - case VK_BROWSER_FORWARD: return ImGuiKey_AppForward; - default: return ImGuiKey_None; - } -} - -// Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. -#ifndef WM_MOUSEHWHEEL -#define WM_MOUSEHWHEEL 0x020E -#endif -#ifndef DBT_DEVNODES_CHANGED -#define DBT_DEVNODES_CHANGED 0x0007 -#endif - // Win32 message handler (process Win32 mouse/keyboard inputs, etc.) -// Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. -// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs. -// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. -// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Call from your application's message handler. +// When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if +// Dear ImGui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags. -// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds. -// PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set -// this flag. -#if 0 -// Copy this line into your .cpp file to forward declare the function. -extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); -#endif - -// See https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages -// Prefer to call this at the top of the message handler to avoid the possibility of other Win32 calls interfering with this. -static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() -{ - LPARAM extra_info = ::GetMessageExtraInfo(); - if ((extra_info & 0xFFFFFF80) == 0xFF515700) - return ImGuiMouseSource_Pen; - if ((extra_info & 0xFFFFFF80) == 0xFF515780) - return ImGuiMouseSource_TouchScreen; - return ImGuiMouseSource_Mouse; -} - -IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +// PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse +// coordinates when dragging mouse outside of our window bounds. PS: We treat DBLCLK messages as regular mouse down +// messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code +// doesn't set this flag. +IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND ahWnd, UINT auMsg, WPARAM awParam, LPARAM alParam) { - // Most backends don't have silent checks like this one, but we need it because WndProc are called early in CreateWindow(). - // We silently allow both context or just only backend data to be nullptr. - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - if (bd == nullptr) + if (ImGui::GetCurrentContext() == NULL) return 0; - ImGuiIO& io = ImGui::GetIO(); - switch (msg) - { - case WM_MOUSEMOVE: - case WM_NCMOUSEMOVE: - { - // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events - ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); - const int area = (msg == WM_MOUSEMOVE) ? 1 : 2; - bd->MouseHwnd = hwnd; - if (bd->MouseTrackedArea != area) - { - TRACKMOUSEEVENT tme_cancel = {sizeof(tme_cancel), TME_CANCEL, hwnd, 0}; - TRACKMOUSEEVENT tme_track = {sizeof(tme_track), (DWORD)((area == 2) ? (TME_LEAVE | TME_NONCLIENT) : TME_LEAVE), hwnd, 0}; - if (bd->MouseTrackedArea != 0) - ::TrackMouseEvent(&tme_cancel); - ::TrackMouseEvent(&tme_track); - bd->MouseTrackedArea = area; - } - POINT mouse_pos = {(LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam)}; - bool want_absolute_pos = (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) != 0; - if (msg == WM_MOUSEMOVE && want_absolute_pos) // WM_MOUSEMOVE are client-relative coordinates. - ::ClientToScreen(hwnd, &mouse_pos); - if (msg == WM_NCMOUSEMOVE && !want_absolute_pos) // WM_NCMOUSEMOVE are absolute coordinates. - ::ScreenToClient(hwnd, &mouse_pos); - io.AddMouseSourceEvent(mouse_source); - io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); - return 0; - } - case WM_MOUSELEAVE: - case WM_NCMOUSELEAVE: + ImGuiIO& io = ImGui::GetIO(); + switch (auMsg) { - const int area = (msg == WM_MOUSELEAVE) ? 1 : 2; - if (bd->MouseTrackedArea == area) - { - if (bd->MouseHwnd == hwnd) - bd->MouseHwnd = nullptr; - bd->MouseTrackedArea = 0; - io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); - } - return 0; - } case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: @@ -747,29 +243,26 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: { - ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); int button = 0; - if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) + if (auMsg == WM_LBUTTONDOWN || auMsg == WM_LBUTTONDBLCLK) { button = 0; } - if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) + if (auMsg == WM_RBUTTONDOWN || auMsg == WM_RBUTTONDBLCLK) { button = 1; } - if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) + if (auMsg == WM_MBUTTONDOWN || auMsg == WM_MBUTTONDBLCLK) { button = 2; } - if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) + if (auMsg == WM_XBUTTONDOWN || auMsg == WM_XBUTTONDBLCLK) { - button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; + button = (GET_XBUTTON_WPARAM(awParam) == XBUTTON1) ? 3 : 4; } - if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr) - ::SetCapture(hwnd); - bd->MouseButtonsDown |= 1 << button; - io.AddMouseSourceEvent(mouse_source); - io.AddMouseButtonEvent(button, true); + if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL) + ::SetCapture(ahWnd); + io.MouseDown[button] = true; return 0; } case WM_LBUTTONUP: @@ -777,128 +270,53 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA case WM_MBUTTONUP: case WM_XBUTTONUP: { - ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); int button = 0; - if (msg == WM_LBUTTONUP) + if (auMsg == WM_LBUTTONUP) { button = 0; } - if (msg == WM_RBUTTONUP) + if (auMsg == WM_RBUTTONUP) { button = 1; } - if (msg == WM_MBUTTONUP) + if (auMsg == WM_MBUTTONUP) { button = 2; } - if (msg == WM_XBUTTONUP) + if (auMsg == WM_XBUTTONUP) { - button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; + button = (GET_XBUTTON_WPARAM(awParam) == XBUTTON1) ? 3 : 4; } - bd->MouseButtonsDown &= ~(1 << button); - if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd) + io.MouseDown[button] = false; + if (!ImGui::IsAnyMouseDown() && ::GetCapture() == ahWnd) ::ReleaseCapture(); - io.AddMouseSourceEvent(mouse_source); - io.AddMouseButtonEvent(button, false); return 0; } - case WM_MOUSEWHEEL: io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA); return 0; - case WM_MOUSEHWHEEL: io.AddMouseWheelEvent(-(float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f); return 0; + case WM_MOUSEWHEEL: io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(awParam) / (float)WHEEL_DELTA; return 0; + case WM_MOUSEHWHEEL: io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(awParam) / (float)WHEEL_DELTA; return 0; case WM_KEYDOWN: - case WM_KEYUP: case WM_SYSKEYDOWN: + if (awParam < 256) + io.KeysDown[awParam] = true; + return 0; + case WM_KEYUP: case WM_SYSKEYUP: - { - const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); - if (wParam < 256) - { - // Submit modifiers - ImGui_ImplWin32_UpdateKeyModifiers(); - - // Obtain virtual key code - // (keypad enter doesn't have its own... VK_RETURN with KF_EXTENDED flag means keypad enter, see IM_VK_KEYPAD_ENTER definition for details, it is mapped to - // ImGuiKey_KeyPadEnter.) - int vk = (int)wParam; - if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) - vk = IM_VK_KEYPAD_ENTER; - const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk); - const int scancode = (int)LOBYTE(HIWORD(lParam)); - - // Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event. - if (key == ImGuiKey_PrintScreen && !is_key_down) - ImGui_ImplWin32_AddKeyEvent(key, true, vk, scancode); - - // Submit key event - if (key != ImGuiKey_None) - ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode); - - // Submit individual left/right modifier events - if (vk == VK_SHIFT) - { - // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds() - if (IsVkDown(VK_LSHIFT) == is_key_down) - { - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); - } - if (IsVkDown(VK_RSHIFT) == is_key_down) - { - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); - } - } - else if (vk == VK_CONTROL) - { - if (IsVkDown(VK_LCONTROL) == is_key_down) - { - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); - } - if (IsVkDown(VK_RCONTROL) == is_key_down) - { - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); - } - } - else if (vk == VK_MENU) - { - if (IsVkDown(VK_LMENU) == is_key_down) - { - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); - } - if (IsVkDown(VK_RMENU) == is_key_down) - { - ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); - } - } - } + if (awParam < 256) + io.KeysDown[awParam] = false; return 0; - } - case WM_SETFOCUS: - case WM_KILLFOCUS: io.AddFocusEvent(msg == WM_SETFOCUS); return 0; - case WM_INPUTLANGCHANGE: ImGui_ImplWin32_UpdateKeyboardCodePage(); return 0; case WM_CHAR: - if (::IsWindowUnicode(hwnd)) - { - // You can also use ToAscii()+GetKeyboardState() to retrieve characters. - if (wParam > 0 && wParam < 0x10000) - io.AddInputCharacterUTF16((unsigned short)wParam); - } - else - { - wchar_t wch = 0; - ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1); - io.AddInputCharacter(wch); - } + // You can also use ToAscii()+GetKeyboardState() to retrieve characters. + if (awParam > 0 && awParam < 0x10000) + io.AddInputCharacterUTF16((unsigned short)awParam); return 0; case WM_SETCURSOR: - // This is required to restore cursor when transitioning from e.g resize borders to client area. - if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) + if (LOWORD(alParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) return 1; return 0; - case WM_DEVICECHANGE: -#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - if ((UINT)wParam == DBT_DEVNODES_CHANGED) - bd->WantUpdateHasGamepad = true; -#endif + case WM_KILLFOCUS: + std::fill_n(io.KeysDown, std::size(io.KeysDown), 0); + std::fill_n(io.MouseDown, std::size(io.MouseDown), 0); return 0; - case WM_DISPLAYCHANGE: bd->WantUpdateMonitors = true; return 0; } return 0; } @@ -908,41 +326,30 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA //-------------------------------------------------------------------------------------------------------- // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. -// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. -// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, -// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. +// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), +// etc. +// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at +// runtime, neither we want to require the user to have. So we dynamically select and load those functions to avoid +// dependencies. //--------------------------------------------------------------------------------------------------------- -// This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable. -// ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically. -// If you are trying to implement your own backend for your own engine, you may ignore that noise. +// This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be +// highly portable. ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it +// automatically. If you are trying to implement your own backend for your own engine, you may ignore that noise. //--------------------------------------------------------------------------------------------------------- -// Perform our own check with RtlVerifyVersionInfo() instead of using functions from as they -// require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200 -static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) +// Implement some of the functions and types normally declared in recent Windows SDK. +#if !defined(_versionhelpers_H_INCLUDED_) && !defined(_INC_VERSIONHELPERS) +static BOOL IsWindowsVersionOrGreater(WORD aMajor, WORD aMinor, WORD aSP) { - typedef LONG(WINAPI * PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG); - static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr; - if (RtlVerifyVersionInfoFn == nullptr) - if (HMODULE ntdllModule = ::GetModuleHandle(_T("ntdll.dll"))) - RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); - if (RtlVerifyVersionInfoFn == nullptr) - return FALSE; - - RTL_OSVERSIONINFOEXW versionInfo = {}; - ULONGLONG conditionMask = 0; - versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); - versionInfo.dwMajorVersion = major; - versionInfo.dwMinorVersion = minor; - VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); - VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); - return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE; + OSVERSIONINFOEXW osvi = {sizeof(osvi), aMajor, aMinor, 0, 0, {0}, aSP, 0, 0, 0, 0}; + DWORD mask = VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR; + ULONGLONG cond = ::VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL); + cond = ::VerSetConditionMask(cond, VER_MINORVERSION, VER_GREATER_EQUAL); + cond = ::VerSetConditionMask(cond, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); + return ::VerifyVersionInfoW(&osvi, mask, cond); } - -#define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA -#define _IsWindows8OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8 -#define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE -#define _IsWindows10OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10 +#define IsWindows8Point1OrGreater() IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WINBLUE +#endif #ifndef DPI_ENUMS_DECLARED typedef enum @@ -973,22 +380,18 @@ typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWAR // Helper function to enable DPI awareness without setting up a manifest void ImGui_ImplWin32_EnableDpiAwareness() { - // Make sure monitors will be updated with latest correct scaling - if (ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData()) - bd->WantUpdateMonitors = true; - - if (_IsWindows10OrGreater()) + // if (IsWindows10OrGreater()) // This needs a manifest to succeed. Instead we try to grab the function pointer! { - static HINSTANCE user32_dll = ::LoadLibrary(_T("user32.dll")); // Reference counted per-process + static HINSTANCE user32_dll = ::LoadLibrary(TEXT("user32.dll")); // Reference counted per-process if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext")) { SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); return; } } - if (_IsWindows8Point1OrGreater()) + if (IsWindows8Point1OrGreater()) { - static HINSTANCE shcore_dll = ::LoadLibrary(_T("shcore.dll")); // Reference counted per-process + static HINSTANCE shcore_dll = ::LoadLibrary(TEXT("shcore.dll")); // Reference counted per-process if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness")) { SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE); @@ -1001,451 +404,36 @@ void ImGui_ImplWin32_EnableDpiAwareness() } #if defined(_MSC_VER) && !defined(NOGDI) -#pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32' +#pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps() #endif -float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) +float ImGui_ImplWin32_GetDpiScaleForMonitor(HMONITOR ahMonitor) { UINT xdpi = 96, ydpi = 96; - if (_IsWindows8Point1OrGreater()) + static BOOL bIsWindows8Point1OrGreater = IsWindows8Point1OrGreater(); + if (bIsWindows8Point1OrGreater) { - static HINSTANCE shcore_dll = ::LoadLibrary(_T("shcore.dll")); // Reference counted per-process - static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr; - if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr) - GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"); - if (GetDpiForMonitorFn != nullptr) - { - GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); - IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! - return xdpi / 96.0f; - } + static HINSTANCE shcore_dll = ::LoadLibrary(TEXT("shcore.dll")); // Reference counted per-process + if (PFN_GetDpiForMonitor GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor")) + GetDpiForMonitorFn(ahMonitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); } #ifndef NOGDI - const HDC dc = ::GetDC(nullptr); - xdpi = ::GetDeviceCaps(dc, LOGPIXELSX); - ydpi = ::GetDeviceCaps(dc, LOGPIXELSY); - IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! - ::ReleaseDC(nullptr, dc); -#endif - return xdpi / 96.0f; -} - -float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) -{ - HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST); - return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); -} - -//--------------------------------------------------------------------------------------------------------- -// Transparency related helpers (optional) -//-------------------------------------------------------------------------------------------------------- - -#if defined(_MSC_VER) -#pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi' -#endif - -// [experimental] -// Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c -// (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW) -void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) -{ - if (!_IsWindowsVistaOrGreater()) - return; - - BOOL composition; - if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition) - return; - - BOOL opaque; - DWORD color; - if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque)) - { - HRGN region = ::CreateRectRgn(0, 0, -1, -1); - DWM_BLURBEHIND bb = {}; - bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION; - bb.hRgnBlur = region; - bb.fEnable = TRUE; - ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); - ::DeleteObject(region); - } else { - DWM_BLURBEHIND bb = {}; - bb.dwFlags = DWM_BB_ENABLE; - ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); + const HDC dc = ::GetDC(NULL); + xdpi = ::GetDeviceCaps(dc, LOGPIXELSX); + ydpi = ::GetDeviceCaps(dc, LOGPIXELSY); + ::ReleaseDC(NULL, dc); } -} - -//--------------------------------------------------------------------------------------------------------- -// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT -// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously. -// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first.. -//-------------------------------------------------------------------------------------------------------- - -// Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data. -struct ImGui_ImplWin32_ViewportData -{ - HWND Hwnd; - HWND HwndParent; - bool HwndOwned; - DWORD DwStyle; - DWORD DwExStyle; - - ImGui_ImplWin32_ViewportData() - { - Hwnd = HwndParent = nullptr; - HwndOwned = false; - DwStyle = DwExStyle = 0; - } - ~ImGui_ImplWin32_ViewportData() { IM_ASSERT(Hwnd == nullptr); } -}; - -static void ImGui_ImplWin32_GetWin32StyleFromViewportFlags(ImGuiViewportFlags flags, DWORD* out_style, DWORD* out_ex_style) -{ - if (flags & ImGuiViewportFlags_NoDecoration) - *out_style = WS_POPUP; - else - *out_style = WS_OVERLAPPEDWINDOW; - - if (flags & ImGuiViewportFlags_NoTaskBarIcon) - *out_ex_style = WS_EX_TOOLWINDOW; - else - *out_ex_style = WS_EX_APPWINDOW; - - if (flags & ImGuiViewportFlags_TopMost) - *out_ex_style |= WS_EX_TOPMOST; -} - -static HWND ImGui_ImplWin32_GetHwndFromViewportID(ImGuiID viewport_id) -{ - if (viewport_id != 0) - if (ImGuiViewport* viewport = ImGui::FindViewportByID(viewport_id)) - return (HWND)viewport->PlatformHandle; - return nullptr; -} - -static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = IM_NEW(ImGui_ImplWin32_ViewportData)(); - viewport->PlatformUserData = vd; - - // Select style and parent window - ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &vd->DwStyle, &vd->DwExStyle); - vd->HwndParent = ImGui_ImplWin32_GetHwndFromViewportID(viewport->ParentViewportId); - - // Create window - RECT rect = {(LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y)}; - ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); - vd->Hwnd = ::CreateWindowEx( - vd->DwExStyle, _T("ImGui Platform"), _T("Untitled"), vd->DwStyle, // Style, class name, window name - rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area - vd->HwndParent, nullptr, ::GetModuleHandle(nullptr), nullptr); // Owner window, Menu, Instance, Param - vd->HwndOwned = true; - viewport->PlatformRequestResize = false; - viewport->PlatformHandle = viewport->PlatformHandleRaw = vd->Hwnd; - - // Secondary viewports store their imgui context - ::SetProp(vd->Hwnd, _T("IMGUI_CONTEXT"), ImGui::GetCurrentContext()); -} - -static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - if (ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData) - { - if (::GetCapture() == vd->Hwnd) - { - // Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event. - ::ReleaseCapture(); - ::SetCapture(bd->hWnd); - } - if (vd->Hwnd && vd->HwndOwned) - ::DestroyWindow(vd->Hwnd); - vd->Hwnd = nullptr; - IM_DELETE(vd); - } - viewport->PlatformUserData = viewport->PlatformHandle = nullptr; -} - -static void ImGui_ImplWin32_ShowWindow(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - - // ShowParent() also brings parent to front, which is not always desirable, - // so we temporarily disable parenting. (#7354) - if (vd->HwndParent != NULL) - ::SetWindowLongPtr(vd->Hwnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr); - - if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) - ::ShowWindow(vd->Hwnd, SW_SHOWNA); - else - ::ShowWindow(vd->Hwnd, SW_SHOW); - - // Restore - if (vd->HwndParent != NULL) - ::SetWindowLongPtr(vd->Hwnd, GWLP_HWNDPARENT, (LONG_PTR)vd->HwndParent); -} - -static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - - // Update Win32 parent if it changed _after_ creation - // Unlike style settings derived from configuration flags, this is more likely to change for advanced apps that are manipulating ParentViewportID manually. - HWND new_parent = ImGui_ImplWin32_GetHwndFromViewportID(viewport->ParentViewportId); - if (new_parent != vd->HwndParent) - { - // Win32 windows can either have a "Parent" (for WS_CHILD window) or an "Owner" (which among other thing keeps window above its owner). - // Our Dear Imgui-side concept of parenting only mostly care about what Win32 call "Owner". - // The parent parameter of CreateWindowEx() sets up Parent OR Owner depending on WS_CHILD flag. In our case an Owner as we never use WS_CHILD. - // Calling ::SetParent() here would be incorrect: it will create a full child relation, alter coordinate system and clipping. - // Calling ::SetWindowLongPtr() with GWLP_HWNDPARENT seems correct although poorly documented. - // https://devblogs.microsoft.com/oldnewthing/20100315-00/?p=14613 - vd->HwndParent = new_parent; - ::SetWindowLongPtr(vd->Hwnd, GWLP_HWNDPARENT, (LONG_PTR)vd->HwndParent); - } - - // (Optional) Update Win32 style if it changed _after_ creation. - // Generally they won't change unless configuration flags are changed, but advanced uses (such as manually rewriting viewport flags) make this useful. - DWORD new_style; - DWORD new_ex_style; - ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &new_style, &new_ex_style); - - // Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows) - if (vd->DwStyle != new_style || vd->DwExStyle != new_ex_style) - { - // (Optional) Update TopMost state if it changed _after_ creation - bool top_most_changed = (vd->DwExStyle & WS_EX_TOPMOST) != (new_ex_style & WS_EX_TOPMOST); - HWND insert_after = top_most_changed ? ((viewport->Flags & ImGuiViewportFlags_TopMost) ? HWND_TOPMOST : HWND_NOTOPMOST) : 0; - UINT swp_flag = top_most_changed ? 0 : SWP_NOZORDER; - - // Apply flags and position (since it is affected by flags) - vd->DwStyle = new_style; - vd->DwExStyle = new_ex_style; - ::SetWindowLong(vd->Hwnd, GWL_STYLE, vd->DwStyle); - ::SetWindowLong(vd->Hwnd, GWL_EXSTYLE, vd->DwExStyle); - RECT rect = {(LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y)}; - ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen - ::SetWindowPos(vd->Hwnd, insert_after, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, swp_flag | SWP_NOACTIVATE | SWP_FRAMECHANGED); - ::ShowWindow(vd->Hwnd, SW_SHOWNA); // This is necessary when we alter the style - viewport->PlatformRequestMove = viewport->PlatformRequestResize = true; - } -} - -static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - POINT pos = {0, 0}; - ::ClientToScreen(vd->Hwnd, &pos); - return ImVec2((float)pos.x, (float)pos.y); -} - -static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - RECT rect = {(LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y}; - ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); - ::SetWindowPos(vd->Hwnd, nullptr, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); -} - -static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - RECT rect; - ::GetClientRect(vd->Hwnd, &rect); - return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top)); -} - -static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport* viewport, ImVec2 size) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - RECT rect = {0, 0, (LONG)size.x, (LONG)size.y}; - ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen - ::SetWindowPos(vd->Hwnd, nullptr, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); -} - -static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - ::BringWindowToTop(vd->Hwnd); - ::SetForegroundWindow(vd->Hwnd); - ::SetFocus(vd->Hwnd); -} - -static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - return ::GetForegroundWindow() == vd->Hwnd; -} - -static bool ImGui_ImplWin32_GetWindowMinimized(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - return ::IsIconic(vd->Hwnd) != 0; -} - -static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport* viewport, const char* title) -{ - // ::SetWindowTextA() doesn't properly handle UTF-8 so we explicitely convert our string. - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - int n = ::MultiByteToWideChar(CP_UTF8, 0, title, -1, nullptr, 0); - ImVector title_w; - title_w.resize(n); - ::MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w.Data, n); - ::SetWindowTextW(vd->Hwnd, title_w.Data); -} - -static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport* viewport, float alpha) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f); - if (alpha < 1.0f) - { - DWORD style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED; - ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, style); - ::SetLayeredWindowAttributes(vd->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA); - } - else - { - DWORD style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED; - ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, style); - } -} - -static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport* viewport) -{ - ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData; - IM_ASSERT(vd->Hwnd != 0); - return ImGui_ImplWin32_GetDpiScaleForHwnd(vd->Hwnd); -} - -// FIXME-DPI: Testing DPI related ideas -static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport* viewport) -{ - (void)viewport; -#if 0 - ImGuiStyle default_style; - //default_style.WindowPadding = ImVec2(0, 0); - //default_style.WindowBorderSize = 0.0f; - //default_style.ItemSpacing.y = 3.0f; - //default_style.FramePadding = ImVec2(0, 0); - default_style.ScaleAllSizes(viewport->DpiScale); - ImGuiStyle& style = ImGui::GetStyle(); - style = default_style; #endif + IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! + return xdpi / 96.0f; } -static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - // Allow secondary viewport WndProc to be called regardless of current context - ImGuiContext* hwnd_ctx = (ImGuiContext*)::GetProp(hWnd, _T("IMGUI_CONTEXT")); - ImGuiContext* prev_ctx = ImGui::GetCurrentContext(); - if (hwnd_ctx != prev_ctx && hwnd_ctx != NULL) - ImGui::SetCurrentContext(hwnd_ctx); - - LRESULT result = 0; - if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) - result = true; - else if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle((void*)hWnd)) - { - switch (msg) - { - case WM_CLOSE: viewport->PlatformRequestClose = true; break; - case WM_MOVE: viewport->PlatformRequestMove = true; break; - case WM_SIZE: viewport->PlatformRequestResize = true; break; - case WM_MOUSEACTIVATE: - if (viewport->Flags & ImGuiViewportFlags_NoFocusOnClick) - result = MA_NOACTIVATE; - break; - case WM_NCHITTEST: - // Let mouse pass-through the window. This will allow the backend to call io.AddMouseViewportEvent() correctly. (which is optional). - // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging. - // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in - // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system. - if (viewport->Flags & ImGuiViewportFlags_NoInputs) - result = HTTRANSPARENT; - break; - } - } - if (result == 0) - result = DefWindowProc(hWnd, msg, wParam, lParam); - if (hwnd_ctx != prev_ctx && hwnd_ctx != NULL) - ImGui::SetCurrentContext(prev_ctx); - return result; -} - -static void ImGui_ImplWin32_InitPlatformInterface(bool platform_has_own_dc) -{ - WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_HREDRAW | CS_VREDRAW | (platform_has_own_dc ? CS_OWNDC : 0); - wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = ::GetModuleHandle(nullptr); - wcex.hIcon = nullptr; - wcex.hCursor = nullptr; - wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1); - wcex.lpszMenuName = nullptr; - wcex.lpszClassName = _T("ImGui Platform"); - wcex.hIconSm = nullptr; - ::RegisterClassEx(&wcex); - - ImGui_ImplWin32_UpdateMonitors(); - - // Register platform interface (will be coupled with a renderer interface) - ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); - platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow; - platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow; - platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow; - platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos; - platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos; - platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize; - platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize; - platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus; - platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus; - platform_io.Platform_GetWindowMinimized = ImGui_ImplWin32_GetWindowMinimized; - platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle; - platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha; - platform_io.Platform_UpdateWindow = ImGui_ImplWin32_UpdateWindow; - platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale; // FIXME-DPI - platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI - - // Register main window handle (which is owned by the main application, not by us) - // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports. - ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - ImGui_ImplWin32_ViewportData* vd = IM_NEW(ImGui_ImplWin32_ViewportData)(); - vd->Hwnd = bd->hWnd; - vd->HwndOwned = false; - main_viewport->PlatformUserData = vd; - main_viewport->PlatformHandle = (void*)bd->hWnd; -} - -static void ImGui_ImplWin32_ShutdownPlatformInterface() +float ImGui_ImplWin32_GetDpiScaleForHwnd(HWND ahWnd) { - ::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(nullptr)); - ImGui::DestroyPlatformWindows(); + HMONITOR monitor = ::MonitorFromWindow(ahWnd, MONITOR_DEFAULTTONEAREST); + return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); } //--------------------------------------------------------------------------------------------------------- - -#if defined(__GNUC__) -#pragma GCC diagnostic pop -#endif -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - -#endif // #ifndef IMGUI_DISABLE diff --git a/src/imgui_impl/win32.h b/src/imgui_impl/win32.h index ea25e954..be3d8889 100644 --- a/src/imgui_impl/win32.h +++ b/src/imgui_impl/win32.h @@ -1,48 +1,40 @@ -// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) -// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. -// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= +// ImGuiConfigFlags_NoMouseCursorChange'. [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. +// ImGui::IsKeyPressed(VK_SPACE). [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= +// ImGuiConfigFlags_NavEnableGamepad'. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. -// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// Learn about Dear ImGui: -// - FAQ https://dearimgui.com/faq -// - Getting Started https://dearimgui.com/getting-started -// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). -// - Introduction, links and more at the top of imgui.cpp +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. +// Read online: https://github.com/ocornut/imgui/tree/master/docs #pragma once -#include "imgui.h" // IMGUI_IMPL_API -#ifndef IMGUI_DISABLE +#include "imgui.h" // IMGUI_IMPL_API -// Follow "Getting Started" link and check examples/ folder to learn about using backends! -IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); -IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); -IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(SIZE aOutSize); +IMGUI_IMPL_API bool ImGui_ImplWin32_Init(HWND ahWnd); +IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(SIZE aOutSize); + +// Configuration +// - Disable gamepad support or linking with xinput.lib +// #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD +// #define IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT // Win32 message handler your application need to call. -extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND ahWnd, UINT auMsg, WPARAM awParam, LPARAM alParam); // DPI-related helpers (optional) // - Use to enable DPI awareness without having to create an application manifest. // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. -// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. -// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, -// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. -IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); -IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd -IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor - -// Transparency related helpers (optional) [experimental] -// - Use to enable alpha compositing transparency with the desktop. -// - Use together with e.g. clearing your framebuffer with zero-alpha. -IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd - -#endif // #ifndef IMGUI_DISABLE \ No newline at end of file +// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), +// etc. +// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at +// runtime, neither we want to require the user to have. So we dynamically select and load those functions to avoid +// dependencies. +IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(HWND ahWnd); +IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(HMONITOR ahMonitor); diff --git a/src/overlay/widgets/Bindings.cpp b/src/overlay/widgets/Bindings.cpp index b2c14fe3..d6ba703a 100644 --- a/src/overlay/widgets/Bindings.cpp +++ b/src/overlay/widgets/Bindings.cpp @@ -465,7 +465,7 @@ void Bindings::UpdateAndDrawModBindings(const std::string& acModName, TiltedPhoq if (!headerOpen) return; - ImGui::TreePush((void*)nullptr); + ImGui::TreePush(); if (aHotkeyCount > 0) { diff --git a/src/overlay/widgets/Settings.cpp b/src/overlay/widgets/Settings.cpp index 06d8335f..eaf2cc0a 100644 --- a/src/overlay/widgets/Settings.cpp +++ b/src/overlay/widgets/Settings.cpp @@ -16,7 +16,8 @@ Settings::Settings(Options& aOptions, LuaVM& aVm) WidgetResult Settings::OnPopup() { - const auto ret = UnsavedChangesPopup("Settings", m_openChangesModal, m_madeChanges, [this] { Save(); }, [this] { Load(); }); + const auto ret = UnsavedChangesPopup( + "Settings", m_openChangesModal, m_madeChanges, [this] { Save(); }, [this] { Load(); }); m_madeChanges = ret == TChangedCBResult::CHANGED; m_popupResult = ret; @@ -53,7 +54,7 @@ void Settings::OnUpdate() m_madeChanges = false; if (ImGui::CollapsingHeader("Patches", ImGuiTreeNodeFlags_DefaultOpen)) { - ImGui::TreePush("##PATCHES"); + ImGui::TreePush(); if (ImGui::BeginTable("##SETTINGS_PATCHES", 2, ImGuiTableFlags_Sortable | ImGuiTableFlags_SizingStretchSame, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) { const auto& patchesSettings = m_options.Patches; @@ -77,9 +78,7 @@ void Settings::OnUpdate() UpdateAndDrawSetting( "Disable Boundary Teleport", "Allows players to access out-of-bounds locations (requires restart to take effect).", m_patches.DisableBoundaryTeleport, patchesSettings.DisableBoundaryTeleport); - UpdateAndDrawSetting( - "Disable V-Sync (Windows 7 only)", "Disables VSync on Windows 7 to bypass the 60 FPS limit (requires restart to take effect).", m_patches.DisableWin7Vsync, - patchesSettings.DisableWin7Vsync); + UpdateAndDrawSetting("Disable V-Sync (Windows 7 only)", "Disables VSync on Windows 7 to bypass the 60 FPS limit (requires restart to take effect).", m_patches.DisableWin7Vsync, patchesSettings.DisableWin7Vsync); UpdateAndDrawSetting( "Fix Minimap Flicker", "Fixes Minimap flicker caused by some mods (requires restart to take effect).", m_patches.MinimapFlicker, patchesSettings.MinimapFlicker); @@ -90,7 +89,7 @@ void Settings::OnUpdate() } if (ImGui::CollapsingHeader("CET Development Settings", ImGuiTreeNodeFlags_DefaultOpen)) { - ImGui::TreePush("##DEV"); + ImGui::TreePush(); if (ImGui::BeginTable("##SETTINGS_DEV", 2, ImGuiTableFlags_Sortable | ImGuiTableFlags_SizingStretchSame, ImVec2(-ImGui::GetStyle().IndentSpacing, 0))) { const auto& developerSettings = m_options.Developer; @@ -109,10 +108,8 @@ void Settings::OnUpdate() "Dump Game Options", "Dumps all game options into main log file (requires restart to take effect).", m_developer.DumpGameOptions, developerSettings.DumpGameOptions); UpdateAndDrawSetting( - "Enable JIT for Lua", - "Enables JIT compiler for Lua VM, which may majorly speed up the mods. Disable it in case you experience issues as a troubleshooting step (requires restart to " - "take effect).", - m_developer.EnableJIT, developerSettings.EnableJIT); + "Enable JIT for Lua", "Enables JIT compiler for Lua VM, which may majorly speed up the mods. Disable it in case you experience issues as a troubleshooting step (requires restart to take effect).", m_developer.EnableJIT, + developerSettings.EnableJIT); ImGui::EndTable(); } diff --git a/src/sol_imgui/README.md b/src/sol_imgui/README.md index ba985122..3f3309e6 100644 --- a/src/sol_imgui/README.md +++ b/src/sol_imgui/README.md @@ -32,17 +32,12 @@ You can find all the supported functions and overloads below. ## Child Windows ```lua -- ImGui.BeginChild(...) - -- Parameters: text (name), float (size_x) [O], float (size_y) [O], ImGuiChildFlags (child_flags) [O], ImGuiWindowFlags (window_flags) [O] + -- Parameters: text (name), float (size_x) [O], float (size_y) [O], bool (border) [O], ImGuiWindowFlags (flags) [O] -- Returns: bool (shouldDraw) -- Overloads shouldDraw = ImGui.BeginChild("Name") shouldDraw = ImGui.BeginChild("Name", 100) shouldDraw = ImGui.BeginChild("Name", 100, 200) - shouldDraw = ImGui.BeginChild("Name", 100, 200, ImGuiChildFlags.Border) - shouldDraw = ImGui.BeginChild("Name", 100, 200, ImGuiChildFlags.Border, ImGuiWindowFlags.NoMove) - - -- The following will still work, but are considered deprecated and the newer overloads above should be used. - -- Parameters: text (name), float (size_x) [O], float (size_y) [O], bool (border) [O], ImGuiWindowFlags (flags) [O] shouldDraw = ImGui.BeginChild("Name", 100, 200, true) shouldDraw = ImGui.BeginChild("Name", 100, 200, true, ImGuiWindowFlags.NoMove) @@ -277,13 +272,6 @@ You can find all the supported functions and overloads below. ImGui.PopStyleVar() ImGui.PopStyleVar(2) - -- ImGui.PushItemFlag(...) - -- Parameters: int/ImGuiItemFlags (option), bool (enabled) - ImGui.PushItemFlag(ImGuiItemFlags.NoTabStop, true) - - -- ImGui.PopItemFlag() - ImGui.PopItemFlag() - -- ImGui.GetStyleColorVec4(...) -- Parameters: ImGuiCol (idx) -- Returns: float (color_r), float (color_g), float (color_b), float (color_a) @@ -333,12 +321,12 @@ You can find all the supported functions and overloads below. -- ImGui.PopTextWrapPos() ImGui.PopTextWrapPos() - -- ImGui.PushTabStop(...) - -- Parameters: bool (tab_stop) - ImGui.PushTabStop(true) + -- ImGui.PushAllowKeyboardFocus(...) + -- Parameters: bool (allow_keyboard_focus) + ImGui.PushAllowKeyboardFocus(true) - -- ImGui.PopTabStop() - ImGui.PopTabStop() + -- ImGui.PopAllowKeyboardFocus() + ImGui.PopAllowKeyboardFocus() -- ImGui.PushButtonRepeat(...) -- Parameters: bool (repeat) @@ -346,15 +334,6 @@ You can find all the supported functions and overloads below. -- ImGui.PopButtonRepeat() ImGui.PopButtonRepeat() - - -- DEPRECATED - -- ImGui.PushAllowKeyboardFocus(...) - -- Parameters: bool (allow_keyboard_focus) - ImGui.PushAllowKeyboardFocus(true) - - -- DEPRECATED - -- ImGui.PopAllowKeyboardFocus() - ImGui.PopAllowKeyboardFocus() ``` ## Cursor / Layout @@ -1030,7 +1009,6 @@ selected, activated = ImGui.MenuItem("Label", "ALT+F4", selected, true) ## Tooltips ```lua - -- returns bool (n/a) [value will always be true in current implementations] -- ImGui.BeginTooltip() ImGui.BeginTooltip() @@ -1373,10 +1351,6 @@ selected, activated = ImGui.MenuItem("Label", "ALT+F4", selected, true) -- Returns: float (x), float (y) x, y = ImGui.GetItemRectSize() - -- ImGuiSetNextItemAllowOverlap() - ImGui.ImGuiSetNextItemAllowOverlap() - - -- DEPRECATED -- ImGui.SetItemAllowOverlap() ImGui.SetItemAllowOverlap() ``` @@ -1404,7 +1378,6 @@ selected, activated = ImGui.MenuItem("Label", "ALT+F4", selected, true) -- Returns: text (style_color_name) style_color_name = ImGui.GetStyleColorName(ImGuiCol.Text) - -- DEPRECATED (use BeginChild() with ImGuiChildFlags.FrameStyle!) -- ImGui.BeginChildFrame(...) -- Parameters: unsigned int (id), float (size_x), float (size_y), ImGuiWindowFlags (flags) [O] -- Returns: bool (open) @@ -1453,38 +1426,33 @@ selected, activated = ImGui.MenuItem("Label", "ALT+F4", selected, true) ## Inputs Utilities: Keyboard ```lua + -- ImGui.GetKeyIndex(...) + -- Parameters: ImGuiKey (key) + -- Returns: int (index) + index = ImGui.GetKeyIndex(ImGuiKey.Tab) + -- ImGui.IsKeyDown(...) - -- Parameters: int/ImGuiKey (key_index) + -- Parameters: int (key_index) -- Returns: bool (down) down = ImGui.IsKeyDown(0) - down = ImGui.IsKeyDown(ImGuiKey.Z) -- ImGui.IsKeyPressed(...) - -- Parameters: int/ImGuiKey (key_index), bool (repeat) [O] + -- Parameters: int (key_index), bool (repeat) [O] -- Returns: bool (pressed) -- Overloads pressed = ImGui.IsKeyPressed(0) - pressed = ImGui.IsKeyPressed(ImGuiKey.Z) pressed = ImGui.IsKeyPressed(0, true) - pressed = ImGui.IsKeyPressed(ImGuiKey.Z, true) -- ImGui.IsKeyReleased(...) - -- Parameters: int/ImGuiKey (key_index) + -- Parameters: int (key_index) -- Returns: bool (released) released = ImGui.IsKeyReleased(0) - released = ImGui.IsKeyReleased(ImGuiKey.Z) -- ImGui.GetKeyPressedAmount(...) - -- Parameters: int/ImGuiKey (key_index), float (repeat_delay), float (rate) + -- Parameters: int (key_index), float (repeat_delay), float (rate) -- Returns: int (pressed_amount) pressed_amount = ImGui.GetKeyPressedAmount(0, 0.5, 5) - pressed_amount = ImGui.GetKeyPressedAmount(ImGuiKey.Z, 0.5, 5) - - -- ImGui.SetNextFrameWantCaptureKeyboard(...) - -- Parameters bool (want_capture_keyboard_valvue) - ImGui.SetNextFrameWantCaptureKeyboard(true) - - -- DEPRECATED (use ImGui.SetNextFrameWantCaptureKeyboard()) + -- ImGui.CaptureKeyboardFromApp(...) -- Parameters: bool (want_capture_keyboard_value) [O] -- Overloads @@ -1562,12 +1530,7 @@ selected, activated = ImGui.MenuItem("Label", "ALT+F4", selected, true) -- ImGui.SetMouseCursor(...) -- Parameters: ImGuiMouseCursor (cursor_type) ImGui.SetMouseCursor(ImGuiMouseCursor.Hand) - - -- ImGui.SetNextFrameWantCaptureMouse(...) - -- Parameters: bool (want_capture_mouse_value) - ImGui.SetNextFrameWantCaptureMouse(true) - - -- DEPRECATED (Use ImGui.SetNextFrameWantCaptureMouse()) + -- ImGui.CaptureMouseFromApp() -- Parameters: bool (want_capture_mouse_value) [O] -- Overloads diff --git a/src/sol_imgui/sol_imgui.h b/src/sol_imgui/sol_imgui.h index f1dcbef9..5624f292 100644 --- a/src/sol_imgui/sol_imgui.h +++ b/src/sol_imgui/sol_imgui.h @@ -43,17 +43,6 @@ inline bool BeginChild(const std::string& name, float sizeX, float sizeY) { return ImGui::BeginChild(name.c_str(), {sizeX, sizeY}); } -inline bool BeginChild(const std::string& name, float sizeX, float sizeY, int child_flags) -{ - return ImGui::BeginChild(name.c_str(), {sizeX, sizeY}, static_cast(child_flags)); -} - -inline bool BeginChild(const std::string& name, float sizeX, float sizeY, int child_flags, int window_flags) -{ - return ImGui::BeginChild(name.c_str(), {sizeX, sizeY}, static_cast(child_flags), static_cast(window_flags)); -} - -// DEPRECATED inline bool BeginChild(const std::string& name, float sizeX, float sizeY, bool border) { return ImGui::BeginChild(name.c_str(), {sizeX, sizeY}, border); @@ -62,7 +51,6 @@ inline bool BeginChild(const std::string& name, float sizeX, float sizeY, bool b { return ImGui::BeginChild(name.c_str(), {sizeX, sizeY}, border, flags); } - inline void EndChild() { ImGui::EndChild(); @@ -243,11 +231,9 @@ inline std::tuple GetWindowContentRegionMax() const auto vec2{ImGui::GetWindowContentRegionMax()}; return std::make_tuple(vec2.x, vec2.y); } - -// DEPRECATED AND REMOVED IN IMGUI. KEEPING SO AMM DOESN'T BREAK ._. inline float GetWindowContentRegionWidth() { - return (ImGui::GetWindowContentRegionMax().x - ImGui::GetWindowContentRegionMin().x); + return ImGui::GetWindowContentRegionWidth(); } // Windows Scrolling @@ -351,16 +337,6 @@ inline void PopStyleVar(int count) { ImGui::PopStyleVar(count); } - -inline void PushItemFlag(int option, bool enabled) -{ - ImGui::PushItemFlag(static_cast(option), enabled); -} -inline void PopItemFlag() -{ - ImGui::PopItemFlag(); -} - inline std::tuple GetStyleColorVec4(int idx) { const auto col{ImGui::GetStyleColorVec4(idx)}; @@ -423,8 +399,6 @@ inline void PopTextWrapPos() { ImGui::PopTextWrapPos(); } - -// DEPRECATED in 1.91, but still allowed. Replaced with PushTabStop/PopTabStop inline void PushAllowKeyboardFocus(bool allowKeyboardFocus) { ImGui::PushAllowKeyboardFocus(allowKeyboardFocus); @@ -433,16 +407,6 @@ inline void PopAllowKeyboardFocus() { ImGui::PopAllowKeyboardFocus(); } - -inline void PushTabStop(bool tab_stop) -{ - ImGui::PushTabStop(tab_stop); -} -inline void PopTabStop() -{ - ImGui::PopTabStop(); -} - inline void PushButtonRepeat(bool repeat) { ImGui::PushButtonRepeat(repeat); @@ -2106,9 +2070,9 @@ inline std::tuple MenuItem(const std::string& label, const std::stri } // Tooltips -inline bool BeginTooltip() +inline void BeginTooltip() { - return ImGui::BeginTooltip(); + ImGui::BeginTooltip(); } inline void EndTooltip() { @@ -2537,18 +2501,11 @@ inline std::tuple GetItemRectSize() const auto vec2{ImGui::GetItemRectSize()}; return std::make_tuple(vec2.x, vec2.y); } - -// DEPRECATED inline void SetItemAllowOverlap() { ImGui::SetItemAllowOverlap(); } -inline void SetNextItemAllowOverlap() -{ - ImGui::SetNextItemAllowOverlap(); -} - // Miscellaneous Utilities inline bool IsRectVisible(float sizeX, float sizeY) { @@ -2580,8 +2537,6 @@ inline std::string GetStyleColorName(int idx) return std::string(ImGui::GetStyleColorName(idx)); } /* TODO: SetStateStorage(), GetStateStorage(), CalcListClipping() ==> UNSUPPORTED */ - -// DEPRECATED inline bool BeginChildFrame(unsigned int id, float sizeX, float sizeY) { return ImGui::BeginChildFrame(id, {sizeX, sizeY}); @@ -2590,7 +2545,6 @@ inline bool BeginChildFrame(unsigned int id, float sizeX, float sizeY, int flags { return ImGui::BeginChildFrame(id, {sizeX, sizeY}, flags); } - inline void EndChildFrame() { return ImGui::EndChildFrame(); @@ -2647,43 +2601,37 @@ inline std::tuple ColorConvertHSVtoRGB(float h, float s, fl } // Inputs Utilities: Keyboard +inline int GetKeyIndex(int imgui_key) +{ + return ImGui::GetKeyIndex(static_cast(imgui_key)); +} inline bool IsKeyDown(int user_key_index) { - return ImGui::IsKeyDown(static_cast(user_key_index)); + return ImGui::IsKeyDown(user_key_index); } inline bool IsKeyPressed(int user_key_index) { - return ImGui::IsKeyPressed(static_cast(user_key_index)); + return ImGui::IsKeyPressed(user_key_index); } inline bool IsKeyPressed(int user_key_index, bool repeat) { - return ImGui::IsKeyPressed(static_cast(user_key_index), repeat); + return ImGui::IsKeyPressed(user_key_index, repeat); } inline bool IsKeyReleased(int user_key_index) { - return ImGui::IsKeyReleased(static_cast(user_key_index)); + return ImGui::IsKeyReleased(user_key_index); } inline int GetKeyPressedAmount(int key_index, float repeat_delay, float rate) { - return ImGui::GetKeyPressedAmount(static_cast(key_index), repeat_delay, rate); -} -inline void SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard_value) -{ - ImGui::SetNextFrameWantCaptureKeyboard(want_capture_keyboard_value); -} - -// DEPRECATED -inline int GetKeyIndex(int imgui_key) -{ - return ImGui::GetKeyIndex(static_cast(imgui_key)); + return ImGui::GetKeyPressedAmount(key_index, repeat_delay, rate); } inline void CaptureKeyboardFromApp() { - ImGui::SetNextFrameWantCaptureKeyboard(true); + ImGui::CaptureKeyboardFromApp(); } inline void CaptureKeyboardFromApp(bool want_capture_keyboard_value) { - ImGui::SetNextFrameWantCaptureKeyboard(want_capture_keyboard_value); + ImGui::CaptureKeyboardFromApp(want_capture_keyboard_value); } // Inputs Utilities: Mouse @@ -2770,19 +2718,13 @@ inline void SetMouseCursor(int cursor_type) { ImGui::SetMouseCursor(static_cast(cursor_type)); } -inline void SetNextFrameWantCaptureMouse(bool want_capture_mouse_value) -{ - ImGui::SetNextFrameWantCaptureMouse(want_capture_mouse_value); -} - -// DEPRECATED inline void CaptureMouseFromApp() { - ImGui::SetNextFrameWantCaptureMouse(true); + ImGui::CaptureMouseFromApp(); } inline void CaptureMouseFromApp(bool want_capture_mouse_value) { - ImGui::SetNextFrameWantCaptureMouse(want_capture_mouse_value); + ImGui::CaptureMouseFromApp(want_capture_mouse_value); } // Clipboard Utilities @@ -2971,31 +2913,14 @@ inline void InitEnums(sol::table luaGlobals) ImGuiWindowFlags_AlwaysAutoResize, "NoBackground", ImGuiWindowFlags_NoBackground, "NoSavedSettings", ImGuiWindowFlags_NoSavedSettings, "NoMouseInputs", ImGuiWindowFlags_NoMouseInputs, "MenuBar", ImGuiWindowFlags_MenuBar, "HorizontalScrollbar", ImGuiWindowFlags_HorizontalScrollbar, "NoFocusOnAppearing", ImGuiWindowFlags_NoFocusOnAppearing, "NoBringToFrontOnFocus", ImGuiWindowFlags_NoBringToFrontOnFocus, "AlwaysVerticalScrollbar", ImGuiWindowFlags_AlwaysVerticalScrollbar, - "AlwaysHorizontalScrollbar", ImGuiWindowFlags_AlwaysHorizontalScrollbar, "NoNavInputs", ImGuiWindowFlags_NoNavInputs, "NoNavFocus", ImGuiWindowFlags_NoNavFocus, - "UnsavedDocument", ImGuiWindowFlags_UnsavedDocument, "NoNav", ImGuiWindowFlags_NoNav, "NoDecoration", ImGuiWindowFlags_NoDecoration, "NoInputs", ImGuiWindowFlags_NoInputs, - // [Internal] - "ChildWindow", ImGuiWindowFlags_ChildWindow, "Tooltip", ImGuiWindowFlags_Tooltip, "Popup", ImGuiWindowFlags_Popup, "Modal", ImGuiWindowFlags_Modal, "ChildMenu", - ImGuiWindowFlags_ChildMenu, - - // DEPRECATED - "AlwaysUseWindowPadding", ImGuiWindowFlags_AlwaysUseWindowPadding, + "AlwaysHorizontalScrollbar", ImGuiWindowFlags_AlwaysHorizontalScrollbar, "AlwaysUseWindowPadding", ImGuiWindowFlags_AlwaysUseWindowPadding, "NoNavInputs", + ImGuiWindowFlags_NoNavInputs, "NoNavFocus", ImGuiWindowFlags_NoNavFocus, "UnsavedDocument", ImGuiWindowFlags_UnsavedDocument, "NoNav", ImGuiWindowFlags_NoNav, + "NoDecoration", ImGuiWindowFlags_NoDecoration, "NoInputs", ImGuiWindowFlags_NoInputs, // [Internal] - "NavFlattened", ImGuiWindowFlags_NavFlattened); + "NavFlattened", ImGuiWindowFlags_NavFlattened, "ChildWindow", ImGuiWindowFlags_ChildWindow, "Tooltip", ImGuiWindowFlags_Tooltip, "Popup", ImGuiWindowFlags_Popup, "Modal", + ImGuiWindowFlags_Modal, "ChildMenu", ImGuiWindowFlags_ChildMenu); #pragma endregion Window Flags -#pragma region Child Flags - luaGlobals.new_enum( - "ImGuiChildFlags", "None", ImGuiChildFlags_None, "Borders", ImGuiChildFlags_Borders, "AlwaysUseWindowPadding", ImGuiChildFlags_AlwaysUseWindowPadding, "ResizeX", - ImGuiChildFlags_ResizeX, "ResizeY", ImGuiChildFlags_ResizeY, "AutoResizeX", ImGuiChildFlags_AutoResizeX, "AutoResizeY", ImGuiChildFlags_AutoResizeY, "AlwaysAutoResize", - ImGuiChildFlags_AlwaysAutoResize, "FrameStyle", ImGuiChildFlags_FrameStyle, "NavFlattened", ImGuiChildFlags_NavFlattened); -#pragma endregion Child Flags - -#pragma region Item Flags - luaGlobals.new_enum( - "ImGuiItemFlags", "None", ImGuiItemFlags_None, "NoTabStop", ImGuiItemFlags_NoTabStop, "NoNav", ImGuiItemFlags_NoNav, "NoNavDefaultFocus", ImGuiItemFlags_NoNavDefaultFocus, - "ButtonRepeat", ImGuiItemFlags_ButtonRepeat, "AutoClosePopups", ImGuiItemFlags_AutoClosePopups); -#pragma endregion Item Flags - #pragma region Focused Flags luaGlobals.new_enum( "ImGuiFocusedFlags", "None", ImGuiFocusedFlags_None, "ChildWindows", ImGuiFocusedFlags_ChildWindows, "RootWindow", ImGuiFocusedFlags_RootWindow, "AnyWindow", @@ -3007,9 +2932,7 @@ inline void InitEnums(sol::table luaGlobals) "ImGuiHoveredFlags", "None", ImGuiHoveredFlags_None, "ChildWindows", ImGuiHoveredFlags_ChildWindows, "RootWindow", ImGuiHoveredFlags_RootWindow, "AnyWindow", ImGuiHoveredFlags_AnyWindow, "AllowWhenBlockedByPopup", ImGuiHoveredFlags_AllowWhenBlockedByPopup, "AllowWhenBlockedByActiveItem", ImGuiHoveredFlags_AllowWhenBlockedByActiveItem, "AllowWhenOverlapped", ImGuiHoveredFlags_AllowWhenOverlapped, "AllowWhenDisabled", ImGuiHoveredFlags_AllowWhenDisabled, - "RectOnly", ImGuiHoveredFlags_RectOnly, "RootAndChildWindows", ImGuiHoveredFlags_RootAndChildWindows, "ForTooltip", ImGuiHoveredFlags_ForTooltip, "Stationary", - ImGuiHoveredFlags_Stationary, "DelayNone", ImGuiHoveredFlags_DelayNone, "DelayShort", ImGuiHoveredFlags_DelayShort, "DelayNormal", ImGuiHoveredFlags_DelayNormal, - "NoSharedDelay", ImGuiHoveredFlags_NoSharedDelay); + "RectOnly", ImGuiHoveredFlags_RectOnly, "RootAndChildWindows", ImGuiHoveredFlags_RootAndChildWindows); #pragma endregion Hovered Flags #pragma region Cond @@ -3026,17 +2949,12 @@ inline void InitEnums(sol::table luaGlobals) "CheckMark", ImGuiCol_CheckMark, "SliderGrab", ImGuiCol_SliderGrab, "SliderGrabActive", ImGuiCol_SliderGrabActive, "Button", ImGuiCol_Button, "ButtonHovered", ImGuiCol_ButtonHovered, "ButtonActive", ImGuiCol_ButtonActive, "Header", ImGuiCol_Header, "HeaderHovered", ImGuiCol_HeaderHovered, "HeaderActive", ImGuiCol_HeaderActive, "Separator", ImGuiCol_Separator, "SeparatorHovered", ImGuiCol_SeparatorHovered, "SeparatorActive", ImGuiCol_SeparatorActive, "ResizeGrip", ImGuiCol_ResizeGrip, - "ResizeGripHovered", ImGuiCol_ResizeGripHovered, "ResizeGripActive", ImGuiCol_ResizeGripActive, "Tab", ImGuiCol_Tab, "TabHovered", ImGuiCol_TabHovered, "TabSelected", - ImGuiCol_TabSelected, "TabDimmed", ImGuiCol_TabDimmed, "TabDimmedSelected", ImGuiCol_TabDimmedSelected, "PlotLines", ImGuiCol_PlotLines, "PlotLinesHovered", + "ResizeGripHovered", ImGuiCol_ResizeGripHovered, "ResizeGripActive", ImGuiCol_ResizeGripActive, "Tab", ImGuiCol_Tab, "TabHovered", ImGuiCol_TabHovered, "TabActive", + ImGuiCol_TabActive, "TabUnfocused", ImGuiCol_TabUnfocused, "TabUnfocusedActive", ImGuiCol_TabUnfocusedActive, "PlotLines", ImGuiCol_PlotLines, "PlotLinesHovered", ImGuiCol_PlotLinesHovered, "PlotHistogram", ImGuiCol_PlotHistogram, "PlotHistogramHovered", ImGuiCol_PlotHistogramHovered, "TableHeaderBg", ImGuiCol_TableHeaderBg, "TableBorderStrong", ImGuiCol_TableBorderStrong, "TableBorderLight", ImGuiCol_TableBorderLight, "TableRowBg", ImGuiCol_TableRowBg, "TableRowBgAlt", ImGuiCol_TableRowBgAlt, "TextSelectedBg", ImGuiCol_TextSelectedBg, "DragDropTarget", ImGuiCol_DragDropTarget, "NavHighlight", ImGuiCol_NavHighlight, "NavWindowingHighlight", - ImGuiCol_NavWindowingHighlight, "NavWindowingDimBg", ImGuiCol_NavWindowingDimBg, "ModalWindowDimBg", ImGuiCol_ModalWindowDimBg, - - // DEPRECATED - "TabActive", ImGuiCol_TabActive, "TabUnfocused", ImGuiCol_TabUnfocused, "TabUnfocusedActive", ImGuiCol_TabUnfocusedActive, - - "COUNT", ImGuiCol_COUNT); + ImGuiCol_NavWindowingHighlight, "NavWindowingDimBg", ImGuiCol_NavWindowingDimBg, "ModalWindowDimBg", ImGuiCol_ModalWindowDimBg, "COUNT", ImGuiCol_COUNT); #pragma endregion Col #pragma region Style @@ -3076,7 +2994,7 @@ inline void InitEnums(sol::table luaGlobals) #pragma region Slider Flags luaGlobals.new_enum( - "ImGuiSliderFlags", "None", ImGuiSliderFlags_None, "AlwaysClamp", ImGuiSliderFlags_AlwaysClamp, "Logarithmic", ImGuiSliderFlags_Logarithmic, "NoRoundToFormat", + "ImGuiSliderFlags", "None", ImGuiSliderFlags_None, "ClampOnInput", ImGuiSliderFlags_ClampOnInput, "Logarithmic", ImGuiSliderFlags_Logarithmic, "NoRoundToFormat", ImGuiSliderFlags_NoRoundToFormat, "NoInput", ImGuiSliderFlags_NoInput); #pragma endregion Slider Flags @@ -3100,32 +3018,25 @@ inline void InitEnums(sol::table luaGlobals) #pragma region TreeNode Flags luaGlobals.new_enum( - "ImGuiTreeNodeFlags", "None", ImGuiTreeNodeFlags_None, "Selected", ImGuiTreeNodeFlags_Selected, "Framed", ImGuiTreeNodeFlags_Framed, "AllowOverlap", - ImGuiTreeNodeFlags_AllowOverlap, "NoTreePushOnOpen", ImGuiTreeNodeFlags_NoTreePushOnOpen, "NoAutoOpenOnLog", ImGuiTreeNodeFlags_NoAutoOpenOnLog, "DefaultOpen", + "ImGuiTreeNodeFlags", "None", ImGuiTreeNodeFlags_None, "Selected", ImGuiTreeNodeFlags_Selected, "Framed", ImGuiTreeNodeFlags_Framed, "AllowItemOverlap", + ImGuiTreeNodeFlags_AllowItemOverlap, "NoTreePushOnOpen", ImGuiTreeNodeFlags_NoTreePushOnOpen, "NoAutoOpenOnLog", ImGuiTreeNodeFlags_NoAutoOpenOnLog, "DefaultOpen", ImGuiTreeNodeFlags_DefaultOpen, "OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick, "OpenOnArrow", ImGuiTreeNodeFlags_OpenOnArrow, "Leaf", ImGuiTreeNodeFlags_Leaf, "Bullet", ImGuiTreeNodeFlags_Bullet, "FramePadding", ImGuiTreeNodeFlags_FramePadding, "SpanAvailWidth", ImGuiTreeNodeFlags_SpanAvailWidth, "SpanFullWidth", - ImGuiTreeNodeFlags_SpanFullWidth, "NavLeftJumpsBackHere", ImGuiTreeNodeFlags_NavLeftJumpsBackHere, "CollapsingHeader", ImGuiTreeNodeFlags_CollapsingHeader, - "AllowItemOverlap", ImGuiTreeNodeFlags_AllowItemOverlap // DEPRECATED - - ); + ImGuiTreeNodeFlags_SpanFullWidth, "NavLeftJumpsBackHere", ImGuiTreeNodeFlags_NavLeftJumpsBackHere, "CollapsingHeader", ImGuiTreeNodeFlags_CollapsingHeader); #pragma endregion TreeNode Flags #pragma region Selectable Flags luaGlobals.new_enum( - "ImGuiSelectableFlags", "None", ImGuiSelectableFlags_None, "NoAutoClosePopups", ImGuiSelectableFlags_NoAutoClosePopups, "SpanAllColumns", - ImGuiSelectableFlags_SpanAllColumns, "AllowDoubleClick", ImGuiSelectableFlags_AllowDoubleClick, "Disabled", ImGuiSelectableFlags_Disabled, "AllowOverlap", - ImGuiSelectableFlags_AllowOverlap, - - // DEPRECATED - "DontClosePopups", ImGuiSelectableFlags_DontClosePopups, "AllowItemOverlap", ImGuiSelectableFlags_AllowItemOverlap); + "ImGuiSelectableFlags", "None", ImGuiSelectableFlags_None, "DontClosePopups", ImGuiSelectableFlags_DontClosePopups, "SpanAllColumns", ImGuiSelectableFlags_SpanAllColumns, + "AllowDoubleClick", ImGuiSelectableFlags_AllowDoubleClick, "Disabled", ImGuiSelectableFlags_Disabled, "AllowItemOverlap", ImGuiSelectableFlags_AllowItemOverlap); #pragma endregion Selectable Flags #pragma region Popup Flags luaGlobals.new_enum( "ImGuiPopupFlags", "None", ImGuiPopupFlags_None, "MouseButtonLeft", ImGuiPopupFlags_MouseButtonLeft, "MouseButtonRight", ImGuiPopupFlags_MouseButtonRight, - "MouseButtonMiddle", ImGuiPopupFlags_MouseButtonMiddle, "MouseButtonMask_", ImGuiPopupFlags_MouseButtonMask_, "NoOpenOverExistingPopup", - ImGuiPopupFlags_NoOpenOverExistingPopup, "NoOpenOverItems", ImGuiPopupFlags_NoOpenOverItems, "AnyPopupId", ImGuiPopupFlags_AnyPopupId, "AnyPopupLevel", - ImGuiPopupFlags_AnyPopupLevel, "AnyPopup", ImGuiPopupFlags_AnyPopup); + "MouseButtonMiddle", ImGuiPopupFlags_MouseButtonMiddle, "MouseButtonMask_", ImGuiPopupFlags_MouseButtonMask_, "MouseButtonDefault_", ImGuiPopupFlags_MouseButtonDefault_, + "NoOpenOverExistingPopup", ImGuiPopupFlags_NoOpenOverExistingPopup, "NoOpenOverItems", ImGuiPopupFlags_NoOpenOverItems, "AnyPopupId", ImGuiPopupFlags_AnyPopupId, + "AnyPopupLevel", ImGuiPopupFlags_AnyPopupLevel, "AnyPopup", ImGuiPopupFlags_AnyPopup); #pragma endregion Popup Flags #pragma region Table Flags @@ -3214,27 +3125,12 @@ inline void InitEnums(sol::table luaGlobals) #pragma endregion MouseButton #pragma region Key - // TODO: consider adding gamepad options luaGlobals.new_enum( - "ImGuiKey", "None", ImGuiKey_None, "Tab", ImGuiKey_Tab, "LeftArrow", ImGuiKey_LeftArrow, "RightArrow", ImGuiKey_RightArrow, "UpArrow", ImGuiKey_UpArrow, "DownArrow", - ImGuiKey_DownArrow, "PageUp", ImGuiKey_PageUp, "PageDown", ImGuiKey_PageDown, "Home", ImGuiKey_Home, "End", ImGuiKey_End, "Insert", ImGuiKey_Insert, "Delete", - ImGuiKey_Delete, "Backspace", ImGuiKey_Backspace, "Space", ImGuiKey_Space, "Enter", ImGuiKey_Enter, "Escape", ImGuiKey_Escape, "LeftCtrl", ImGuiKey_LeftCtrl, "LeftShift", - ImGuiKey_LeftShift, "LeftAlt", ImGuiKey_LeftAlt, "LeftSuper", ImGuiKey_LeftSuper, "RightCtrl", ImGuiKey_RightCtrl, "RightShift", ImGuiKey_RightShift, "RightAlt", - ImGuiKey_RightAlt, "RightSuper", ImGuiKey_RightSuper, "Menu", ImGuiKey_Menu, "0", ImGuiKey_0, "1", ImGuiKey_1, "2", ImGuiKey_2, "3", ImGuiKey_3, "4", ImGuiKey_4, "5", - ImGuiKey_5, "6", ImGuiKey_6, "7", ImGuiKey_7, "8", ImGuiKey_8, "9", ImGuiKey_9, "A", ImGuiKey_A, "B", ImGuiKey_B, "C", ImGuiKey_C, "D", ImGuiKey_D, "E", ImGuiKey_E, "F", - ImGuiKey_F, "G", ImGuiKey_G, "H", ImGuiKey_H, "I", ImGuiKey_I, "J", ImGuiKey_J, "K", ImGuiKey_K, "L", ImGuiKey_L, "M", ImGuiKey_M, "N", ImGuiKey_N, "O", ImGuiKey_O, "P", - ImGuiKey_P, "Q", ImGuiKey_Q, "R", ImGuiKey_R, "S", ImGuiKey_S, "T", ImGuiKey_T, "U", ImGuiKey_U, "V", ImGuiKey_V, "W", ImGuiKey_W, "X", ImGuiKey_X, "Y", ImGuiKey_Y, "Z", - ImGuiKey_Z, "F1", ImGuiKey_F1, "F2", ImGuiKey_F2, "F3", ImGuiKey_F3, "F4", ImGuiKey_F4, "F5", ImGuiKey_F5, "F6", ImGuiKey_F6, "F7", ImGuiKey_F7, "F8", ImGuiKey_F8, "F9", - ImGuiKey_F9, "F10", ImGuiKey_F10, "F11", ImGuiKey_F11, "F12", ImGuiKey_F12, "F13", ImGuiKey_F13, "F14", ImGuiKey_F14, "F15", ImGuiKey_F15, "F16", ImGuiKey_F16, "F17", - ImGuiKey_F17, "F18", ImGuiKey_F18, "F19", ImGuiKey_F19, "F20", ImGuiKey_F20, "F21", ImGuiKey_F21, "F22", ImGuiKey_F22, "F23", ImGuiKey_F23, "F24", ImGuiKey_F24, - "Apostrophe", ImGuiKey_Apostrophe, "Comma", ImGuiKey_Comma, "Minus", ImGuiKey_Minus, "Period", ImGuiKey_Period, "Slash", ImGuiKey_Slash, "Semicolon", ImGuiKey_Semicolon, - "Equal", ImGuiKey_Equal, "LeftBracket", ImGuiKey_LeftBracket, "Backslash", ImGuiKey_Backslash, "RightBracket", ImGuiKey_RightBracket, "GraveAccent", ImGuiKey_GraveAccent, - "CapsLock", ImGuiKey_CapsLock, "ScrollLock", ImGuiKey_ScrollLock, "NumLock", ImGuiKey_NumLock, "PrintScreen", ImGuiKey_PrintScreen, "Pause", ImGuiKey_Pause, "Keypad0", - ImGuiKey_Keypad0, "Keypad1", ImGuiKey_Keypad1, "Keypad2", ImGuiKey_Keypad2, "Keypad3", ImGuiKey_Keypad3, "Keypad4", ImGuiKey_Keypad4, "Keypad5", ImGuiKey_Keypad5, - "Keypad6", ImGuiKey_Keypad6, "Keypad7", ImGuiKey_Keypad7, "Keypad8", ImGuiKey_Keypad8, "Keypad9", ImGuiKey_Keypad9, "KeypadDecimal", ImGuiKey_KeypadDecimal, "KeypadDivide", - ImGuiKey_KeypadDivide, "KeypadMultiply", ImGuiKey_KeypadMultiply, "KeypadSubtract", ImGuiKey_KeypadSubtract, "KeypadAdd", ImGuiKey_KeypadAdd, "KeypadEnter", - ImGuiKey_KeypadEnter, "COUNT", ImGuiKey_COUNT); - + "ImGuiKey", "Tab", ImGuiKey_Tab, "LeftArrow", ImGuiKey_LeftArrow, "RightArrow", ImGuiKey_RightArrow, "UpArrow", ImGuiKey_UpArrow, "DownArrow", ImGuiKey_DownArrow, "PageUp", + ImGuiKey_PageUp, "PageDown", ImGuiKey_PageDown, "Home", ImGuiKey_Home, "End", ImGuiKey_End, "Insert", ImGuiKey_Insert, "Delete", ImGuiKey_Delete, "Backspace", + ImGuiKey_Backspace, "Space", ImGuiKey_Space, "Enter", ImGuiKey_Enter, "Escape", ImGuiKey_Escape, "KeyPadEnter", ImGuiKey_KeyPadEnter, "A", ImGuiKey_A, "C", ImGuiKey_C, "V", + ImGuiKey_V, "X", ImGuiKey_X, "Y", ImGuiKey_Y, "Z", ImGuiKey_Z, "COUNT", ImGuiKey_COUNT, "LeftCtrl", ImGuiKey_LeftCtrl, "LeftShift", ImGuiKey_LeftShift, "G", ImGuiKey_G, + "S", ImGuiKey_S, "D", ImGuiKey_D, "R", ImGuiKey_R, "H", ImGuiKey_H); #pragma endregion Key #pragma region MouseCursor @@ -3243,6 +3139,13 @@ inline void InitEnums(sol::table luaGlobals) "ResizeNS", ImGuiMouseCursor_ResizeNS, "ResizeEW", ImGuiMouseCursor_ResizeEW, "ResizeNESW", ImGuiMouseCursor_ResizeNESW, "ResizeNWSE", ImGuiMouseCursor_ResizeNWSE, "Hand", ImGuiMouseCursor_Hand, "NotAllowed", ImGuiMouseCursor_NotAllowed, "COUNT", ImGuiMouseCursor_COUNT); #pragma endregion MouseCursor + +#pragma region ImDrawCorner Flags + luaGlobals.new_enum( + "ImDrawCornerFlags", "None", ImDrawCornerFlags_None, "TopLeft", ImDrawCornerFlags_TopLeft, "TopRight", ImDrawCornerFlags_TopRight, "BotLeft", ImDrawCornerFlags_BotLeft, + "BotRight", ImDrawCornerFlags_BotRight, "Top", ImDrawCornerFlags_Top, "Bot", ImDrawCornerFlags_Bot, "Left", ImDrawCornerFlags_Left, "Right", ImDrawCornerFlags_Right, "All", + ImDrawCornerFlags_All); +#pragma endregion ImDrawCorner Flags } inline void InitBindings(sol::state& lua, sol::table luaGlobals) @@ -3264,11 +3167,8 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function( "BeginChild", sol::overload( sol::resolve(BeginChild), sol::resolve(BeginChild), - sol::resolve(BeginChild), sol::resolve(BeginChild), - sol::resolve(BeginChild), - - // DEPRECATED - sol::resolve(BeginChild), sol::resolve(BeginChild))); + sol::resolve(BeginChild), sol::resolve(BeginChild), + sol::resolve(BeginChild))); ImGui.set_function("EndChild", EndChild); #pragma endregion Child Windows @@ -3315,8 +3215,6 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function("GetContentRegionAvail", GetContentRegionAvail); ImGui.set_function("GetWindowContentRegionMin", GetWindowContentRegionMin); ImGui.set_function("GetWindowContentRegionMax", GetWindowContentRegionMax); - - // DEPRECATED ImGui.set_function("GetWindowContentRegionWidth", GetWindowContentRegionWidth); #pragma endregion Content Region @@ -3342,8 +3240,6 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function("PopStyleColor", sol::overload(sol::resolve(PopStyleColor), sol::resolve(PopStyleColor))); ImGui.set_function("PushStyleVar", sol::overload(sol::resolve(PushStyleVar), sol::resolve(PushStyleVar))); ImGui.set_function("PopStyleVar", sol::overload(sol::resolve(PopStyleVar), sol::resolve(PopStyleVar))); - ImGui.set_function("PushItemFlag", PushItemFlag); - ImGui.set_function("PopItemFlag", PopItemFlag); ImGui.set_function("GetStyleColorVec4", GetStyleColorVec4); #ifdef SOL_IMGUI_ENABLE_FONT_MANIPULATORS ImGui.set_function("GetFont", GetFont); @@ -3360,15 +3256,11 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function("SetNextItemWidth", SetNextItemWidth); ImGui.set_function("CalcItemWidth", CalcItemWidth); ImGui.set_function("PushTextWrapPos", sol::overload(sol::resolve(PushTextWrapPos), sol::resolve(PushTextWrapPos))); - ImGui.set_function("PushTabStop", PushTabStop); - ImGui.set_function("PopTabStop", PopTabStop); ImGui.set_function("PopTextWrapPos", PopTextWrapPos); - - // DEPRECATED - ImGui.set_function("PushButtonRepeat", PushButtonRepeat); - ImGui.set_function("PopButtonRepeat", PopButtonRepeat); ImGui.set_function("PushAllowKeyboardFocus", PushAllowKeyboardFocus); ImGui.set_function("PopAllowKeyboardFocus", PopAllowKeyboardFocus); + ImGui.set_function("PushButtonRepeat", PushButtonRepeat); + ImGui.set_function("PopButtonRepeat", PopButtonRepeat); #pragma endregion Parameters stacks(current window) #pragma region Cursor / Layout @@ -3853,9 +3745,6 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function("GetItemRectMin", GetItemRectMin); ImGui.set_function("GetItemRectMax", GetItemRectMax); ImGui.set_function("GetItemRectSize", GetItemRectSize); - ImGui.set_function("SetNextItemAllowOverlap", SetNextItemAllowOverlap); - - // DEPRECATED ImGui.set_function("SetItemAllowOverlap", SetItemAllowOverlap); #pragma endregion Item / Widgets Utilities @@ -3866,12 +3755,10 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function("GetBackgroundDrawList", GetBackgroundDrawList); ImGui.set_function("GetForegroundDrawList", GetForegroundDrawList); ImGui.set_function("GetStyleColorName", GetStyleColorName); - ImGui.set_function("GetStyle", GetStyle); - - // DEPRECATED ImGui.set_function( "BeginChildFrame", sol::overload(sol::resolve(BeginChildFrame), sol::resolve(BeginChildFrame))); ImGui.set_function("EndChildFrame", EndChildFrame); + ImGui.set_function("GetStyle", GetStyle); #pragma endregion Miscellaneous Utilities #pragma region Text Utilities @@ -3894,9 +3781,6 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function("IsKeyDown", IsKeyDown); ImGui.set_function("IsKeyPressed", sol::overload(sol::resolve(IsKeyPressed), sol::resolve(IsKeyPressed))); ImGui.set_function("IsKeyReleased", IsKeyReleased); - ImGui.set_function("SetNextFrameWantCaptureKeyboard", SetNextFrameWantCaptureKeyboard); - - // DEPRECATED ImGui.set_function("CaptureKeyboardFromApp", sol::overload(sol::resolve(CaptureKeyboardFromApp), sol::resolve(CaptureKeyboardFromApp))); #pragma endregion Inputs Utilities : Keyboard @@ -3919,9 +3803,6 @@ inline void InitBindings(sol::state& lua, sol::table luaGlobals) ImGui.set_function("ResetMouseDragDelta", sol::overload(sol::resolve(ResetMouseDragDelta), sol::resolve(ResetMouseDragDelta))); ImGui.set_function("GetMouseCursor", GetMouseCursor); ImGui.set_function("SetMouseCursor", SetMouseCursor); - ImGui.set_function("SetNextFrameWantCaptureMouse", SetNextFrameWantCaptureMouse); - - // DEPRECATED ImGui.set_function("CaptureMouseFromApp", sol::overload(sol::resolve(CaptureMouseFromApp), sol::resolve(CaptureMouseFromApp))); #pragma endregion Inputs Utilities : Mouse diff --git a/xmake.lua b/xmake.lua index 576aee4a..56d95776 100644 --- a/xmake.lua +++ b/xmake.lua @@ -54,7 +54,7 @@ add_requires("sol2", { configs = { includes_lua = false } }) add_requires("openrestry-luajit", { configs = { gc64 = true } }) local imguiUserConfig = string.gsub(path.absolute("src/imgui_impl/imgui_user_config.h"), "\\", "/") -add_requires("imgui v1.91.1-docking", { configs = { wchar32 = true, freetype = true, user_config = imguiUserConfig } }) +add_requires("imgui v1.88-docking", { configs = { wchar32 = true, freetype = true, user_config = imguiUserConfig } }) target("RED4ext.SDK") set_kind("headeronly") @@ -71,7 +71,7 @@ target("cyber_engine_tweaks") add_files("src/**.cpp") add_headerfiles("src/**.h", "build/CETVersion.h") add_includedirs("src/", "build/") - add_syslinks("User32", "Version", "d3d11", "dxgi") + add_syslinks("User32", "Version", "d3d11") add_packages("spdlog", "nlohmann_json", "minhook", "hopscotch-map", "imgui", "mem", "sol2", "tiltedcore", "sqlite3", "openrestry-luajit", "xbyak", "stb") add_deps("RED4ext.SDK") add_configfiles("src/CETVersion.h.in")