diff --git a/libs/filagui/src/ImGuiExtensions.cpp b/libs/filagui/src/ImGuiExtensions.cpp index 89b5944d40e..0c1677c9f78 100644 --- a/libs/filagui/src/ImGuiExtensions.cpp +++ b/libs/filagui/src/ImGuiExtensions.cpp @@ -119,7 +119,7 @@ static void PlotEx(ImGuiPlotType plot_type, const char* label, int series_count, const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); ImGui::ItemSize(total_bb, style.FramePadding.y); if (!ImGui::ItemAdd(total_bb, 0, &frame_bb)) return; - const bool hovered = ImGui::ItemHoverable(inner_bb, 0); + const bool hovered = ImGui::ItemHoverable(inner_bb, 0, g.LastItemData.InFlags); // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { diff --git a/libs/filamentapp/src/FilamentApp.cpp b/libs/filamentapp/src/FilamentApp.cpp index 7e315b0da47..1015c16c985 100644 --- a/libs/filamentapp/src/FilamentApp.cpp +++ b/libs/filamentapp/src/FilamentApp.cpp @@ -196,7 +196,7 @@ void FilamentApp::run(const Config& config, SetupCallback setupCallback, SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window->getSDLWindow(), &wmInfo); - io.ImeWindowHandle = wmInfo.info.win.window; + ImGui::GetMainViewport()->PlatformHandleRaw = wmInfo.info.win.window; #endif io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; diff --git a/third_party/imgui/.editorconfig b/third_party/imgui/.editorconfig index 284ba13fe3e..5adfefa20d8 100644 --- a/third_party/imgui/.editorconfig +++ b/third_party/imgui/.editorconfig @@ -1,6 +1,12 @@ # See http://editorconfig.org to read about the EditorConfig format. -# - Automatically supported by VS2017+ and most common IDE or text editors. -# - For older VS2010 to VS2015, install https://marketplace.visualstudio.com/items?itemName=EditorConfigTeam.EditorConfig +# - In theory automatically supported by VS2017+ and most common IDE or text editors. +# - In practice VS2019-VS2022 stills don't trim trailing whitespaces correctly :( +# - Suggest installing this to trim whitespaces: +# GitHub https://github.com/madskristensen/TrailingWhitespace +# VS2019 https://marketplace.visualstudio.com/items?itemName=MadsKristensen.TrailingWhitespaceVisualizer +# VS2022 https://marketplace.visualstudio.com/items?itemName=MadsKristensen.TrailingWhitespace64 +# (in spite of its name doesn't only visualize but also trims) +# - Alternative for older VS2010 to VS2015: https://marketplace.visualstudio.com/items?itemName=EditorConfigTeam.EditorConfig # top-most EditorConfig file root = true diff --git a/third_party/imgui/.github/FUNDING.yml b/third_party/imgui/.github/FUNDING.yml new file mode 100644 index 00000000000..2aa08b4474c --- /dev/null +++ b/third_party/imgui/.github/FUNDING.yml @@ -0,0 +1 @@ +custom: ['https://github.com/ocornut/imgui/wiki/Sponsors'] diff --git a/third_party/imgui/.github/ISSUE_TEMPLATE/config.yml b/third_party/imgui/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000000..3ba13e0cec6 --- /dev/null +++ b/third_party/imgui/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/third_party/imgui/.github/ISSUE_TEMPLATE/issue_template.yml b/third_party/imgui/.github/ISSUE_TEMPLATE/issue_template.yml new file mode 100644 index 00000000000..792d8f63ed4 --- /dev/null +++ b/third_party/imgui/.github/ISSUE_TEMPLATE/issue_template.yml @@ -0,0 +1,90 @@ +name: "Ask a question, report a bug, request a feature, etc." +description: "Ask any question, discuss best practices, report a bug, request a feature." +body: + - type: markdown + attributes: + value: | + FOR FIRST-TIME USERS ISSUES COMPILING/LINKING/RUNNING or LOADING FONTS, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions) + For anything else: we are happy to use 'GitHub Issues' for many types of open-ended questions. We are encouraging 'Issues' becoming a large, centralized and cross-referenced database of Dear ImGui contents. + + Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. + - type: markdown + attributes: + value: | + **Prerequisites:** + - I have read [Frequently Asked Questions](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md). + - I have read [Contributing Guidelines -> General Advices](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md#getting-started--general-advice). + - I have read [Contributing Guidelines -> How to open an Issue](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md#how-to-open-an-issue). + - I have searched [Github Issues and PR](https://github.com/ocornut/imgui/issues?q=) for discussion of similar topics. + + ---- + - type: input + id: specs_version + attributes: + label: "Version/Branch of Dear ImGui:" + description: "(please specify if you have made substantial modifications to your copy)" + value: "Version 1.XX, Branch: XXX (master/docking/etc.)" + placeholder: "Version 1.XX, Branch: XXX (master/docking/etc.)" + validations: + required: true + - type: input + id: specs_backend + attributes: + label: "Back-ends:" + description: (or specify when using custom engine/back-ends) + value: "imgui_impl_XXX.cpp + imgui_impl_XXX.cpp" + placeholder: "imgui_impl_XXX.cpp + imgui_impl_XXX.cpp or n/a" + validations: + required: true + - type: input + id: specs_compiler_os + attributes: + label: "Compiler, OS:" + placeholder: "e.g. Windows 11 + MSVC 2022, macOS + Clang 12, Linux + GCC etc." + validations: + required: true + - type: textarea + id: specs_full + attributes: + label: "Full config/build information:" + placeholder: | + (If you can run, you may go to 'Demo->Tools->About Dear ImGui->Config/Build Info' to obtain detailed information that you can paste here) + validations: + required: false + - type: textarea + id: issue_description + attributes: + label: "Details:" + description: "Try to be explicit with your goals, your expectations and what you have tried. Be mindful of [The XY Problem](https://xyproblem.info). What you have in mind or in your code is not obvious to other people. People frequently discuss problems and suggest incorrect solutions without first clarifying their goals. When requesting a new feature, please describe the usage context (how you intend to use it, why you need it, etc.). If you tried something and it failed, show us what you tried. If you are reporting a bug, explain what's the bug, how does it occur, etc. If you are reporting a crash, please include a debugger callstack." + value: | + **My Issue/Question:** + + XXX _(please provide as much context as possible)_ + validations: + required: true + - type: textarea + id: screenshots + attributes: + label: "Screenshots/Video:" + description: "Attach screenshots or gif/videos to clarify the context. They often convey useful information that is omitted by the description." + placeholder: "(You can drag files here)" + validations: + required: false + - type: textarea + id: repro_code + attributes: + label: "Minimal, Complete and Verifiable Example code:" + description: "Provide an [MCVE](https://stackoverflow.com/help/mcve) to demonstrate your problem. An ideal submission includes a small piece of code that anyone can paste into one of the examples applications (examples/*/main.cpp) or the demo (imgui_demo.cpp) to understand and reproduce it. Narrowing your problem to its shortest and purest form is the easiest way to understand it, explain it and fix it. Please test your shortened code to ensure it exhibits the problem. Often while creating the MCVE you will solve the problem! Many questions that are missing a standalone verifiable example are missing the actual cause of their issue in the description, which ends up wasting everyone's time." + value: | + ```cpp + // Here's some code anyone can copy and paste to reproduce your issue + ImGui::Begin("Example Bug"); + MoreCodeToExplainMyIssue(); + ImGui::End(); + ``` + validations: + required: false + - type: markdown + attributes: + value: | + Thank you for taking the time to read prerequisites, filling this template and double-checking your message and your code! diff --git a/third_party/imgui/.github/issue_template.md b/third_party/imgui/.github/issue_template.md deleted file mode 100644 index 3812ad0b015..00000000000 --- a/third_party/imgui/.github/issue_template.md +++ /dev/null @@ -1,46 +0,0 @@ -(Click "Preview" above ^ to turn URL into clickable links) - -1. PLEASE CAREFULLY READ: [FAQ](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) - -2. PLEASE CAREFULLY READ: [Issue Submitting Guidelines](https://github.com/ocornut/imgui/issues/2261) - -3. FOR FIRST-TIME USERS ISSUES COMPILING/LINKING/RUNNING/LOADING FONTS, please use the [Discord server](http://discord.dearimgui.org). - -4. PLEASE MAKE SURE that you have: read the FAQ; explored the contents of `ShowDemoWindow()` including the Examples menu; searched among Issues; used your IDE to search for keywords in all sources and text files; and read the link provided in (1) (2). - -5. Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users. - -6. Delete points 1-6 and PLEASE FILL THE TEMPLATE BELOW before submitting your issue. - -Thank you! - ----- - -_(you may also go to Demo>About Window, and click "Config/Build Information" to obtain a bunch of detailed information that you can paste here)_ - -**Version/Branch of Dear ImGui:** - -Version: XXX -Branch: XXX _(master/viewport/docking/etc.)_ - -**Back-end/Renderer/Compiler/OS** - -Back-ends: imgui_impl_XXX.cpp + imgui_impl_XXX.cpp _(or specify if using a custom engine/back-end)_ -Compiler: XXX _(if the question is related to building or platform specific features)_ -Operating System: XXX - -**My Issue/Question:** - -XXX _(please provide as much context as possible)_ - -**Screenshots/Video** - -XXX _(you can drag files here)_ - -**Standalone, minimal, complete and verifiable example:** _(see https://github.com/ocornut/imgui/issues/2261)_ -``` -// Here's some code anyone can copy and paste to reproduce your issue -ImGui::Begin("Example Bug"); -MoreCodeToExplainMyIssue(); -ImGui::End(); -``` diff --git a/third_party/imgui/.github/pull_request_template.md b/third_party/imgui/.github/pull_request_template.md index 533027c9ad6..638545bd6d3 100644 --- a/third_party/imgui/.github/pull_request_template.md +++ b/third_party/imgui/.github/pull_request_template.md @@ -1,6 +1,6 @@ (Click "Preview" to turn any http URL into a clickable link) -PLEASE CAREFULLY READ: -https://github.com/ocornut/imgui/issues/2261 +1. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md) + +2. Clear this template before submitting your PR. -(Clear this template before submitting your PR) diff --git a/third_party/imgui/.github/workflows/build.yml b/third_party/imgui/.github/workflows/build.yml index 8edef47bf64..d332903ed0d 100644 --- a/third_party/imgui/.github/workflows/build.yml +++ b/third_party/imgui/.github/workflows/build.yml @@ -1,10 +1,18 @@ name: build on: - push: {} - pull_request: {} - schedule: - - cron: '0 9 * * *' + push: + pull_request: + workflow_run: + # Use a workflow as a trigger of scheduled builds. Forked repositories can disable scheduled builds by disabling + # "scheduled" workflow, while maintaining ability to perform local CI builds. + workflows: + - scheduled + branches: + - master + - docking + types: + - requested jobs: Windows: @@ -12,73 +20,92 @@ jobs: env: VS_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\ MSBUILD_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\ - # Until gh-actions allow us to use env variables inside other env variables (because we need %GITHUB_WORKSPACE%) we have to use relative path to imgui/examples/example_name directory. - SDL2_DIR: ..\..\SDL2-devel-2.0.10-VC\SDL2-2.0.10\ - VULKAN_SDK: ..\..\vulkan-sdk-1.1.121.2\ steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 + - uses: actions/checkout@v4 - name: Install Dependencies shell: powershell run: | - Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL2-devel-2.0.10-VC.zip" -OutFile "SDL2-devel-2.0.10-VC.zip" - Expand-Archive -Path SDL2-devel-2.0.10-VC.zip + Invoke-WebRequest -Uri "https://www.libsdl.org/release/SDL2-devel-2.26.3-VC.zip" -OutFile "SDL2-devel-2.26.3-VC.zip" + Expand-Archive -Path SDL2-devel-2.26.3-VC.zip + echo "SDL2_DIR=$(pwd)\SDL2-devel-2.26.3-VC\SDL2-2.26.3\" >>${env:GITHUB_ENV} + Invoke-WebRequest -Uri "https://github.com/ocornut/imgui/files/3789205/vulkan-sdk-1.1.121.2.zip" -OutFile vulkan-sdk-1.1.121.2.zip Expand-Archive -Path vulkan-sdk-1.1.121.2.zip + echo "VULKAN_SDK=$(pwd)\vulkan-sdk-1.1.121.2\" >>${env:GITHUB_ENV} - name: Fix Projects shell: powershell run: | - # WARNING: This will need updating if toolset/sdk change in project files! + # CI workers do not supporter older Visual Studio versions. Fix projects to target newer available version. gci -recurse -filter "*.vcxproj" | ForEach-Object { - # Fix SDK and toolset for most samples. - (Get-Content $_.FullName) -Replace "v110","v142" | Set-Content -Path $_.FullName - (Get-Content $_.FullName) -Replace "8.1","10.0.18362.0" | Set-Content -Path $_.FullName - # Fix SDK and toolset for samples that require newer SDK/toolset. At the moment it is only dx12. - (Get-Content $_.FullName) -Replace "v140","v142" | Set-Content -Path $_.FullName - (Get-Content $_.FullName) -Replace "10.0.14393.0","10.0.18362.0" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "v\d{3}","v142" | Set-Content -Path $_.FullName + (Get-Content $_.FullName) -Replace "[\d\.]+","10.0.18362.0" | Set-Content -Path $_.FullName } # Not using matrix here because it would inflate job count too much. Check out and setup is done for every job and that makes build times way too long. - name: Build example_null (extra warnings, mingw 64-bit) run: mingw32-make -C examples/example_null WITH_EXTRA_WARNINGS=1 + - name: Build example_null (mingw 64-bit, as DLL) + shell: bash + run: | + echo '#ifdef _EXPORT' > example_single_file.cpp + echo '# define IMGUI_API __declspec(dllexport)' >> example_single_file.cpp + echo '#else' >> example_single_file.cpp + echo '# define IMGUI_API __declspec(dllimport)' >> example_single_file.cpp + echo '#endif' >> example_single_file.cpp + echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp + echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + g++ -I. -Wall -Wformat -D_EXPORT -shared -o libimgui.dll -Wl,--out-implib,libimgui.a example_single_file.cpp -limm32 + g++ -I. -Wall -Wformat -o example_null.exe examples/example_null/main.cpp -L. -limgui + rm -f example_null.exe libimgui.* example_single_file.* + - name: Build example_null (extra warnings, msvc 64-bit) shell: cmd run: | cd examples\example_null - "%VS_PATH%\VC\Auxiliary\Build\vcvarsall.bat" x64 && .\build_win32.bat /W4 + call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" + .\build_win32.bat /W4 - name: Build example_null (single file build) shell: bash run: | - echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 - name: Build example_null (with IMGUI_DISABLE_WIN32_FUNCTIONS) shell: bash run: | - echo '#define IMGUI_DISABLE_WIN32_FUNCTIONS' > example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_DISABLE_WIN32_FUNCTIONS + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -Wall -Wformat -o example_single_file.exe example_single_file.cpp -limm32 - name: Build example_null (as DLL) shell: cmd run: | - "%VS_PATH%\VC\Auxiliary\Build\vcvarsall.bat" x64 - echo '#ifdef _EXPORT' > example_single_file.cpp - echo '# define IMGUI_API __declspec(dllexport)' >> example_single_file.cpp - echo '#else' >> example_single_file.cpp - echo '# define IMGUI_API __declspec(dllimport)' >> example_single_file.cpp - echo '#endif' >> example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp + call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" + + echo #ifdef _EXPORT > example_single_file.cpp + echo # define IMGUI_API __declspec(dllexport) >> example_single_file.cpp + echo #else >> example_single_file.cpp + echo # define IMGUI_API __declspec(dllimport) >> example_single_file.cpp + echo #endif >> example_single_file.cpp + echo #define IMGUI_IMPLEMENTATION >> example_single_file.cpp + echo #include "misc/single_file/imgui_single_file.h" >> example_single_file.cpp + cl.exe /D_USRDLL /D_WINDLL /D_EXPORT /I. example_single_file.cpp /LD /FeImGui.dll /link cl.exe /I. ImGui.lib /Feexample_null.exe examples/example_null/main.cpp @@ -89,31 +116,31 @@ jobs: - name: Build Win32 example_glfw_opengl3 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj /p:Platform=Win32 /p:Configuration=Release' - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - name: Build Win32 example_glfw_vulkan shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj /p:Platform=Win32 /p:Configuration=Release' - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - - name: Build Win32 example_sdl_vulkan + - name: Build Win32 example_sdl2_vulkan shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj /p:Platform=Win32 /p:Configuration=Release' - if: github.event_name == 'schedule' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - - name: Build Win32 example_sdl_opengl2 + - name: Build Win32 example_sdl2_opengl2 shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj /p:Platform=Win32 /p:Configuration=Release' - if: github.event_name == 'schedule' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - - name: Build Win32 example_sdl_opengl3 + - name: Build Win32 example_sdl2_opengl3 shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj /p:Platform=Win32 /p:Configuration=Release' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj /p:Platform=Win32 /p:Configuration=Release' - - name: Build Win32 example_sdl_directx11 + - name: Build Win32 example_sdl2_directx11 shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_directx11/example_sdl_directx11.vcxproj /p:Platform=Win32 /p:Configuration=Release' - if: github.event_name == 'schedule' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj /p:Platform=Win32 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - name: Build Win32 example_win32_directx9 shell: cmd @@ -126,12 +153,12 @@ jobs: - name: Build Win32 example_win32_directx11 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx11/example_win32_directx11.vcxproj /p:Platform=Win32 /p:Configuration=Release' - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - name: Build x64 example_glfw_opengl2 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - name: Build x64 example_glfw_opengl3 shell: cmd @@ -141,55 +168,53 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' - - name: Build x64 example_sdl_vulkan + - name: Build x64 example_sdl2_vulkan shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'schedule' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl_opengl2 + - name: Build x64 example_sdl2_opengl2 shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'schedule' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl_opengl3 + - name: Build x64 example_sdl2_opengl3 shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'schedule' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj /p:Platform=x64 /p:Configuration=Release' + if: github.event_name == 'workflow_run' - - name: Build x64 example_sdl_directx11 + - name: Build x64 example_sdl2_directx11 shell: cmd - run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl_directx11/example_sdl_directx11.vcxproj /p:Platform=x64 /p:Configuration=Release' + run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj /p:Platform=x64 /p:Configuration=Release' - name: Build x64 example_win32_directx9 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx9/example_win32_directx9.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - name: Build x64 example_win32_directx10 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx10/example_win32_directx10.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - name: Build x64 example_win32_directx11 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx11/example_win32_directx11.vcxproj /p:Platform=x64 /p:Configuration=Release' - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - name: Build x64 example_win32_directx12 shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' Linux: - runs-on: ubuntu-18.04 + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 + - uses: actions/checkout@v4 - name: Install Dependencies run: | sudo apt-get update - sudo apt-get install -y libglfw3-dev libsdl2-dev gcc-multilib g++-multilib libfreetype6-dev + sudo apt-get install -y libglfw3-dev libsdl2-dev gcc-multilib g++-multilib libfreetype6-dev libvulkan-dev - name: Build example_null (extra warnings, gcc 32-bit) run: | @@ -211,6 +236,18 @@ jobs: make -C examples/example_null clean CXXFLAGS="$CXXFLAGS -m64 -Werror" CXX=clang++ make -C examples/example_null WITH_EXTRA_WARNINGS=1 + - name: Build example_null (extra warnings, empty IM_ASSERT) + run: | + cat > example_single_file.cpp <<'EOF' + + #define IM_ASSERT(x) + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -Wextra -Werror -Wno-zero-as-null-pointer-constant -Wno-double-promotion -Wno-variadic-macros -Wno-empty-body -o example_single_file example_single_file.cpp + - name: Build example_null (freetype) run: | make -C examples/example_null clean @@ -218,146 +255,203 @@ jobs: - name: Build example_null (single file build) run: | - echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with ImWchar32) run: | - echo '#define IMGUI_USE_WCHAR32' > example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_USE_WCHAR32 + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - - name: Build example_null (with large ImDrawIdx) + - name: Build example_null (with large ImDrawIdx + pointer ImTextureID) run: | - echo '#define ImDrawIdx unsigned int' > example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define ImTextureID void* + #define ImDrawIdx unsigned int + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_OBSOLETE_FUNCTIONS) run: | - echo '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' > example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp + + - name: Build example_null (with IMGUI_DISABLE_OBSOLETE_KEYIO) + run: | + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_DISABLE_OBSOLETE_KEYIO + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - - name: Build example_null (with IMGUI_DISABLE_DEMO_WINDOWS and IMGUI_DISABLE_METRICS_WINDOW) + - name: Build example_null (with IMGUI_DISABLE_DEMO_WINDOWS and IMGUI_DISABLE_DEBUG_TOOLS) run: | - echo '#define IMGUI_DISABLE_DEMO_WINDOWS' > example_single_file.cpp - echo '#define IMGUI_DISABLE_METRICS_WINDOW' >> example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_DISABLE_DEMO_WINDOWS + #define IMGUI_DISABLE_DEBUG_TOOLS + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_DISABLE_FILE_FUNCTIONS) run: | - echo '#define IMGUI_DISABLE_FILE_FUNCTIONS' > example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_DISABLE_FILE_FUNCTIONS + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IMGUI_USE_BGRA_PACKED_COLOR) run: | - echo '#define IMGUI_USE_BGRA_PACKED_COLOR' > example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_USE_BGRA_PACKED_COLOR + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (with IM_VEC2_CLASS_EXTRA and IM_VEC4_CLASS_EXTRA) run: | - echo 'struct MyVec2 { float x; float y; MyVec2(float x, float y) : x(x), y(y) { } };' > example_single_file.cpp - echo 'struct MyVec4 { float x; float y; float z; float w;' >> example_single_file.cpp - echo 'MyVec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { } };' >> example_single_file.cpp - echo '#define IM_VEC2_CLASS_EXTRA \' >> example_single_file.cpp - echo ' ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \' >> example_single_file.cpp - echo ' operator MyVec2() const { return MyVec2(x, y); }' >> example_single_file.cpp - echo '#define IM_VEC4_CLASS_EXTRA \' >> example_single_file.cpp - echo ' ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \' >> example_single_file.cpp - echo ' operator MyVec4() const { return MyVec4(x, y, z, w); }' >> example_single_file.cpp - echo '#define IMGUI_IMPLEMENTATION' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - g++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + struct MyVec2 { float x; float y; MyVec2(float x, float y) : x(x), y(y) { } }; + struct MyVec4 { float x; float y; float z; float w; + MyVec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { } }; + #define IM_VEC2_CLASS_EXTRA \ + ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ + operator MyVec2() const { return MyVec2(x, y); } + #define IM_VEC4_CLASS_EXTRA \ + ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ + operator MyVec4() const { return MyVec4(x, y, z, w); } + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + g++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (without c++ runtime, Clang) run: | - echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp - echo '#define IMGUI_DISABLE_DEMO_WINDOWS' >> example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - clang++ -I. -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_IMPLEMENTATION + #define IMGUI_DISABLE_DEMO_WINDOWS + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + clang++ -I. -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 - name: Build example_glfw_opengl3 run: make -C examples/example_glfw_opengl3 - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - - name: Build example_sdl_opengl2 - run: make -C examples/example_sdl_opengl2 - if: github.event_name == 'schedule' + - name: Build example_sdl2_opengl2 + run: make -C examples/example_sdl2_opengl2 + if: github.event_name == 'workflow_run' - - name: Build example_sdl_opengl3 - run: make -C examples/example_sdl_opengl3 + - name: Build example_sdl2_opengl3 + run: make -C examples/example_sdl2_opengl3 + + - name: Build with IMGUI_IMPL_VULKAN_NO_PROTOTYPES + run: g++ -c -I. -std=c++11 -DIMGUI_IMPL_VULKAN_NO_PROTOTYPES=1 backends/imgui_impl_vulkan.cpp MacOS: - runs-on: macOS-latest + runs-on: macos-latest steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 + - uses: actions/checkout@v4 - name: Install Dependencies run: | - brew install glfw3 - brew install sdl2 + brew install glfw3 sdl2 - name: Build example_null (extra warnings, clang 64-bit) run: make -C examples/example_null WITH_EXTRA_WARNINGS=1 - name: Build example_null (single file build) run: | - echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - clang++ -I. -Wall -Wformat -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + clang++ -I. -std=c++11 -Wall -Wformat -o example_single_file example_single_file.cpp - name: Build example_null (without c++ runtime) run: | - echo '#define IMGUI_IMPLEMENTATION' > example_single_file.cpp - echo '#include "misc/single_file/imgui_single_file.h"' >> example_single_file.cpp - echo '#include "examples/example_null/main.cpp"' >> example_single_file.cpp - clang++ -I. -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp + cat > example_single_file.cpp <<'EOF' + + #define IMGUI_IMPLEMENTATION + #include "misc/single_file/imgui_single_file.h" + #include "examples/example_null/main.cpp" + + EOF + clang++ -I. -std=c++11 -Wall -Wformat -nodefaultlibs -fno-rtti -fno-exceptions -fno-threadsafe-statics -lc -lm -o example_single_file example_single_file.cpp - name: Build example_glfw_opengl2 run: make -C examples/example_glfw_opengl2 - name: Build example_glfw_opengl3 run: make -C examples/example_glfw_opengl3 - if: github.event_name == 'schedule' + if: github.event_name == 'workflow_run' - name: Build example_glfw_metal run: make -C examples/example_glfw_metal - - name: Build example_sdl_metal - run: make -C examples/example_sdl_metal + - name: Build example_sdl2_metal + run: make -C examples/example_sdl2_metal - - name: Build example_sdl_opengl2 - run: make -C examples/example_sdl_opengl2 - if: github.event_name == 'schedule' + - name: Build example_sdl2_opengl2 + run: make -C examples/example_sdl2_opengl2 + if: github.event_name == 'workflow_run' - - name: Build example_sdl_opengl3 - run: make -C examples/example_sdl_opengl3 + - name: Build example_sdl2_opengl3 + run: make -C examples/example_sdl2_opengl3 - name: Build example_apple_metal run: xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_macos @@ -366,11 +460,9 @@ jobs: run: xcodebuild -project examples/example_apple_opengl2/example_apple_opengl2.xcodeproj -target example_osx_opengl2 iOS: - runs-on: macOS-latest + runs-on: macos-latest steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 + - uses: actions/checkout@v4 - name: Build example_apple_metal run: | @@ -378,56 +470,38 @@ jobs: xcodebuild -project examples/example_apple_metal/example_apple_metal.xcodeproj -target example_apple_metal_ios CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO Emscripten: - runs-on: ubuntu-18.04 + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 + - uses: actions/checkout@v4 - name: Install Dependencies run: | wget -q https://github.com/emscripten-core/emsdk/archive/master.tar.gz tar -xvf master.tar.gz emsdk-master/emsdk update - emsdk-master/emsdk install latest-fastcomp - emsdk-master/emsdk activate latest-fastcomp + emsdk-master/emsdk install latest + emsdk-master/emsdk activate latest + + - name: Build example_sdl2_opengl3 with Emscripten + run: | + pushd emsdk-master + source ./emsdk_env.sh + popd + make -C examples/example_sdl2_opengl3 -f Makefile.emscripten - - name: Build example_emscripten + - name: Build example_emscripten_wgpu run: | - source emsdk-master/emsdk_env.sh - make -C examples/example_emscripten + pushd emsdk-master + source ./emsdk_env.sh + popd + make -C examples/example_emscripten_wgpu -f Makefile.emscripten - Static-Analysis: - runs-on: ubuntu-18.04 + Android: + runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 + - uses: actions/checkout@v4 - - name: Install Dependencies - env: - PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }} - run: | - if [[ "$PVS_STUDIO_LICENSE" != "" ]]; - then - echo "$PVS_STUDIO_LICENSE" > pvs-studio.lic - wget -q https://files.viva64.com/etc/pubkey.txt - sudo apt-key add pubkey.txt - sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list - sudo apt-get update - sudo apt-get install -y pvs-studio - fi - - - name: PVS-Studio static analysis - run: | - if [[ ! -f pvs-studio.lic ]]; - then - echo "PVS Studio license is missing. No analysis will be performed." - echo "If you have a PVS Studio license please create a project secret named PVS_STUDIO_LICENSE with your license." - echo "You may use a free license. More information at https://www.viva64.com/en/b/0457/" - exit 0 - fi - cd examples/example_null - pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 - pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log - plog-converter -a 'GA:1,2;OP:1' -t errorfile -w pvs-studio.log + - name: Build example_android_opengl3 + run: | + cd examples/example_android_opengl3/android + gradle assembleDebug --stacktrace diff --git a/third_party/imgui/.github/workflows/scheduled.yml b/third_party/imgui/.github/workflows/scheduled.yml new file mode 100644 index 00000000000..2a08578fb65 --- /dev/null +++ b/third_party/imgui/.github/workflows/scheduled.yml @@ -0,0 +1,15 @@ +# +# This is a dummy workflow used to trigger scheduled builds. Forked repositories most likely should disable this +# workflow to avoid daily builds of inactive repositories. +# +name: scheduled + +on: + schedule: + - cron: '0 9 * * *' + +jobs: + scheduled: + runs-on: ubuntu-latest + steps: + - run: exit 0 diff --git a/third_party/imgui/.github/workflows/static-analysis.yml b/third_party/imgui/.github/workflows/static-analysis.yml new file mode 100644 index 00000000000..69df5cdf803 --- /dev/null +++ b/third_party/imgui/.github/workflows/static-analysis.yml @@ -0,0 +1,46 @@ +name: static-analysis + +on: + workflow_run: + # Perform static analysis together with build workflow. Build triggers of "build" workflow do not need to be repeated here. + workflows: + - build + types: + - requested + +jobs: + PVS-Studio: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Install Dependencies + env: + # The Secret variable setup in GitHub must be in format: "name_or_email key", on a single line + PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }} + run: | + if [[ "$PVS_STUDIO_LICENSE" != "" ]]; + then + wget -q https://files.viva64.com/etc/pubkey.txt + sudo apt-key add pubkey.txt + sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list + sudo apt-get update + sudo apt-get install -y pvs-studio + pvs-studio-analyzer credentials -o pvs-studio.lic $PVS_STUDIO_LICENSE + fi + + - name: PVS-Studio static analysis + run: | + if [[ ! -f pvs-studio.lic ]]; + then + echo "PVS Studio license is missing. No analysis will be performed." + echo "If you have a PVS Studio license please create a project secret named PVS_STUDIO_LICENSE with your license." + echo "You may use a free license. More information at https://www.viva64.com/en/b/0457/" + exit 0 + fi + cd examples/example_null + pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1 + pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log + plog-converter -a 'GA:1,2;OP:1' -d V1071 -t errorfile -w pvs-studio.log diff --git a/third_party/imgui/.gitignore b/third_party/imgui/.gitignore index 84014850bb1..211d21dda88 100644 --- a/third_party/imgui/.gitignore +++ b/third_party/imgui/.gitignore @@ -8,7 +8,6 @@ imgui.ini *.o *.obj *.exe -examples/build/* examples/*/Debug/* examples/*/Release/* examples/*/x64/* @@ -26,6 +25,12 @@ ipch *.VC.db *.VC.VC.opendb +## Getting files created in JSON/Schemas/Catalog/ from a VS2022 update +JSON/ + +## Commonly used CMake directories +build*/ + ## Xcode artifacts project.xcworkspace xcuserdata @@ -34,16 +39,21 @@ xcuserdata examples/*.o.tmp examples/*.out.js examples/*.out.wasm -examples/example_emscripten/example_emscripten.* +examples/example_glfw_opengl3/web/* +examples/example_sdl2_opengl3/web/* +examples/example_emscripten_wgpu/web/* ## JetBrains IDE artifacts .idea cmake-build-* ## Unix executables from our example Makefiles +examples/example_glfw_metal/example_glfw_metal examples/example_glfw_opengl2/example_glfw_opengl2 examples/example_glfw_opengl3/example_glfw_opengl3 examples/example_glut_opengl2/example_glut_opengl2 examples/example_null/example_null -examples/example_sdl_opengl2/example_sdl_opengl2 -examples/example_sdl_opengl3/example_sdl_opengl3 +examples/example_sdl2_metal/example_sdl2_metal +examples/example_sdl2_opengl2/example_sdl2_opengl2 +examples/example_sdl2_opengl3/example_sdl2_opengl3 +examples/example_sdl2_sdlrenderer/example_sdl2_sdlrenderer diff --git a/third_party/imgui/LICENSE.txt b/third_party/imgui/LICENSE.txt index 780533dcb26..3282f5b5b10 100644 --- a/third_party/imgui/LICENSE.txt +++ b/third_party/imgui/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014-2021 Omar Cornut +Copyright (c) 2014-2024 Omar Cornut Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/third_party/imgui/backends/imgui_impl_allegro5.cpp b/third_party/imgui/backends/imgui_impl_allegro5.cpp index 8eb63614a42..ef1f13f38ca 100644 --- a/third_party/imgui/backends/imgui_impl_allegro5.cpp +++ b/third_party/imgui/backends/imgui_impl_allegro5.cpp @@ -3,20 +3,31 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Clipboard support (from Allegro 5.1.12) // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Issues: -// [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. +// [ ] Renderer: The renderer is suboptimal as we need to convert vertices manually. // [ ] Platform: Missing gamepad support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2021-12-08: Renderer: Fixed mishandling of the the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. +// 2022-11-30: Renderer: Restoring using al_draw_indexed_prim() when Allegro version is >= 5.2.5. +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). +// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. +// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). +// 2022-01-17: Inputs: always calling io.AddKeyModsEvent() next and before key event (not in NewFrame) to fix input queue with very low framerates. +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. +// 2021-12-08: Renderer: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. // 2021-08-17: Calling io.AddFocusEvent() on ALLEGRO_EVENT_DISPLAY_SWITCH_OUT/ALLEGRO_EVENT_DISPLAY_SWITCH_IN events. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: Renderer: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) @@ -30,6 +41,7 @@ // 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window. // 2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12). // 2018-06-13: Renderer: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. +// 2018-06-13: Renderer: Stopped using al_draw_indexed_prim() as it is buggy in Allegro's DX9 backend. // 2018-06-13: Renderer: Backup/restore transform and clipping rectangle. // 2018-06-11: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. // 2018-04-18: Misc: Renamed file from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp. @@ -38,10 +50,11 @@ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. -#include // uint64_t -#include // memcpy #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_allegro5.h" +#include // uint64_t +#include // memcpy // Allegro #include @@ -49,13 +62,27 @@ #ifdef _WIN32 #include #endif -#define ALLEGRO_HAS_CLIPBOARD (ALLEGRO_VERSION_INT >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12 +#define ALLEGRO_HAS_CLIPBOARD (ALLEGRO_VERSION_INT >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12 +#define ALLEGRO_HAS_DRAW_INDEXED_PRIM (ALLEGRO_VERSION_INT >= ((5 << 24) | (2 << 16) | ( 5 << 8))) // DX9 implementation of al_draw_indexed_prim() got fixed in Allegro 5.2.5 // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #endif +struct ImDrawVertAllegro +{ + ImVec2 pos; + ImVec2 uv; + ALLEGRO_COLOR col; +}; + +// FIXME-OPT: Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 float as well.. +// FIXME-OPT: Consider inlining al_map_rgba()? +// see https://github.com/liballeg/allegro5/blob/master/src/pixels.c#L554 +// and https://github.com/liballeg/allegro5/blob/master/include/allegro5/internal/aintern_pixels.h +#define DRAW_VERT_IMGUI_TO_ALLEGRO(DST, SRC) { (DST)->pos = (SRC)->pos; (DST)->uv = (SRC)->uv; unsigned char* c = (unsigned char*)&(SRC)->col; (DST)->col = al_map_rgba(c[0], c[1], c[2], c[3]); } + // Allegro Data struct ImGui_ImplAllegro5_Data { @@ -66,20 +93,16 @@ struct ImGui_ImplAllegro5_Data ALLEGRO_VERTEX_DECL* VertexDecl; char* ClipboardTextData; - ImGui_ImplAllegro5_Data() { memset(this, 0, sizeof(*this)); } + ImVector BufVertices; + ImVector BufIndices; + + ImGui_ImplAllegro5_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. -static ImGui_ImplAllegro5_Data* ImGui_ImplAllegro5_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplAllegro5_Data*)ImGui::GetIO().BackendPlatformUserData : NULL; } - -struct ImDrawVertAllegro -{ - ImVec2 pos; - ImVec2 uv; - ALLEGRO_COLOR col; -}; +static ImGui_ImplAllegro5_Data* ImGui_ImplAllegro5_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplAllegro5_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } static void ImGui_ImplAllegro5_SetupRenderState(ImDrawData* draw_data) { @@ -125,35 +148,40 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; - // Allegro's implementation of al_draw_indexed_prim() for DX9 is completely broken. Unindex our buffers ourselves. - // FIXME-OPT: Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 float as well.. - static ImVector vertices; - vertices.resize(cmd_list->IdxBuffer.Size); - for (int i = 0; i < cmd_list->IdxBuffer.Size; i++) + ImVector& vertices = bd->BufVertices; +#if ALLEGRO_HAS_DRAW_INDEXED_PRIM + vertices.resize(cmd_list->VtxBuffer.Size); + for (int i = 0; i < cmd_list->VtxBuffer.Size; i++) { - const ImDrawVert* src_v = &cmd_list->VtxBuffer[cmd_list->IdxBuffer[i]]; + const ImDrawVert* src_v = &cmd_list->VtxBuffer[i]; ImDrawVertAllegro* dst_v = &vertices[i]; - dst_v->pos = src_v->pos; - dst_v->uv = src_v->uv; - unsigned char* c = (unsigned char*)&src_v->col; - dst_v->col = al_map_rgba(c[0], c[1], c[2], c[3]); + DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v); } - - const int* indices = NULL; + const int* indices = nullptr; if (sizeof(ImDrawIdx) == 2) { - // FIXME-OPT: Unfortunately Allegro doesn't support 16-bit indices.. You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices. + // FIXME-OPT: Allegro doesn't support 16-bit indices. + // You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices. // Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful. - static ImVector indices_converted; - indices_converted.resize(cmd_list->IdxBuffer.Size); + bd->BufIndices.resize(cmd_list->IdxBuffer.Size); for (int i = 0; i < cmd_list->IdxBuffer.Size; ++i) - indices_converted[i] = (int)cmd_list->IdxBuffer.Data[i]; - indices = indices_converted.Data; + bd->BufIndices[i] = (int)cmd_list->IdxBuffer.Data[i]; + indices = bd->BufIndices.Data; } else if (sizeof(ImDrawIdx) == 4) { indices = (const int*)cmd_list->IdxBuffer.Data; } +#else + // Allegro's implementation of al_draw_indexed_prim() for DX9 was broken until 5.2.5. Unindex buffers ourselves while converting vertex format. + vertices.resize(cmd_list->IdxBuffer.Size); + for (int i = 0; i < cmd_list->IdxBuffer.Size; i++) + { + const ImDrawVert* src_v = &cmd_list->VtxBuffer[cmd_list->IdxBuffer[i]]; + ImDrawVertAllegro* dst_v = &vertices[i]; + DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v); + } +#endif // Render command lists ImVec2 clip_off = draw_data->DisplayPos; @@ -180,7 +208,11 @@ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data) // Apply scissor/clipping rectangle, Draw ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->GetTexID(); al_set_clipping_rectangle(clip_min.x, clip_min.y, clip_max.x - clip_min.x, clip_max.y - clip_min.y); +#if ALLEGRO_HAS_DRAW_INDEXED_PRIM + al_draw_indexed_prim(&vertices[0], bd->VertexDecl, texture, &indices[pcmd->IdxOffset], pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST); +#else al_draw_prim(&vertices[0], bd->VertexDecl, texture, pcmd->IdxOffset, pcmd->IdxOffset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST); +#endif } } } @@ -202,6 +234,7 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Create texture + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) int flags = al_get_new_bitmap_flags(); int fmt = al_get_new_bitmap_format(); al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); @@ -228,7 +261,7 @@ bool ImGui_ImplAllegro5_CreateDeviceObjects() return false; // Store our identifier - io.Fonts->SetTexID((void*)cloned_img); + io.Fonts->SetTexID((ImTextureID)(intptr_t)cloned_img); bd->Texture = cloned_img; // Create an invisible mouse cursor @@ -246,14 +279,14 @@ void ImGui_ImplAllegro5_InvalidateDeviceObjects() ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); if (bd->Texture) { - io.Fonts->SetTexID(NULL); + io.Fonts->SetTexID(0); al_destroy_bitmap(bd->Texture); - bd->Texture = NULL; + bd->Texture = nullptr; } if (bd->MouseCursorInvisible) { al_destroy_mouse_cursor(bd->MouseCursorInvisible); - bd->MouseCursorInvisible = NULL; + bd->MouseCursorInvisible = nullptr; } } @@ -274,10 +307,123 @@ static void ImGui_ImplAllegro5_SetClipboardText(void*, const char* text) } #endif +static ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code) +{ + switch (key_code) + { + case ALLEGRO_KEY_TAB: return ImGuiKey_Tab; + case ALLEGRO_KEY_LEFT: return ImGuiKey_LeftArrow; + case ALLEGRO_KEY_RIGHT: return ImGuiKey_RightArrow; + case ALLEGRO_KEY_UP: return ImGuiKey_UpArrow; + case ALLEGRO_KEY_DOWN: return ImGuiKey_DownArrow; + case ALLEGRO_KEY_PGUP: return ImGuiKey_PageUp; + case ALLEGRO_KEY_PGDN: return ImGuiKey_PageDown; + case ALLEGRO_KEY_HOME: return ImGuiKey_Home; + case ALLEGRO_KEY_END: return ImGuiKey_End; + case ALLEGRO_KEY_INSERT: return ImGuiKey_Insert; + case ALLEGRO_KEY_DELETE: return ImGuiKey_Delete; + case ALLEGRO_KEY_BACKSPACE: return ImGuiKey_Backspace; + case ALLEGRO_KEY_SPACE: return ImGuiKey_Space; + case ALLEGRO_KEY_ENTER: return ImGuiKey_Enter; + case ALLEGRO_KEY_ESCAPE: return ImGuiKey_Escape; + case ALLEGRO_KEY_QUOTE: return ImGuiKey_Apostrophe; + case ALLEGRO_KEY_COMMA: return ImGuiKey_Comma; + case ALLEGRO_KEY_MINUS: return ImGuiKey_Minus; + case ALLEGRO_KEY_FULLSTOP: return ImGuiKey_Period; + case ALLEGRO_KEY_SLASH: return ImGuiKey_Slash; + case ALLEGRO_KEY_SEMICOLON: return ImGuiKey_Semicolon; + case ALLEGRO_KEY_EQUALS: return ImGuiKey_Equal; + case ALLEGRO_KEY_OPENBRACE: return ImGuiKey_LeftBracket; + case ALLEGRO_KEY_BACKSLASH: return ImGuiKey_Backslash; + case ALLEGRO_KEY_CLOSEBRACE: return ImGuiKey_RightBracket; + case ALLEGRO_KEY_TILDE: return ImGuiKey_GraveAccent; + case ALLEGRO_KEY_CAPSLOCK: return ImGuiKey_CapsLock; + case ALLEGRO_KEY_SCROLLLOCK: return ImGuiKey_ScrollLock; + case ALLEGRO_KEY_NUMLOCK: return ImGuiKey_NumLock; + case ALLEGRO_KEY_PRINTSCREEN: return ImGuiKey_PrintScreen; + case ALLEGRO_KEY_PAUSE: return ImGuiKey_Pause; + case ALLEGRO_KEY_PAD_0: return ImGuiKey_Keypad0; + case ALLEGRO_KEY_PAD_1: return ImGuiKey_Keypad1; + case ALLEGRO_KEY_PAD_2: return ImGuiKey_Keypad2; + case ALLEGRO_KEY_PAD_3: return ImGuiKey_Keypad3; + case ALLEGRO_KEY_PAD_4: return ImGuiKey_Keypad4; + case ALLEGRO_KEY_PAD_5: return ImGuiKey_Keypad5; + case ALLEGRO_KEY_PAD_6: return ImGuiKey_Keypad6; + case ALLEGRO_KEY_PAD_7: return ImGuiKey_Keypad7; + case ALLEGRO_KEY_PAD_8: return ImGuiKey_Keypad8; + case ALLEGRO_KEY_PAD_9: return ImGuiKey_Keypad9; + case ALLEGRO_KEY_PAD_DELETE: return ImGuiKey_KeypadDecimal; + case ALLEGRO_KEY_PAD_SLASH: return ImGuiKey_KeypadDivide; + case ALLEGRO_KEY_PAD_ASTERISK: return ImGuiKey_KeypadMultiply; + case ALLEGRO_KEY_PAD_MINUS: return ImGuiKey_KeypadSubtract; + case ALLEGRO_KEY_PAD_PLUS: return ImGuiKey_KeypadAdd; + case ALLEGRO_KEY_PAD_ENTER: return ImGuiKey_KeypadEnter; + case ALLEGRO_KEY_PAD_EQUALS: return ImGuiKey_KeypadEqual; + case ALLEGRO_KEY_LCTRL: return ImGuiKey_LeftCtrl; + case ALLEGRO_KEY_LSHIFT: return ImGuiKey_LeftShift; + case ALLEGRO_KEY_ALT: return ImGuiKey_LeftAlt; + case ALLEGRO_KEY_LWIN: return ImGuiKey_LeftSuper; + case ALLEGRO_KEY_RCTRL: return ImGuiKey_RightCtrl; + case ALLEGRO_KEY_RSHIFT: return ImGuiKey_RightShift; + case ALLEGRO_KEY_ALTGR: return ImGuiKey_RightAlt; + case ALLEGRO_KEY_RWIN: return ImGuiKey_RightSuper; + case ALLEGRO_KEY_MENU: return ImGuiKey_Menu; + case ALLEGRO_KEY_0: return ImGuiKey_0; + case ALLEGRO_KEY_1: return ImGuiKey_1; + case ALLEGRO_KEY_2: return ImGuiKey_2; + case ALLEGRO_KEY_3: return ImGuiKey_3; + case ALLEGRO_KEY_4: return ImGuiKey_4; + case ALLEGRO_KEY_5: return ImGuiKey_5; + case ALLEGRO_KEY_6: return ImGuiKey_6; + case ALLEGRO_KEY_7: return ImGuiKey_7; + case ALLEGRO_KEY_8: return ImGuiKey_8; + case ALLEGRO_KEY_9: return ImGuiKey_9; + case ALLEGRO_KEY_A: return ImGuiKey_A; + case ALLEGRO_KEY_B: return ImGuiKey_B; + case ALLEGRO_KEY_C: return ImGuiKey_C; + case ALLEGRO_KEY_D: return ImGuiKey_D; + case ALLEGRO_KEY_E: return ImGuiKey_E; + case ALLEGRO_KEY_F: return ImGuiKey_F; + case ALLEGRO_KEY_G: return ImGuiKey_G; + case ALLEGRO_KEY_H: return ImGuiKey_H; + case ALLEGRO_KEY_I: return ImGuiKey_I; + case ALLEGRO_KEY_J: return ImGuiKey_J; + case ALLEGRO_KEY_K: return ImGuiKey_K; + case ALLEGRO_KEY_L: return ImGuiKey_L; + case ALLEGRO_KEY_M: return ImGuiKey_M; + case ALLEGRO_KEY_N: return ImGuiKey_N; + case ALLEGRO_KEY_O: return ImGuiKey_O; + case ALLEGRO_KEY_P: return ImGuiKey_P; + case ALLEGRO_KEY_Q: return ImGuiKey_Q; + case ALLEGRO_KEY_R: return ImGuiKey_R; + case ALLEGRO_KEY_S: return ImGuiKey_S; + case ALLEGRO_KEY_T: return ImGuiKey_T; + case ALLEGRO_KEY_U: return ImGuiKey_U; + case ALLEGRO_KEY_V: return ImGuiKey_V; + case ALLEGRO_KEY_W: return ImGuiKey_W; + case ALLEGRO_KEY_X: return ImGuiKey_X; + case ALLEGRO_KEY_Y: return ImGuiKey_Y; + case ALLEGRO_KEY_Z: return ImGuiKey_Z; + case ALLEGRO_KEY_F1: return ImGuiKey_F1; + case ALLEGRO_KEY_F2: return ImGuiKey_F2; + case ALLEGRO_KEY_F3: return ImGuiKey_F3; + case ALLEGRO_KEY_F4: return ImGuiKey_F4; + case ALLEGRO_KEY_F5: return ImGuiKey_F5; + case ALLEGRO_KEY_F6: return ImGuiKey_F6; + case ALLEGRO_KEY_F7: return ImGuiKey_F7; + case ALLEGRO_KEY_F8: return ImGuiKey_F8; + case ALLEGRO_KEY_F9: return ImGuiKey_F9; + case ALLEGRO_KEY_F10: return ImGuiKey_F10; + case ALLEGRO_KEY_F11: return ImGuiKey_F11; + case ALLEGRO_KEY_F12: return ImGuiKey_F12; + default: return ImGuiKey_None; + } +} + bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!"); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); // Setup backend capabilities flags ImGui_ImplAllegro5_Data* bd = IM_NEW(ImGui_ImplAllegro5_Data)(); @@ -292,41 +438,17 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion. ALLEGRO_VERTEX_ELEMENT elems[] = { - { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, pos) }, - { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, uv) }, - { ALLEGRO_PRIM_COLOR_ATTR, 0, IM_OFFSETOF(ImDrawVertAllegro, col) }, + { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, pos) }, + { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, uv) }, + { ALLEGRO_PRIM_COLOR_ATTR, 0, offsetof(ImDrawVertAllegro, col) }, { 0, 0, 0 } }; bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); - io.KeyMap[ImGuiKey_Tab] = ALLEGRO_KEY_TAB; - io.KeyMap[ImGuiKey_LeftArrow] = ALLEGRO_KEY_LEFT; - io.KeyMap[ImGuiKey_RightArrow] = ALLEGRO_KEY_RIGHT; - io.KeyMap[ImGuiKey_UpArrow] = ALLEGRO_KEY_UP; - io.KeyMap[ImGuiKey_DownArrow] = ALLEGRO_KEY_DOWN; - io.KeyMap[ImGuiKey_PageUp] = ALLEGRO_KEY_PGUP; - io.KeyMap[ImGuiKey_PageDown] = ALLEGRO_KEY_PGDN; - io.KeyMap[ImGuiKey_Home] = ALLEGRO_KEY_HOME; - io.KeyMap[ImGuiKey_End] = ALLEGRO_KEY_END; - io.KeyMap[ImGuiKey_Insert] = ALLEGRO_KEY_INSERT; - io.KeyMap[ImGuiKey_Delete] = ALLEGRO_KEY_DELETE; - io.KeyMap[ImGuiKey_Backspace] = ALLEGRO_KEY_BACKSPACE; - io.KeyMap[ImGuiKey_Space] = ALLEGRO_KEY_SPACE; - io.KeyMap[ImGuiKey_Enter] = ALLEGRO_KEY_ENTER; - io.KeyMap[ImGuiKey_Escape] = ALLEGRO_KEY_ESCAPE; - io.KeyMap[ImGuiKey_KeyPadEnter] = ALLEGRO_KEY_PAD_ENTER; - io.KeyMap[ImGuiKey_A] = ALLEGRO_KEY_A; - io.KeyMap[ImGuiKey_C] = ALLEGRO_KEY_C; - io.KeyMap[ImGuiKey_V] = ALLEGRO_KEY_V; - io.KeyMap[ImGuiKey_X] = ALLEGRO_KEY_X; - io.KeyMap[ImGuiKey_Y] = ALLEGRO_KEY_Y; - io.KeyMap[ImGuiKey_Z] = ALLEGRO_KEY_Z; - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - #if ALLEGRO_HAS_CLIPBOARD io.SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText; - io.ClipboardUserData = NULL; + io.ClipboardUserData = nullptr; #endif return true; @@ -335,7 +457,7 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) void ImGui_ImplAllegro5_Shutdown() { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); - IM_ASSERT(bd != NULL && "No platform backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplAllegro5_InvalidateDeviceObjects(); @@ -344,14 +466,27 @@ void ImGui_ImplAllegro5_Shutdown() if (bd->ClipboardTextData) al_free(bd->ClipboardTextData); - io.BackendPlatformUserData = NULL; - io.BackendPlatformName = io.BackendRendererName = NULL; + io.BackendPlatformName = io.BackendRendererName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_HasMouseCursors; IM_DELETE(bd); } +// ev->keyboard.modifiers seems always zero so using that... +static void ImGui_ImplAllegro5_UpdateKeyModifiers() +{ + ImGuiIO& io = ImGui::GetIO(); + ALLEGRO_KEYBOARD_STATE keys; + al_get_keyboard_state(&keys); + io.AddKeyEvent(ImGuiMod_Ctrl, al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL)); + io.AddKeyEvent(ImGuiMod_Shift, al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT)); + io.AddKeyEvent(ImGuiMod_Alt, al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR)); + io.AddKeyEvent(ImGuiMod_Super, al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN)); +} + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. -// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. -// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) { @@ -363,29 +498,28 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) case ALLEGRO_EVENT_MOUSE_AXES: if (ev->mouse.display == bd->Display) { - io.MouseWheel += ev->mouse.dz; - io.MouseWheelH -= ev->mouse.dw; - io.MousePos = ImVec2(ev->mouse.x, ev->mouse.y); + io.AddMousePosEvent(ev->mouse.x, ev->mouse.y); + io.AddMouseWheelEvent(-ev->mouse.dw, ev->mouse.dz); } return true; case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: case ALLEGRO_EVENT_MOUSE_BUTTON_UP: - if (ev->mouse.display == bd->Display && ev->mouse.button <= 5) - io.MouseDown[ev->mouse.button - 1] = (ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN); + if (ev->mouse.display == bd->Display && ev->mouse.button > 0 && ev->mouse.button <= 5) + io.AddMouseButtonEvent(ev->mouse.button - 1, ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN); return true; case ALLEGRO_EVENT_TOUCH_MOVE: if (ev->touch.display == bd->Display) - io.MousePos = ImVec2(ev->touch.x, ev->touch.y); + io.AddMousePosEvent(ev->touch.x, ev->touch.y); return true; case ALLEGRO_EVENT_TOUCH_BEGIN: case ALLEGRO_EVENT_TOUCH_END: case ALLEGRO_EVENT_TOUCH_CANCEL: if (ev->touch.display == bd->Display && ev->touch.primary) - io.MouseDown[0] = (ev->type == ALLEGRO_EVENT_TOUCH_BEGIN); + io.AddMouseButtonEvent(0, ev->type == ALLEGRO_EVENT_TOUCH_BEGIN); return true; case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY: if (ev->mouse.display == bd->Display) - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); return true; case ALLEGRO_EVENT_KEY_CHAR: if (ev->keyboard.display == bd->Display) @@ -395,7 +529,12 @@ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_UP: if (ev->keyboard.display == bd->Display) - io.KeysDown[ev->keyboard.keycode] = (ev->type == ALLEGRO_EVENT_KEY_DOWN); + { + ImGui_ImplAllegro5_UpdateKeyModifiers(); + ImGuiKey key = ImGui_ImplAllegro5_KeyCodeToImGuiKey(ev->keyboard.keycode); + io.AddKeyEvent(key, (ev->type == ALLEGRO_EVENT_KEY_DOWN)); + io.SetKeyEventNativeData(key, ev->keyboard.keycode, -1); // To support legacy indexing (<1.87 user code) + } return true; case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT: if (ev->display.source == bd->Display) @@ -447,7 +586,7 @@ static void ImGui_ImplAllegro5_UpdateMouseCursor() void ImGui_ImplAllegro5_NewFrame() { ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplAllegro5_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplAllegro5_Init()?"); if (!bd->Texture) ImGui_ImplAllegro5_CreateDeviceObjects(); @@ -465,13 +604,10 @@ void ImGui_ImplAllegro5_NewFrame() io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f); bd->Time = current_time; - // Setup inputs - ALLEGRO_KEYBOARD_STATE keys; - al_get_keyboard_state(&keys); - io.KeyCtrl = al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL); - io.KeyShift = al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT); - io.KeyAlt = al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR); - io.KeySuper = al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN); - + // Setup mouse cursor shape ImGui_ImplAllegro5_UpdateMouseCursor(); } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_allegro5.h b/third_party/imgui/backends/imgui_impl_allegro5.h index 06c7120b287..5b63654ef9c 100644 --- a/third_party/imgui/backends/imgui_impl_allegro5.h +++ b/third_party/imgui/backends/imgui_impl_allegro5.h @@ -3,19 +3,24 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Clipboard support (from Allegro 5.1.12) // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // Issues: // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. // [ ] Platform: Missing gamepad support. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE struct ALLEGRO_DISPLAY; union ALLEGRO_EVENT; @@ -29,3 +34,5 @@ IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_android.cpp b/third_party/imgui/backends/imgui_impl_android.cpp index aae8e6b8d73..7dd2afc2efc 100644 --- a/third_party/imgui/backends/imgui_impl_android.cpp +++ b/third_party/imgui/backends/imgui_impl_android.cpp @@ -2,29 +2,37 @@ // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3) // Implemented features: -// [X] Platform: Keyboard arrays indexed using AKEYCODE_* codes, e.g. ImGui::IsKeyPressed(AKEYCODE_SPACE). +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // Missing features: // [ ] Platform: Clipboard support. // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. // Important: +// - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446) // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446) -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). +// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. +// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2021-03-04: Initial version. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_android.h" #include -#include -#include #include #include #include @@ -34,9 +42,121 @@ static double g_Time = 0.0; static ANativeWindow* g_Window; static char g_LogTag[] = "ImGuiExample"; -static std::map> g_KeyEventQueues; // FIXME: Remove dependency on map and queue once we use upcoming input queue. -int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event) +static ImGuiKey ImGui_ImplAndroid_KeyCodeToImGuiKey(int32_t key_code) +{ + switch (key_code) + { + case AKEYCODE_TAB: return ImGuiKey_Tab; + case AKEYCODE_DPAD_LEFT: return ImGuiKey_LeftArrow; + case AKEYCODE_DPAD_RIGHT: return ImGuiKey_RightArrow; + case AKEYCODE_DPAD_UP: return ImGuiKey_UpArrow; + case AKEYCODE_DPAD_DOWN: return ImGuiKey_DownArrow; + case AKEYCODE_PAGE_UP: return ImGuiKey_PageUp; + case AKEYCODE_PAGE_DOWN: return ImGuiKey_PageDown; + case AKEYCODE_MOVE_HOME: return ImGuiKey_Home; + case AKEYCODE_MOVE_END: return ImGuiKey_End; + case AKEYCODE_INSERT: return ImGuiKey_Insert; + case AKEYCODE_FORWARD_DEL: return ImGuiKey_Delete; + case AKEYCODE_DEL: return ImGuiKey_Backspace; + case AKEYCODE_SPACE: return ImGuiKey_Space; + case AKEYCODE_ENTER: return ImGuiKey_Enter; + case AKEYCODE_ESCAPE: return ImGuiKey_Escape; + case AKEYCODE_APOSTROPHE: return ImGuiKey_Apostrophe; + case AKEYCODE_COMMA: return ImGuiKey_Comma; + case AKEYCODE_MINUS: return ImGuiKey_Minus; + case AKEYCODE_PERIOD: return ImGuiKey_Period; + case AKEYCODE_SLASH: return ImGuiKey_Slash; + case AKEYCODE_SEMICOLON: return ImGuiKey_Semicolon; + case AKEYCODE_EQUALS: return ImGuiKey_Equal; + case AKEYCODE_LEFT_BRACKET: return ImGuiKey_LeftBracket; + case AKEYCODE_BACKSLASH: return ImGuiKey_Backslash; + case AKEYCODE_RIGHT_BRACKET: return ImGuiKey_RightBracket; + case AKEYCODE_GRAVE: return ImGuiKey_GraveAccent; + case AKEYCODE_CAPS_LOCK: return ImGuiKey_CapsLock; + case AKEYCODE_SCROLL_LOCK: return ImGuiKey_ScrollLock; + case AKEYCODE_NUM_LOCK: return ImGuiKey_NumLock; + case AKEYCODE_SYSRQ: return ImGuiKey_PrintScreen; + case AKEYCODE_BREAK: return ImGuiKey_Pause; + case AKEYCODE_NUMPAD_0: return ImGuiKey_Keypad0; + case AKEYCODE_NUMPAD_1: return ImGuiKey_Keypad1; + case AKEYCODE_NUMPAD_2: return ImGuiKey_Keypad2; + case AKEYCODE_NUMPAD_3: return ImGuiKey_Keypad3; + case AKEYCODE_NUMPAD_4: return ImGuiKey_Keypad4; + case AKEYCODE_NUMPAD_5: return ImGuiKey_Keypad5; + case AKEYCODE_NUMPAD_6: return ImGuiKey_Keypad6; + case AKEYCODE_NUMPAD_7: return ImGuiKey_Keypad7; + case AKEYCODE_NUMPAD_8: return ImGuiKey_Keypad8; + case AKEYCODE_NUMPAD_9: return ImGuiKey_Keypad9; + case AKEYCODE_NUMPAD_DOT: return ImGuiKey_KeypadDecimal; + case AKEYCODE_NUMPAD_DIVIDE: return ImGuiKey_KeypadDivide; + case AKEYCODE_NUMPAD_MULTIPLY: return ImGuiKey_KeypadMultiply; + case AKEYCODE_NUMPAD_SUBTRACT: return ImGuiKey_KeypadSubtract; + case AKEYCODE_NUMPAD_ADD: return ImGuiKey_KeypadAdd; + case AKEYCODE_NUMPAD_ENTER: return ImGuiKey_KeypadEnter; + case AKEYCODE_NUMPAD_EQUALS: return ImGuiKey_KeypadEqual; + case AKEYCODE_CTRL_LEFT: return ImGuiKey_LeftCtrl; + case AKEYCODE_SHIFT_LEFT: return ImGuiKey_LeftShift; + case AKEYCODE_ALT_LEFT: return ImGuiKey_LeftAlt; + case AKEYCODE_META_LEFT: return ImGuiKey_LeftSuper; + case AKEYCODE_CTRL_RIGHT: return ImGuiKey_RightCtrl; + case AKEYCODE_SHIFT_RIGHT: return ImGuiKey_RightShift; + case AKEYCODE_ALT_RIGHT: return ImGuiKey_RightAlt; + case AKEYCODE_META_RIGHT: return ImGuiKey_RightSuper; + case AKEYCODE_MENU: return ImGuiKey_Menu; + case AKEYCODE_0: return ImGuiKey_0; + case AKEYCODE_1: return ImGuiKey_1; + case AKEYCODE_2: return ImGuiKey_2; + case AKEYCODE_3: return ImGuiKey_3; + case AKEYCODE_4: return ImGuiKey_4; + case AKEYCODE_5: return ImGuiKey_5; + case AKEYCODE_6: return ImGuiKey_6; + case AKEYCODE_7: return ImGuiKey_7; + case AKEYCODE_8: return ImGuiKey_8; + case AKEYCODE_9: return ImGuiKey_9; + case AKEYCODE_A: return ImGuiKey_A; + case AKEYCODE_B: return ImGuiKey_B; + case AKEYCODE_C: return ImGuiKey_C; + case AKEYCODE_D: return ImGuiKey_D; + case AKEYCODE_E: return ImGuiKey_E; + case AKEYCODE_F: return ImGuiKey_F; + case AKEYCODE_G: return ImGuiKey_G; + case AKEYCODE_H: return ImGuiKey_H; + case AKEYCODE_I: return ImGuiKey_I; + case AKEYCODE_J: return ImGuiKey_J; + case AKEYCODE_K: return ImGuiKey_K; + case AKEYCODE_L: return ImGuiKey_L; + case AKEYCODE_M: return ImGuiKey_M; + case AKEYCODE_N: return ImGuiKey_N; + case AKEYCODE_O: return ImGuiKey_O; + case AKEYCODE_P: return ImGuiKey_P; + case AKEYCODE_Q: return ImGuiKey_Q; + case AKEYCODE_R: return ImGuiKey_R; + case AKEYCODE_S: return ImGuiKey_S; + case AKEYCODE_T: return ImGuiKey_T; + case AKEYCODE_U: return ImGuiKey_U; + case AKEYCODE_V: return ImGuiKey_V; + case AKEYCODE_W: return ImGuiKey_W; + case AKEYCODE_X: return ImGuiKey_X; + case AKEYCODE_Y: return ImGuiKey_Y; + case AKEYCODE_Z: return ImGuiKey_Z; + case AKEYCODE_F1: return ImGuiKey_F1; + case AKEYCODE_F2: return ImGuiKey_F2; + case AKEYCODE_F3: return ImGuiKey_F3; + case AKEYCODE_F4: return ImGuiKey_F4; + case AKEYCODE_F5: return ImGuiKey_F5; + case AKEYCODE_F6: return ImGuiKey_F6; + case AKEYCODE_F7: return ImGuiKey_F7; + case AKEYCODE_F8: return ImGuiKey_F8; + case AKEYCODE_F9: return ImGuiKey_F9; + case AKEYCODE_F10: return ImGuiKey_F10; + case AKEYCODE_F11: return ImGuiKey_F11; + case AKEYCODE_F12: return ImGuiKey_F12; + default: return ImGuiKey_None; + } +} + +int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event) { ImGuiIO& io = ImGui::GetIO(); int32_t event_type = AInputEvent_getType(input_event); @@ -45,12 +165,14 @@ int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event) case AINPUT_EVENT_TYPE_KEY: { int32_t event_key_code = AKeyEvent_getKeyCode(input_event); + int32_t event_scan_code = AKeyEvent_getScanCode(input_event); int32_t event_action = AKeyEvent_getAction(input_event); int32_t event_meta_state = AKeyEvent_getMetaState(input_event); - io.KeyCtrl = ((event_meta_state & AMETA_CTRL_ON) != 0); - io.KeyShift = ((event_meta_state & AMETA_SHIFT_ON) != 0); - io.KeyAlt = ((event_meta_state & AMETA_ALT_ON) != 0); + io.AddKeyEvent(ImGuiMod_Ctrl, (event_meta_state & AMETA_CTRL_ON) != 0); + io.AddKeyEvent(ImGuiMod_Shift, (event_meta_state & AMETA_SHIFT_ON) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (event_meta_state & AMETA_ALT_ON) != 0); + io.AddKeyEvent(ImGuiMod_Super, (event_meta_state & AMETA_META_ON) != 0); switch (event_action) { @@ -59,8 +181,16 @@ int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event) // ImGui_ImplAndroid_NewFrame()...or consider using IO queue, if suitable: https://github.com/ocornut/imgui/issues/2787 case AKEY_EVENT_ACTION_DOWN: case AKEY_EVENT_ACTION_UP: - g_KeyEventQueues[event_key_code].push(event_action); + { + ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code); + if (key != ImGuiKey_None) + { + io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN); + io.SetKeyEventNativeData(key, event_key_code, event_scan_code); + } + break; + } default: break; } @@ -71,36 +201,53 @@ int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event) int32_t event_action = AMotionEvent_getAction(input_event); int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; event_action &= AMOTION_EVENT_ACTION_MASK; + + switch (AMotionEvent_getToolType(input_event, event_pointer_index)) + { + case AMOTION_EVENT_TOOL_TYPE_MOUSE: + io.AddMouseSourceEvent(ImGuiMouseSource_Mouse); + break; + case AMOTION_EVENT_TOOL_TYPE_STYLUS: + case AMOTION_EVENT_TOOL_TYPE_ERASER: + io.AddMouseSourceEvent(ImGuiMouseSource_Pen); + break; + case AMOTION_EVENT_TOOL_TYPE_FINGER: + default: + io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen); + break; + } + switch (event_action) { case AMOTION_EVENT_ACTION_DOWN: case AMOTION_EVENT_ACTION_UP: + { // Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP, // but we have to process them separately to identify the actual button pressed. This is done below via // AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback). - if((AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_FINGER) - || (AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)) + int tool_type = AMotionEvent_getToolType(input_event, event_pointer_index); + if (tool_type == AMOTION_EVENT_TOOL_TYPE_FINGER || tool_type == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { - io.MouseDown[0] = (event_action == AMOTION_EVENT_ACTION_DOWN); - io.MousePos = ImVec2(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); + io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); + io.AddMouseButtonEvent(0, event_action == AMOTION_EVENT_ACTION_DOWN); } break; + } case AMOTION_EVENT_ACTION_BUTTON_PRESS: case AMOTION_EVENT_ACTION_BUTTON_RELEASE: - { - int32_t button_state = AMotionEvent_getButtonState(input_event); - io.MouseDown[0] = ((button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0); - io.MouseDown[1] = ((button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0); - io.MouseDown[2] = ((button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0); - } + { + int32_t button_state = AMotionEvent_getButtonState(input_event); + io.AddMouseButtonEvent(0, (button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0); + io.AddMouseButtonEvent(1, (button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0); + io.AddMouseButtonEvent(2, (button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0); break; + } case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse) case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN - io.MousePos = ImVec2(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); + io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); break; case AMOTION_EVENT_ACTION_SCROLL: - io.MouseWheel = AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_VSCROLL, event_pointer_index); - io.MouseWheelH = AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_HSCROLL, event_pointer_index); + io.AddMouseWheelEvent(AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_HSCROLL, event_pointer_index), AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_VSCROLL, event_pointer_index)); break; default: break; @@ -123,51 +270,19 @@ bool ImGui_ImplAndroid_Init(ANativeWindow* window) ImGuiIO& io = ImGui::GetIO(); io.BackendPlatformName = "imgui_impl_android"; - // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array. - io.KeyMap[ImGuiKey_Tab] = AKEYCODE_TAB; - io.KeyMap[ImGuiKey_LeftArrow] = AKEYCODE_DPAD_LEFT; // also covers physical keyboard arrow key - io.KeyMap[ImGuiKey_RightArrow] = AKEYCODE_DPAD_RIGHT; // also covers physical keyboard arrow key - io.KeyMap[ImGuiKey_UpArrow] = AKEYCODE_DPAD_UP; // also covers physical keyboard arrow key - io.KeyMap[ImGuiKey_DownArrow] = AKEYCODE_DPAD_DOWN; // also covers physical keyboard arrow key - io.KeyMap[ImGuiKey_PageUp] = AKEYCODE_PAGE_UP; - io.KeyMap[ImGuiKey_PageDown] = AKEYCODE_PAGE_DOWN; - io.KeyMap[ImGuiKey_Home] = AKEYCODE_MOVE_HOME; - io.KeyMap[ImGuiKey_End] = AKEYCODE_MOVE_END; - io.KeyMap[ImGuiKey_Insert] = AKEYCODE_INSERT; - io.KeyMap[ImGuiKey_Delete] = AKEYCODE_FORWARD_DEL; - io.KeyMap[ImGuiKey_Backspace] = AKEYCODE_DEL; - io.KeyMap[ImGuiKey_Space] = AKEYCODE_SPACE; - io.KeyMap[ImGuiKey_Enter] = AKEYCODE_ENTER; - io.KeyMap[ImGuiKey_Escape] = AKEYCODE_ESCAPE; - io.KeyMap[ImGuiKey_KeyPadEnter] = AKEYCODE_NUMPAD_ENTER; - io.KeyMap[ImGuiKey_A] = AKEYCODE_A; - io.KeyMap[ImGuiKey_C] = AKEYCODE_C; - io.KeyMap[ImGuiKey_V] = AKEYCODE_V; - io.KeyMap[ImGuiKey_X] = AKEYCODE_X; - io.KeyMap[ImGuiKey_Y] = AKEYCODE_Y; - io.KeyMap[ImGuiKey_Z] = AKEYCODE_Z; - return true; } void ImGui_ImplAndroid_Shutdown() { + ImGuiIO& io = ImGui::GetIO(); + io.BackendPlatformName = nullptr; } void ImGui_ImplAndroid_NewFrame() { ImGuiIO& io = ImGui::GetIO(); - // Process queued key events - // FIXME: This is a workaround for multiple key event actions occurring at once (see above) and can be removed once we use upcoming input queue. - for (auto& key_queue : g_KeyEventQueues) - { - if (key_queue.second.empty()) - continue; - io.KeysDown[key_queue.first] = (key_queue.second.front() == AKEY_EVENT_ACTION_DOWN); - key_queue.second.pop(); - } - // Setup display size (every frame to accommodate for window resizing) int32_t window_width = ANativeWindow_getWidth(g_Window); int32_t window_height = ANativeWindow_getHeight(g_Window); @@ -185,3 +300,7 @@ void ImGui_ImplAndroid_NewFrame() io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_android.h b/third_party/imgui/backends/imgui_impl_android.h index 92b466b6654..557bf0e0921 100644 --- a/third_party/imgui/backends/imgui_impl_android.h +++ b/third_party/imgui/backends/imgui_impl_android.h @@ -2,26 +2,35 @@ // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3) // Implemented features: -// [X] Platform: Keyboard arrays indexed using AKEYCODE_* codes, e.g. ImGui::IsKeyPressed(AKEYCODE_SPACE). +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. // Missing features: // [ ] Platform: Clipboard support. // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. // Important: +// - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446) // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446) -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE struct ANativeWindow; struct AInputEvent; IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window); -IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event); +IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event); IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown(); IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx10.cpp b/third_party/imgui/backends/imgui_impl_dx10.cpp index 79bf731d0ad..96e27471c4d 100644 --- a/third_party/imgui/backends/imgui_impl_dx10.cpp +++ b/third_party/imgui/backends/imgui_impl_dx10.cpp @@ -2,16 +2,20 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture backend. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX10: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: DirectX10: Change blending equation to preserve alpha in output buffer. @@ -29,6 +33,7 @@ // 2016-05-07: DirectX10: Disabling depth-write. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_dx10.h" // DirectX @@ -59,10 +64,10 @@ struct ImGui_ImplDX10_Data int VertexBufferSize; int IndexBufferSize; - ImGui_ImplDX10_Data() { memset(this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } + ImGui_ImplDX10_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } }; -struct VERTEX_CONSTANT_BUFFER +struct VERTEX_CONSTANT_BUFFER_DX10 { float mvp[4][4]; }; @@ -71,7 +76,7 @@ struct VERTEX_CONSTANT_BUFFER // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions @@ -100,7 +105,7 @@ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); ctx->PSSetShader(bd->pPixelShader); ctx->PSSetSamplers(0, 1, &bd->pFontSampler); - ctx->GSSetShader(NULL); + ctx->GSSetShader(nullptr); // Setup render state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; @@ -122,7 +127,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) // Create and grow vertex/index buffers if needed if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { - if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; } + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D10_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); @@ -131,13 +136,13 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) desc.BindFlags = D3D10_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; desc.MiscFlags = 0; - if (ctx->CreateBuffer(&desc, NULL, &bd->pVB) < 0) + if (ctx->CreateBuffer(&desc, nullptr, &bd->pVB) < 0) return; } if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) { - if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; } + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D10_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D10_BUFFER_DESC)); @@ -145,13 +150,13 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D10_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; - if (ctx->CreateBuffer(&desc, NULL, &bd->pIB) < 0) + if (ctx->CreateBuffer(&desc, nullptr, &bd->pIB) < 0) return; } // Copy and convert all vertices into a single contiguous buffer - ImDrawVert* vtx_dst = NULL; - ImDrawIdx* idx_dst = NULL; + ImDrawVert* vtx_dst = nullptr; + ImDrawIdx* idx_dst = nullptr; bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst); bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst); for (int n = 0; n < draw_data->CmdListsCount; n++) @@ -171,7 +176,7 @@ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data) void* mapped_resource; if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) return; - VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource; + VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource; float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; @@ -314,13 +319,13 @@ static void ImGui_ImplDX10_CreateFontsTexture() desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - ID3D10Texture2D* pTexture = NULL; + ID3D10Texture2D* pTexture = nullptr; D3D10_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); - IM_ASSERT(pTexture != NULL); + IM_ASSERT(pTexture != nullptr); // Create texture view D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc; @@ -337,6 +342,7 @@ static void ImGui_ImplDX10_CreateFontsTexture() io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView); // Create texture sampler + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) { D3D10_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); @@ -397,7 +403,7 @@ bool ImGui_ImplDX10_CreateDeviceObjects() }"; ID3DBlob* vertexShaderBlob; - if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL))) + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pVertexShader) != S_OK) { @@ -408,9 +414,9 @@ bool ImGui_ImplDX10_CreateDeviceObjects() // Create the input layout D3D10_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) { @@ -422,12 +428,12 @@ bool ImGui_ImplDX10_CreateDeviceObjects() // Create the constant buffer { D3D10_BUFFER_DESC desc; - desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER); + desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10); desc.Usage = D3D10_USAGE_DYNAMIC; desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; desc.MiscFlags = 0; - bd->pd3dDevice->CreateBuffer(&desc, NULL, &bd->pVertexConstantBuffer); + bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer); } } @@ -450,7 +456,7 @@ bool ImGui_ImplDX10_CreateDeviceObjects() }"; ID3DBlob* pixelShaderBlob; - if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL))) + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &bd->pPixelShader) != S_OK) { @@ -512,23 +518,23 @@ void ImGui_ImplDX10_InvalidateDeviceObjects() if (!bd->pd3dDevice) return; - if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = NULL; } - if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = NULL; ImGui::GetIO().Fonts->SetTexID(NULL); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. - if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; } - if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; } - if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = NULL; } - if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = NULL; } - if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = NULL; } - if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = NULL; } - if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = NULL; } - if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = NULL; } - if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = NULL; } + if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } + if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } + if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } + if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; } + if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; } + if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; } + if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; } + if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; } + if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; } } bool ImGui_ImplDX10_Init(ID3D10Device* device) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX10_Data* bd = IM_NEW(ImGui_ImplDX10_Data)(); @@ -537,9 +543,9 @@ bool ImGui_ImplDX10_Init(ID3D10Device* device) io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device - IDXGIDevice* pDXGIDevice = NULL; - IDXGIAdapter* pDXGIAdapter = NULL; - IDXGIFactory* pFactory = NULL; + IDXGIDevice* pDXGIDevice = nullptr; + IDXGIAdapter* pDXGIAdapter = nullptr; + IDXGIFactory* pFactory = nullptr; if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK) if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK) if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK) @@ -557,22 +563,27 @@ bool ImGui_ImplDX10_Init(ID3D10Device* device) void ImGui_ImplDX10_Shutdown() { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX10_InvalidateDeviceObjects(); if (bd->pFactory) { bd->pFactory->Release(); } if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplDX10_NewFrame() { ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplDX10_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX10_Init()?"); if (!bd->pFontSampler) ImGui_ImplDX10_CreateDeviceObjects(); } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx10.h b/third_party/imgui/backends/imgui_impl_dx10.h index 31e62aca202..e7e798aa496 100644 --- a/third_party/imgui/backends/imgui_impl_dx10.h +++ b/third_party/imgui/backends/imgui_impl_dx10.h @@ -2,16 +2,20 @@ // This needs to be used along with a Platform Backend (e.g. Win32) // Implemented features: -// [X] Renderer: User texture backend. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE struct ID3D10Device; @@ -23,3 +27,5 @@ IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx11.cpp b/third_party/imgui/backends/imgui_impl_dx11.cpp index 3f628cbc829..bbc26a7514e 100644 --- a/third_party/imgui/backends/imgui_impl_dx11.cpp +++ b/third_party/imgui/backends/imgui_impl_dx11.cpp @@ -3,15 +3,19 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer. @@ -30,6 +34,7 @@ // 2016-05-07: DirectX11: Disabling depth-write. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_dx11.h" // DirectX @@ -60,10 +65,10 @@ struct ImGui_ImplDX11_Data int VertexBufferSize; int IndexBufferSize; - ImGui_ImplDX11_Data() { memset(this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } + ImGui_ImplDX11_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } }; -struct VERTEX_CONSTANT_BUFFER +struct VERTEX_CONSTANT_BUFFER_DX11 { float mvp[4][4]; }; @@ -72,7 +77,7 @@ struct VERTEX_CONSTANT_BUFFER // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions @@ -97,14 +102,14 @@ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceC ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset); ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - ctx->VSSetShader(bd->pVertexShader, NULL, 0); + ctx->VSSetShader(bd->pVertexShader, nullptr, 0); ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); - ctx->PSSetShader(bd->pPixelShader, NULL, 0); + ctx->PSSetShader(bd->pPixelShader, nullptr, 0); ctx->PSSetSamplers(0, 1, &bd->pFontSampler); - ctx->GSSetShader(NULL, NULL, 0); - ctx->HSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used.. - ctx->DSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used.. - ctx->CSSetShader(NULL, NULL, 0); // In theory we should backup and restore this as well.. very infrequently used.. + ctx->GSSetShader(nullptr, nullptr, 0); + ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. + ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. + ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. // Setup blend state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; @@ -126,7 +131,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) // Create and grow vertex/index buffers if needed if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { - if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; } + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); @@ -135,12 +140,12 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; - if (bd->pd3dDevice->CreateBuffer(&desc, NULL, &bd->pVB) < 0) + if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0) return; } if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) { - if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; } + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); @@ -148,7 +153,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D11_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - if (bd->pd3dDevice->CreateBuffer(&desc, NULL, &bd->pIB) < 0) + if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0) return; } @@ -177,7 +182,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) D3D11_MAPPED_SUBRESOURCE mapped_resource; if (ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) return; - VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData; + VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData; float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; @@ -252,7 +257,7 @@ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != NULL) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) @@ -326,13 +331,13 @@ static void ImGui_ImplDX11_CreateFontsTexture() desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; - ID3D11Texture2D* pTexture = NULL; + ID3D11Texture2D* pTexture = nullptr; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); - IM_ASSERT(pTexture != NULL); + IM_ASSERT(pTexture != nullptr); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; @@ -349,6 +354,7 @@ static void ImGui_ImplDX11_CreateFontsTexture() io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView); // Create texture sampler + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) { D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); @@ -409,9 +415,9 @@ bool ImGui_ImplDX11_CreateDeviceObjects() }"; ID3DBlob* vertexShaderBlob; - if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &vertexShaderBlob, NULL))) + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), NULL, &bd->pVertexShader) != S_OK) + if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK) { vertexShaderBlob->Release(); return false; @@ -420,9 +426,9 @@ bool ImGui_ImplDX11_CreateDeviceObjects() // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) { @@ -434,12 +440,12 @@ bool ImGui_ImplDX11_CreateDeviceObjects() // Create the constant buffer { D3D11_BUFFER_DESC desc; - desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER); + desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11); desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; - bd->pd3dDevice->CreateBuffer(&desc, NULL, &bd->pVertexConstantBuffer); + bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer); } } @@ -462,9 +468,9 @@ bool ImGui_ImplDX11_CreateDeviceObjects() }"; ID3DBlob* pixelShaderBlob; - if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &pixelShaderBlob, NULL))) + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr))) return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! - if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), NULL, &bd->pPixelShader) != S_OK) + if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK) { pixelShaderBlob->Release(); return false; @@ -524,23 +530,23 @@ void ImGui_ImplDX11_InvalidateDeviceObjects() if (!bd->pd3dDevice) return; - if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = NULL; } - if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = NULL; ImGui::GetIO().Fonts->SetTexID(NULL); } // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well. - if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; } - if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; } - if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = NULL; } - if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = NULL; } - if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = NULL; } - if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = NULL; } - if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = NULL; } - if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = NULL; } - if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = NULL; } + if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } + if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well. + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } + if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } + if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; } + if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; } + if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; } + if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; } + if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; } + if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; } } bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)(); @@ -549,9 +555,9 @@ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_co io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. // Get factory from device - IDXGIDevice* pDXGIDevice = NULL; - IDXGIAdapter* pDXGIAdapter = NULL; - IDXGIFactory* pFactory = NULL; + IDXGIDevice* pDXGIDevice = nullptr; + IDXGIAdapter* pDXGIAdapter = nullptr; + IDXGIFactory* pFactory = nullptr; if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK) if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK) @@ -572,23 +578,28 @@ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_co void ImGui_ImplDX11_Shutdown() { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX11_InvalidateDeviceObjects(); if (bd->pFactory) { bd->pFactory->Release(); } if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); } - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplDX11_NewFrame() { ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplDX11_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX11_Init()?"); if (!bd->pFontSampler) ImGui_ImplDX11_CreateDeviceObjects(); } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx11.h b/third_party/imgui/backends/imgui_impl_dx11.h index a83bce1b34a..20887f37070 100644 --- a/third_party/imgui/backends/imgui_impl_dx11.h +++ b/third_party/imgui/backends/imgui_impl_dx11.h @@ -3,15 +3,19 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE struct ID3D11Device; struct ID3D11DeviceContext; @@ -24,3 +28,5 @@ IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx12.cpp b/third_party/imgui/backends/imgui_impl_dx12.cpp index e9d2e961322..15aadc05807 100644 --- a/third_party/imgui/backends/imgui_impl_dx12.cpp +++ b/third_party/imgui/backends/imgui_impl_dx12.cpp @@ -3,7 +3,7 @@ // Implemented features: // [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. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. @@ -15,11 +15,15 @@ // 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer. @@ -38,6 +42,7 @@ // 2018-02-22: Merged into master with all Win32 code synchronized to other examples. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_dx12.h" // DirectX @@ -49,6 +54,33 @@ #endif // DirectX data +struct ImGui_ImplDX12_RenderBuffers; +struct ImGui_ImplDX12_Data +{ + ID3D12Device* pd3dDevice; + ID3D12RootSignature* pRootSignature; + ID3D12PipelineState* pPipelineState; + DXGI_FORMAT RTVFormat; + ID3D12Resource* pFontTextureResource; + D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle; + D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle; + ID3D12DescriptorHeap* pd3dSrvDescHeap; + UINT numFramesInFlight; + + ImGui_ImplDX12_RenderBuffers* pFrameResources; + UINT frameIndex; + + ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); frameIndex = UINT_MAX; } +}; + +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + +// Buffers used during the rendering of a frame struct ImGui_ImplDX12_RenderBuffers { ID3D12Resource* IndexBuffer; @@ -57,35 +89,11 @@ struct ImGui_ImplDX12_RenderBuffers int VertexBufferSize; }; -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; - - ImGui_ImplDX12_RenderBuffers* pFrameResources; - UINT numFramesInFlight; - UINT frameIndex; - - ImGui_ImplDX12_Data() { memset(this, 0, sizeof(*this)); frameIndex = UINT_MAX; } -}; - -struct VERTEX_CONSTANT_BUFFER +struct VERTEX_CONSTANT_BUFFER_DX12 { float mvp[4][4]; }; -// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts -// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. -static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData() -{ - return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : NULL; -} - // Functions static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* ctx, ImGui_ImplDX12_RenderBuffers* fr) { @@ -93,7 +101,7 @@ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12Graphic // 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 vertex_constant_buffer; + VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer; { float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; @@ -149,7 +157,7 @@ static inline void SafeRelease(T*& res) { if (res) res->Release(); - res = NULL; + res = nullptr; } // Render function @@ -166,7 +174,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight]; // Create and grow vertex/index buffers if needed - if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount) + if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount) { SafeRelease(fr->VertexBuffer); fr->VertexBufferSize = draw_data->TotalVtxCount + 5000; @@ -186,10 +194,10 @@ 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, NULL, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) + if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0) return; } - if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount) + if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount) { SafeRelease(fr->IndexBuffer); fr->IndexBufferSize = draw_data->TotalIdxCount + 10000; @@ -209,7 +217,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, NULL, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) + if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0) return; } @@ -248,7 +256,7 @@ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandL for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != NULL) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) @@ -310,9 +318,9 @@ static void ImGui_ImplDX12_CreateFontsTexture() desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; desc.Flags = D3D12_RESOURCE_FLAG_NONE; - ID3D12Resource* pTexture = NULL; + ID3D12Resource* pTexture = nullptr; bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COPY_DEST, NULL, IID_PPV_ARGS(&pTexture)); + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture)); UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u); UINT uploadSize = height * uploadPitch; @@ -332,12 +340,12 @@ static void ImGui_ImplDX12_CreateFontsTexture() props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - ID3D12Resource* uploadBuffer = NULL; + ID3D12Resource* uploadBuffer = nullptr; HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, NULL, IID_PPV_ARGS(&uploadBuffer)); + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer)); IM_ASSERT(SUCCEEDED(hr)); - void* mapped = NULL; + void* mapped = nullptr; D3D12_RANGE range = { 0, uploadSize }; hr = uploadBuffer->Map(0, &range, &mapped); IM_ASSERT(SUCCEEDED(hr)); @@ -367,31 +375,31 @@ static void ImGui_ImplDX12_CreateFontsTexture() barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - ID3D12Fence* fence = NULL; + ID3D12Fence* fence = nullptr; hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); IM_ASSERT(SUCCEEDED(hr)); HANDLE event = CreateEvent(0, 0, 0, 0); - IM_ASSERT(event != NULL); + IM_ASSERT(event != nullptr); D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.NodeMask = 1; - ID3D12CommandQueue* cmdQueue = NULL; + ID3D12CommandQueue* cmdQueue = nullptr; hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue)); IM_ASSERT(SUCCEEDED(hr)); - ID3D12CommandAllocator* cmdAlloc = NULL; + ID3D12CommandAllocator* cmdAlloc = nullptr; hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc)); IM_ASSERT(SUCCEEDED(hr)); - ID3D12GraphicsCommandList* cmdList = NULL; - hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, NULL, IID_PPV_ARGS(&cmdList)); + ID3D12GraphicsCommandList* cmdList = nullptr; + hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList)); IM_ASSERT(SUCCEEDED(hr)); - cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, NULL); + cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr); cmdList->ResourceBarrier(1, &barrier); hr = cmdList->Close(); @@ -466,6 +474,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() 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; @@ -495,7 +504,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7. // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that. static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll"); - if (d3d12_dll == NULL) + if (d3d12_dll == nullptr) { // Attempt to load d3d12.dll from local directories. This will only succeed if // (1) the current OS is Windows 7, and @@ -503,23 +512,23 @@ bool ImGui_ImplDX12_CreateDeviceObjects() // See https://github.com/ocornut/imgui/pull/3696 for details. const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++) - if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != NULL) + if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr) break; // If failed, we are on Windows >= 10. - if (d3d12_dll == NULL) + if (d3d12_dll == nullptr) d3d12_dll = ::LoadLibraryA("d3d12.dll"); - if (d3d12_dll == NULL) + if (d3d12_dll == nullptr) return false; } PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature"); - if (D3D12SerializeRootSignatureFn == NULL) + if (D3D12SerializeRootSignatureFn == nullptr) return false; - ID3DBlob* blob = NULL; - if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, NULL) != S_OK) + ID3DBlob* blob = nullptr; + if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK) return false; bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature)); @@ -528,7 +537,7 @@ bool ImGui_ImplDX12_CreateDeviceObjects() // 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] + // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution] // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. @@ -576,16 +585,16 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return output;\ }"; - 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! + if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr))) + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() }; // Create the input layout static D3D12_INPUT_ELEMENT_DESC local_layout[] = { - { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)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 }, + { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, + { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; psoDesc.InputLayout = { local_layout, 3 }; } @@ -608,10 +617,10 @@ bool ImGui_ImplDX12_CreateDeviceObjects() return out_col; \ }"; - if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_5_0", 0, 0, &pixelShaderBlob, NULL))) + if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr))) { vertexShaderBlob->Release(); - return false; // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! + return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! } psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() }; } @@ -674,12 +683,12 @@ void ImGui_ImplDX12_InvalidateDeviceObjects() ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); if (!bd || !bd->pd3dDevice) return; - ImGuiIO& io = ImGui::GetIO(); + ImGuiIO& io = ImGui::GetIO(); SafeRelease(bd->pRootSignature); SafeRelease(bd->pPipelineState); SafeRelease(bd->pFontTextureResource); - io.Fonts->SetTexID(NULL); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. + io.Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. for (UINT i = 0; i < bd->numFramesInFlight; i++) { @@ -693,7 +702,7 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)(); @@ -707,15 +716,15 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO bd->hFontSrvGpuDescHandle = font_srv_gpu_desc_handle; bd->pFrameResources = new ImGui_ImplDX12_RenderBuffers[num_frames_in_flight]; bd->numFramesInFlight = num_frames_in_flight; + bd->pd3dSrvDescHeap = cbv_srv_heap; bd->frameIndex = UINT_MAX; - IM_UNUSED(cbv_srv_heap); // 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 < num_frames_in_flight; i++) { ImGui_ImplDX12_RenderBuffers* fr = &bd->pFrameResources[i]; - fr->IndexBuffer = NULL; - fr->VertexBuffer = NULL; + fr->IndexBuffer = nullptr; + fr->VertexBuffer = nullptr; fr->IndexBufferSize = 10000; fr->VertexBufferSize = 5000; } @@ -726,21 +735,27 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO void ImGui_ImplDX12_Shutdown() { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); + // Clean up windows and device objects ImGui_ImplDX12_InvalidateDeviceObjects(); delete[] bd->pFrameResources; - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplDX12_NewFrame() { ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplDX12_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX12_Init()?"); if (!bd->pPipelineState) ImGui_ImplDX12_CreateDeviceObjects(); } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx12.h b/third_party/imgui/backends/imgui_impl_dx12.h index 899c8229245..8710910b4ce 100644 --- a/third_party/imgui/backends/imgui_impl_dx12.h +++ b/third_party/imgui/backends/imgui_impl_dx12.h @@ -3,19 +3,22 @@ // Implemented features: // [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. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. -// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. -// 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. +// See imgui_impl_dx12.cpp file for details. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE #include // DXGI_FORMAT struct ID3D12Device; @@ -37,3 +40,5 @@ IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3 // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx9.cpp b/third_party/imgui/backends/imgui_impl_dx9.cpp index 4cbd7959dbf..ea0b26ec046 100644 --- a/third_party/imgui/backends/imgui_impl_dx9.cpp +++ b/third_party/imgui/backends/imgui_impl_dx9.cpp @@ -3,15 +3,20 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575) +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1. // 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) @@ -31,6 +36,7 @@ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_dx9.h" // DirectX @@ -46,7 +52,7 @@ struct ImGui_ImplDX9_Data int VertexBufferSize; int IndexBufferSize; - ImGui_ImplDX9_Data() { memset(this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } + ImGui_ImplDX9_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } }; struct CUSTOMVERTEX @@ -67,7 +73,7 @@ struct CUSTOMVERTEX // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions @@ -84,9 +90,9 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) vp.MaxZ = 1.0f; bd->pd3dDevice->SetViewport(&vp); - // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient) - bd->pd3dDevice->SetPixelShader(NULL); - bd->pd3dDevice->SetVertexShader(NULL); + // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling. + bd->pd3dDevice->SetPixelShader(nullptr); + bd->pd3dDevice->SetVertexShader(nullptr); bd->pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); bd->pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); bd->pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); @@ -151,21 +157,21 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) { - if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; } + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; - if (bd->pd3dDevice->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, NULL) < 0) + if (bd->pd3dDevice->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0) return; } if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) { - if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; } + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; - if (bd->pd3dDevice->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, NULL) < 0) + if (bd->pd3dDevice->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0) return; } // Backup the DX9 state - IDirect3DStateBlock9* d3d9_state_block = NULL; + IDirect3DStateBlock9* d3d9_state_block = nullptr; if (bd->pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0) return; if (d3d9_state_block->Capture() < 0) @@ -237,7 +243,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != NULL) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) @@ -279,7 +285,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)(); @@ -296,16 +302,35 @@ bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) void ImGui_ImplDX9_Shutdown() { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplDX9_InvalidateDeviceObjects(); if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } +static bool ImGui_ImplDX9_CheckFormatSupport(IDirect3DDevice9* pDevice, D3DFORMAT format) +{ + IDirect3D9* pd3d = nullptr; + if (pDevice->GetDirect3D(&pd3d) != D3D_OK) + return false; + D3DDEVICE_CREATION_PARAMETERS param = {}; + D3DDISPLAYMODE mode = {}; + if (pDevice->GetCreationParameters(¶m) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK) + { + pd3d->Release(); + return false; + } + // Font texture should support linear filter, color blend and write to render-target + bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK; + pd3d->Release(); + return support; +} + static bool ImGui_ImplDX9_CreateFontsTexture() { // Build texture atlas @@ -317,21 +342,24 @@ static bool ImGui_ImplDX9_CreateFontsTexture() // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices) #ifndef IMGUI_USE_BGRA_PACKED_COLOR - if (io.Fonts->TexPixelsUseColors) + const bool rgba_support = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8); + if (!rgba_support && io.Fonts->TexPixelsUseColors) { ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel); for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++) *dst = IMGUI_COL_TO_DX9_ARGB(*src); pixels = (unsigned char*)dst_start; } +#else + const bool rgba_support = false; #endif // Upload texture to graphics system - bd->FontTexture = NULL; - if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, NULL) < 0) + bd->FontTexture = nullptr; + if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, rgba_support ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0) return false; D3DLOCKED_RECT tex_locked_rect; - if (bd->FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK) + if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK) return false; for (int y = 0; y < height; y++) memcpy((unsigned char*)tex_locked_rect.pBits + (size_t)tex_locked_rect.Pitch * y, pixels + (size_t)width * bytes_per_pixel * y, (size_t)width * bytes_per_pixel); @@ -341,7 +369,7 @@ static bool ImGui_ImplDX9_CreateFontsTexture() io.Fonts->SetTexID((ImTextureID)bd->FontTexture); #ifndef IMGUI_USE_BGRA_PACKED_COLOR - if (io.Fonts->TexPixelsUseColors) + if (!rgba_support && io.Fonts->TexPixelsUseColors) ImGui::MemFree(pixels); #endif @@ -363,16 +391,20 @@ void ImGui_ImplDX9_InvalidateDeviceObjects() ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); if (!bd || !bd->pd3dDevice) return; - if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; } - if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; } - if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = NULL; ImGui::GetIO().Fonts->SetTexID(NULL); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. + if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } + if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } + if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. } void ImGui_ImplDX9_NewFrame() { ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplDX9_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX9_Init()?"); if (!bd->FontTexture) ImGui_ImplDX9_CreateDeviceObjects(); } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_dx9.h b/third_party/imgui/backends/imgui_impl_dx9.h index 6dc805b9044..3965583bd86 100644 --- a/third_party/imgui/backends/imgui_impl_dx9.h +++ b/third_party/imgui/backends/imgui_impl_dx9.h @@ -3,15 +3,19 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE struct IDirect3DDevice9; @@ -23,3 +27,5 @@ IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_glfw.cpp b/third_party/imgui/backends/imgui_impl_glfw.cpp index 1be2c52446e..a968fe308a3 100644 --- a/third_party/imgui/backends/imgui_impl_glfw.cpp +++ b/third_party/imgui/backends/imgui_impl_glfw.cpp @@ -1,21 +1,49 @@ // dear imgui: Platform Backend for GLFW // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) -// (Requires: GLFW 3.1+) +// (Requires: GLFW 3.1+. Prefer GLFW 3.3+ or GLFW 3.4+ for full feature support.) // Implemented features: // [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). -// [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). // 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window. +// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys. +// 2023-07-18: Inputs: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used differently. User may set ImGuiConfigFLags_NoMouse if desired. (#5625, #6609) +// 2023-06-12: Accept glfwGetTime() not returning a monotonically increasing value. This seems to happens on some Windows setup when peripherals disconnect, and is likely to also happen on browser + Emscripten. (#6491) +// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen on Windows ONLY, using a custom WndProc hook. (#2702) +// 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034) +// 2023-03-14: Emscripten: Avoid using glfwGetError() and glfwGetGamepadState() which are not correctly implemented in Emscripten emulation. (#6240) +// 2023-02-03: Emscripten: Registering custom low-level mouse wheel handler to get more accurate scrolling impulses on Emscripten. (#4019, #6096) +// 2023-01-04: Inputs: Fixed mods state on Linux when using Alt-GR text input (e.g. German keyboard layout), could lead to broken text input. Revert a 2022/01/17 change were we resumed using mods provided by GLFW, turns out they were faulty. +// 2022-11-22: Perform a dummy glfwGetError() read to cancel missing names with glfwGetKeyName(). (#5908) +// 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785) +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). +// 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position *EDIT* Reverted 2023-07-18. +// 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX. +// 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11. +// 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend. +// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. +// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. +// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). +// 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates. +// 2022-01-12: *BREAKING CHANGE*: Now using glfwSetCursorPosCallback(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetCursorPosCallback() and forward it to the backend via ImGui_ImplGlfw_CursorPosCallback(). +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. +// 2022-01-05: Inputs: Converting GLFW untranslated keycodes back to translated keycodes (in the ImGui_ImplGlfw_KeyCallback() function) in order to match the behavior of every other backend, and facilitate the use of GLFW with lettered-shortcuts API. // 2021-08-17: *BREAKING CHANGE*: Now using glfwSetWindowFocusCallback() to calling io.AddFocusEvent(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() and forward it to the backend via ImGui_ImplGlfw_WindowFocusCallback(). // 2021-07-29: *BREAKING CHANGE*: Now using glfwSetCursorEnterCallback(). MousePos is correctly reported when the host platform window is hovered but not focused. If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() callback and forward it to the backend via ImGui_ImplGlfw_CursorEnterCallback(). // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). @@ -42,32 +70,51 @@ // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_glfw.h" +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + // GLFW #include + #ifdef _WIN32 #undef APIENTRY #define GLFW_EXPOSE_NATIVE_WIN32 -#include // for glfwGetWin32Window +#include // for glfwGetWin32Window() #endif -#define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING -#define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED -#define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity -#define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale -#define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface -#ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released? -#define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR +#ifdef __APPLE__ +#define GLFW_EXPOSE_NATIVE_COCOA +#include // for glfwGetCocoaWindow() +#endif + +#ifdef __EMSCRIPTEN__ +#include +#include +#endif + +// We gather version tests as define in order to easily see which features are version-dependent. +#define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION) +#ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released? +#define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR #else -#define GLFW_HAS_NEW_CURSORS (0) +#define GLFW_HAS_NEW_CURSORS (0) #endif +#define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api +#define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName() +#define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError() // GLFW data enum GlfwClientApi { GlfwClientApi_Unknown, GlfwClientApi_OpenGL, - GlfwClientApi_Vulkan + GlfwClientApi_Vulkan, }; struct ImGui_ImplGlfw_Data @@ -76,20 +123,28 @@ struct ImGui_ImplGlfw_Data GlfwClientApi ClientApi; double Time; GLFWwindow* MouseWindow; - bool MouseJustPressed[ImGuiMouseButton_COUNT]; GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT]; + ImVec2 LastValidMousePos; bool InstalledCallbacks; + bool CallbacksChainForAllWindows; +#ifdef __EMSCRIPTEN__ + const char* CanvasSelector; +#endif // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. GLFWwindowfocusfun PrevUserCallbackWindowFocus; + GLFWcursorposfun PrevUserCallbackCursorPos; GLFWcursorenterfun PrevUserCallbackCursorEnter; GLFWmousebuttonfun PrevUserCallbackMousebutton; GLFWscrollfun PrevUserCallbackScroll; GLFWkeyfun PrevUserCallbackKey; GLFWcharfun PrevUserCallbackChar; GLFWmonitorfun PrevUserCallbackMonitor; +#ifdef _WIN32 + WNDPROC GlfwWndProc; +#endif - ImGui_ImplGlfw_Data() { memset(this, 0, sizeof(*this)); } + ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts @@ -101,7 +156,7 @@ struct ImGui_ImplGlfw_Data // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } // Functions @@ -115,79 +170,275 @@ static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text) glfwSetClipboardString((GLFWwindow*)user_data, text); } +static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key) +{ + switch (key) + { + case GLFW_KEY_TAB: return ImGuiKey_Tab; + case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow; + case GLFW_KEY_RIGHT: return ImGuiKey_RightArrow; + case GLFW_KEY_UP: return ImGuiKey_UpArrow; + case GLFW_KEY_DOWN: return ImGuiKey_DownArrow; + case GLFW_KEY_PAGE_UP: return ImGuiKey_PageUp; + case GLFW_KEY_PAGE_DOWN: return ImGuiKey_PageDown; + case GLFW_KEY_HOME: return ImGuiKey_Home; + case GLFW_KEY_END: return ImGuiKey_End; + case GLFW_KEY_INSERT: return ImGuiKey_Insert; + case GLFW_KEY_DELETE: return ImGuiKey_Delete; + case GLFW_KEY_BACKSPACE: return ImGuiKey_Backspace; + case GLFW_KEY_SPACE: return ImGuiKey_Space; + case GLFW_KEY_ENTER: return ImGuiKey_Enter; + case GLFW_KEY_ESCAPE: return ImGuiKey_Escape; + case GLFW_KEY_APOSTROPHE: return ImGuiKey_Apostrophe; + case GLFW_KEY_COMMA: return ImGuiKey_Comma; + case GLFW_KEY_MINUS: return ImGuiKey_Minus; + case GLFW_KEY_PERIOD: return ImGuiKey_Period; + case GLFW_KEY_SLASH: return ImGuiKey_Slash; + case GLFW_KEY_SEMICOLON: return ImGuiKey_Semicolon; + case GLFW_KEY_EQUAL: return ImGuiKey_Equal; + case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket; + case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash; + case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket; + case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent; + case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock; + case GLFW_KEY_SCROLL_LOCK: return ImGuiKey_ScrollLock; + case GLFW_KEY_NUM_LOCK: return ImGuiKey_NumLock; + case GLFW_KEY_PRINT_SCREEN: return ImGuiKey_PrintScreen; + case GLFW_KEY_PAUSE: return ImGuiKey_Pause; + case GLFW_KEY_KP_0: return ImGuiKey_Keypad0; + case GLFW_KEY_KP_1: return ImGuiKey_Keypad1; + case GLFW_KEY_KP_2: return ImGuiKey_Keypad2; + case GLFW_KEY_KP_3: return ImGuiKey_Keypad3; + case GLFW_KEY_KP_4: return ImGuiKey_Keypad4; + case GLFW_KEY_KP_5: return ImGuiKey_Keypad5; + case GLFW_KEY_KP_6: return ImGuiKey_Keypad6; + case GLFW_KEY_KP_7: return ImGuiKey_Keypad7; + case GLFW_KEY_KP_8: return ImGuiKey_Keypad8; + case GLFW_KEY_KP_9: return ImGuiKey_Keypad9; + case GLFW_KEY_KP_DECIMAL: return ImGuiKey_KeypadDecimal; + case GLFW_KEY_KP_DIVIDE: return ImGuiKey_KeypadDivide; + case GLFW_KEY_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; + case GLFW_KEY_KP_SUBTRACT: return ImGuiKey_KeypadSubtract; + case GLFW_KEY_KP_ADD: return ImGuiKey_KeypadAdd; + case GLFW_KEY_KP_ENTER: return ImGuiKey_KeypadEnter; + case GLFW_KEY_KP_EQUAL: return ImGuiKey_KeypadEqual; + case GLFW_KEY_LEFT_SHIFT: return ImGuiKey_LeftShift; + case GLFW_KEY_LEFT_CONTROL: return ImGuiKey_LeftCtrl; + case GLFW_KEY_LEFT_ALT: return ImGuiKey_LeftAlt; + case GLFW_KEY_LEFT_SUPER: return ImGuiKey_LeftSuper; + case GLFW_KEY_RIGHT_SHIFT: return ImGuiKey_RightShift; + case GLFW_KEY_RIGHT_CONTROL: return ImGuiKey_RightCtrl; + case GLFW_KEY_RIGHT_ALT: return ImGuiKey_RightAlt; + case GLFW_KEY_RIGHT_SUPER: return ImGuiKey_RightSuper; + case GLFW_KEY_MENU: return ImGuiKey_Menu; + case GLFW_KEY_0: return ImGuiKey_0; + case GLFW_KEY_1: return ImGuiKey_1; + case GLFW_KEY_2: return ImGuiKey_2; + case GLFW_KEY_3: return ImGuiKey_3; + case GLFW_KEY_4: return ImGuiKey_4; + case GLFW_KEY_5: return ImGuiKey_5; + case GLFW_KEY_6: return ImGuiKey_6; + case GLFW_KEY_7: return ImGuiKey_7; + case GLFW_KEY_8: return ImGuiKey_8; + case GLFW_KEY_9: return ImGuiKey_9; + case GLFW_KEY_A: return ImGuiKey_A; + case GLFW_KEY_B: return ImGuiKey_B; + case GLFW_KEY_C: return ImGuiKey_C; + case GLFW_KEY_D: return ImGuiKey_D; + case GLFW_KEY_E: return ImGuiKey_E; + case GLFW_KEY_F: return ImGuiKey_F; + case GLFW_KEY_G: return ImGuiKey_G; + case GLFW_KEY_H: return ImGuiKey_H; + case GLFW_KEY_I: return ImGuiKey_I; + case GLFW_KEY_J: return ImGuiKey_J; + case GLFW_KEY_K: return ImGuiKey_K; + case GLFW_KEY_L: return ImGuiKey_L; + case GLFW_KEY_M: return ImGuiKey_M; + case GLFW_KEY_N: return ImGuiKey_N; + case GLFW_KEY_O: return ImGuiKey_O; + case GLFW_KEY_P: return ImGuiKey_P; + case GLFW_KEY_Q: return ImGuiKey_Q; + case GLFW_KEY_R: return ImGuiKey_R; + case GLFW_KEY_S: return ImGuiKey_S; + case GLFW_KEY_T: return ImGuiKey_T; + case GLFW_KEY_U: return ImGuiKey_U; + case GLFW_KEY_V: return ImGuiKey_V; + case GLFW_KEY_W: return ImGuiKey_W; + case GLFW_KEY_X: return ImGuiKey_X; + case GLFW_KEY_Y: return ImGuiKey_Y; + case GLFW_KEY_Z: return ImGuiKey_Z; + case GLFW_KEY_F1: return ImGuiKey_F1; + case GLFW_KEY_F2: return ImGuiKey_F2; + case GLFW_KEY_F3: return ImGuiKey_F3; + case GLFW_KEY_F4: return ImGuiKey_F4; + case GLFW_KEY_F5: return ImGuiKey_F5; + case GLFW_KEY_F6: return ImGuiKey_F6; + case GLFW_KEY_F7: return ImGuiKey_F7; + case GLFW_KEY_F8: return ImGuiKey_F8; + case GLFW_KEY_F9: return ImGuiKey_F9; + case GLFW_KEY_F10: return ImGuiKey_F10; + case GLFW_KEY_F11: return ImGuiKey_F11; + case GLFW_KEY_F12: return ImGuiKey_F12; + case GLFW_KEY_F13: return ImGuiKey_F13; + case GLFW_KEY_F14: return ImGuiKey_F14; + case GLFW_KEY_F15: return ImGuiKey_F15; + case GLFW_KEY_F16: return ImGuiKey_F16; + case GLFW_KEY_F17: return ImGuiKey_F17; + case GLFW_KEY_F18: return ImGuiKey_F18; + case GLFW_KEY_F19: return ImGuiKey_F19; + case GLFW_KEY_F20: return ImGuiKey_F20; + case GLFW_KEY_F21: return ImGuiKey_F21; + case GLFW_KEY_F22: return ImGuiKey_F22; + case GLFW_KEY_F23: return ImGuiKey_F23; + case GLFW_KEY_F24: return ImGuiKey_F24; + default: return ImGuiKey_None; + } +} + +// X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW +// See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630 +static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window) +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiMod_Ctrl, (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)); + io.AddKeyEvent(ImGuiMod_Shift, (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS)); + io.AddKeyEvent(ImGuiMod_Alt, (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS)); + io.AddKeyEvent(ImGuiMod_Super, (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS)); +} + +static bool ImGui_ImplGlfw_ShouldChainCallback(GLFWwindow* window) +{ + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + return bd->CallbacksChainForAllWindows ? true : (window == bd->Window); +} + void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackMousebutton != NULL && window == bd->Window) + if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackMousebutton(window, button, action, mods); - if (action == GLFW_PRESS && button >= 0 && button < IM_ARRAYSIZE(bd->MouseJustPressed)) - bd->MouseJustPressed[button] = true; + ImGui_ImplGlfw_UpdateKeyModifiers(window); + + ImGuiIO& io = ImGui::GetIO(); + if (button >= 0 && button < ImGuiMouseButton_COUNT) + io.AddMouseButtonEvent(button, action == GLFW_PRESS); } void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackScroll != NULL && window == bd->Window) + if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackScroll(window, xoffset, yoffset); +#ifdef __EMSCRIPTEN__ + // Ignore GLFW events: will be processed in ImGui_ImplEmscripten_WheelCallback(). + return; +#endif + ImGuiIO& io = ImGui::GetIO(); - io.MouseWheelH += (float)xoffset; - io.MouseWheel += (float)yoffset; + io.AddMouseWheelEvent((float)xoffset, (float)yoffset); } -void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) +static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode) { - ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackKey != NULL && window == bd->Window) - bd->PrevUserCallbackKey(window, key, scancode, action, mods); - - ImGuiIO& io = ImGui::GetIO(); - if (key >= 0 && key < IM_ARRAYSIZE(io.KeysDown)) +#if GLFW_HAS_GETKEYNAME && !defined(__EMSCRIPTEN__) + // GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult. + // (It had reasons to do so: namely GLFW is/was more likely to be used for WASD-type game controls rather than lettered shortcuts, but IHMO the 3.1 change could have been done differently) + // See https://github.com/glfw/glfw/issues/1502 for details. + // Adding a workaround to undo this (so our keys are translated->untranslated->translated, likely a lossy process). + // This won't cover edge cases but this is at least going to cover common cases. + if (key >= GLFW_KEY_KP_0 && key <= GLFW_KEY_KP_EQUAL) + return key; + GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr); + const char* key_name = glfwGetKeyName(key, scancode); + glfwSetErrorCallback(prev_error_callback); +#if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908) + (void)glfwGetError(nullptr); +#endif + if (key_name && key_name[0] != 0 && key_name[1] == 0) { - if (action == GLFW_PRESS) - io.KeysDown[key] = true; - if (action == GLFW_RELEASE) - io.KeysDown[key] = false; + const char char_names[] = "`-=[]\\,;\'./"; + const int char_keys[] = { GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_BACKSLASH, GLFW_KEY_COMMA, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, 0 }; + IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys)); + if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); } + else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); } + else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); } + else if (const char* p = strchr(char_names, key_name[0])) { key = char_keys[p - char_names]; } } - - // Modifiers are not reliable across systems - io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; - io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; - io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; -#ifdef _WIN32 - io.KeySuper = false; + // if (action == GLFW_PRESS) printf("key %d scancode %d name '%s'\n", key, scancode, key_name); #else - io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER]; + IM_UNUSED(scancode); #endif + return key; +} + +void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods) +{ + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + bd->PrevUserCallbackKey(window, keycode, scancode, action, mods); + + if (action != GLFW_PRESS && action != GLFW_RELEASE) + return; + + ImGui_ImplGlfw_UpdateKeyModifiers(window); + + keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode); + + ImGuiIO& io = ImGui::GetIO(); + ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode); + io.AddKeyEvent(imgui_key, (action == GLFW_PRESS)); + io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code) } void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackWindowFocus != NULL && window == bd->Window) + if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackWindowFocus(window, focused); ImGuiIO& io = ImGui::GetIO(); io.AddFocusEvent(focused != 0); } +void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y) +{ + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) + bd->PrevUserCallbackCursorPos(window, x, y); + + ImGuiIO& io = ImGui::GetIO(); + io.AddMousePosEvent((float)x, (float)y); + bd->LastValidMousePos = ImVec2((float)x, (float)y); +} + +// Workaround: X11 seems to send spurious Leave/Enter events which would make us lose our position, +// so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984) void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackCursorEnter != NULL && window == bd->Window) + if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackCursorEnter(window, entered); + ImGuiIO& io = ImGui::GetIO(); if (entered) + { bd->MouseWindow = window; - if (!entered && bd->MouseWindow == window) - bd->MouseWindow = NULL; + io.AddMousePosEvent(bd->LastValidMousePos.x, bd->LastValidMousePos.y); + } + else if (!entered && bd->MouseWindow == window) + { + bd->LastValidMousePos = io.MousePos; + bd->MouseWindow = nullptr; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + } } void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c) { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - if (bd->PrevUserCallbackChar != NULL && window == bd->Window) + if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) bd->PrevUserCallbackChar(window, c); ImGuiIO& io = ImGui::GetIO(); @@ -199,10 +450,110 @@ void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int) // Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too. } +#ifdef __EMSCRIPTEN__ +static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*) +{ + // Mimic Emscripten_HandleWheel() in SDL. + // Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096 + float multiplier = 0.0f; + if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step. + else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step. + else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps. + float wheel_x = ev->deltaX * -multiplier; + float wheel_y = ev->deltaY * -multiplier; + ImGuiIO& io = ImGui::GetIO(); + io.AddMouseWheelEvent(wheel_x, wheel_y); + //IMGUI_DEBUG_LOG("[Emsc] mode %d dx: %.2f, dy: %.2f, dz: %.2f --> feed %.2f %.2f\n", (int)ev->deltaMode, ev->deltaX, ev->deltaY, ev->deltaZ, wheel_x, wheel_y); + return EM_TRUE; +} +#endif + +#ifdef _WIN32 +// GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen. +// Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently. +static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() +{ + LPARAM extra_info = ::GetMessageExtraInfo(); + if ((extra_info & 0xFFFFFF80) == 0xFF515700) + return ImGuiMouseSource_Pen; + if ((extra_info & 0xFFFFFF80) == 0xFF515780) + return ImGuiMouseSource_TouchScreen; + return ImGuiMouseSource_Mouse; +} +static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + switch (msg) + { + case WM_MOUSEMOVE: case WM_NCMOUSEMOVE: + case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_LBUTTONUP: + case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP: + case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP: + case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP: + ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); + break; + } + return ::CallWindowProcW(bd->GlfwWndProc, hWnd, msg, wParam, lParam); +} +#endif + +void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window) +{ + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!"); + IM_ASSERT(bd->Window == window); + + bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback); + bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback); + bd->PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback); + bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback); + bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback); + bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback); + bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback); + bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback); + bd->InstalledCallbacks = true; +} + +void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window) +{ + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!"); + IM_ASSERT(bd->Window == window); + + glfwSetWindowFocusCallback(window, bd->PrevUserCallbackWindowFocus); + glfwSetCursorEnterCallback(window, bd->PrevUserCallbackCursorEnter); + glfwSetCursorPosCallback(window, bd->PrevUserCallbackCursorPos); + glfwSetMouseButtonCallback(window, bd->PrevUserCallbackMousebutton); + glfwSetScrollCallback(window, bd->PrevUserCallbackScroll); + glfwSetKeyCallback(window, bd->PrevUserCallbackKey); + glfwSetCharCallback(window, bd->PrevUserCallbackChar); + glfwSetMonitorCallback(bd->PrevUserCallbackMonitor); + bd->InstalledCallbacks = false; + bd->PrevUserCallbackWindowFocus = nullptr; + bd->PrevUserCallbackCursorEnter = nullptr; + bd->PrevUserCallbackCursorPos = nullptr; + bd->PrevUserCallbackMousebutton = nullptr; + bd->PrevUserCallbackScroll = nullptr; + bd->PrevUserCallbackKey = nullptr; + bd->PrevUserCallbackChar = nullptr; + bd->PrevUserCallbackMonitor = nullptr; +} + +// Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user. +// This is 'false' by default meaning we only chain callbacks for the main viewport. +// We cannot set this to 'true' by default because user callbacks code may be not testing the 'window' parameter of their callback. +// If you set this to 'true' your user callback code will need to make sure you are testing the 'window' parameter. +void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) +{ + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + bd->CallbacksChainForAllWindows = chain_for_all_windows; +} + static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!"); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + //printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED); // Setup backend capabilities flags ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)(); @@ -214,42 +565,15 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw bd->Window = window; bd->Time = 0.0; - // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array. - io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; - io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; - io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; - io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; - io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; - io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; - io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; - io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; - io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; - io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT; - io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; - io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; - io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE; - io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; - io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; - io.KeyMap[ImGuiKey_KeyPadEnter] = GLFW_KEY_KP_ENTER; - io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; - io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; - io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; - io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; - io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; - io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; - io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; io.ClipboardUserData = bd->Window; -#if defined(_WIN32) - io.ImeWindowHandle = (void*)glfwGetWin32Window(bd->Window); -#endif // Create mouse cursors // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist, // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting. - // Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.) - GLFWerrorfun prev_error_callback = glfwSetErrorCallback(NULL); + // Missing cursors will return nullptr and our _UpdateMouseCursor() function will use the Arrow cursor instead.) + GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr); bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR); bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR); @@ -267,26 +591,36 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); #endif glfwSetErrorCallback(prev_error_callback); +#if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908) + (void)glfwGetError(nullptr); +#endif // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. - bd->PrevUserCallbackWindowFocus = NULL; - bd->PrevUserCallbackCursorEnter = NULL; - bd->PrevUserCallbackMousebutton = NULL; - bd->PrevUserCallbackScroll = NULL; - bd->PrevUserCallbackKey = NULL; - bd->PrevUserCallbackChar = NULL; - bd->PrevUserCallbackMonitor = NULL; if (install_callbacks) - { - bd->InstalledCallbacks = true; - bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback); - bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback); - bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback); - bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback); - bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback); - bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback); - bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback); - } + ImGui_ImplGlfw_InstallCallbacks(window); + // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096) + // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves. + // FIXME: May break chaining in case user registered their own Emscripten callback? +#ifdef __EMSCRIPTEN__ + emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, false, ImGui_ImplEmscripten_WheelCallback); +#endif + + // Set platform dependent data in viewport + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); +#ifdef _WIN32 + main_viewport->PlatformHandleRaw = glfwGetWin32Window(bd->Window); +#elif defined(__APPLE__) + main_viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(bd->Window); +#else + IM_UNUSED(main_viewport); +#endif + + // Windows: register a WndProc hook so we can intercept some messages. +#ifdef _WIN32 + bd->GlfwWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC); + IM_ASSERT(bd->GlfwWndProc != nullptr); + ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); +#endif bd->ClientApi = client_api; return true; @@ -310,61 +644,59 @@ bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks) void ImGui_ImplGlfw_Shutdown() { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - IM_ASSERT(bd != NULL && "No platform backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); if (bd->InstalledCallbacks) - { - glfwSetWindowFocusCallback(bd->Window, bd->PrevUserCallbackWindowFocus); - glfwSetCursorEnterCallback(bd->Window, bd->PrevUserCallbackCursorEnter); - glfwSetMouseButtonCallback(bd->Window, bd->PrevUserCallbackMousebutton); - glfwSetScrollCallback(bd->Window, bd->PrevUserCallbackScroll); - glfwSetKeyCallback(bd->Window, bd->PrevUserCallbackKey); - glfwSetCharCallback(bd->Window, bd->PrevUserCallbackChar); - glfwSetMonitorCallback(bd->PrevUserCallbackMonitor); - } + ImGui_ImplGlfw_RestoreCallbacks(bd->Window); +#ifdef __EMSCRIPTEN__ + emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, false, nullptr); +#endif for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) glfwDestroyCursor(bd->MouseCursors[cursor_n]); - io.BackendPlatformName = NULL; - io.BackendPlatformUserData = NULL; + // Windows: register a WndProc hook so we can intercept some messages. +#ifdef _WIN32 + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->GlfwWndProc); + bd->GlfwWndProc = nullptr; +#endif + + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); IM_DELETE(bd); } -static void ImGui_ImplGlfw_UpdateMousePosAndButtons() +static void ImGui_ImplGlfw_UpdateMouseData() { ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); - const ImVec2 mouse_pos_prev = io.MousePos; - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - - // Update mouse buttons - // (if a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame) - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) + // (those braces are here to reduce diff with multi-viewports support in 'docking' branch) { - io.MouseDown[i] = bd->MouseJustPressed[i] || glfwGetMouseButton(bd->Window, i) != 0; - bd->MouseJustPressed[i] = false; - } - + GLFWwindow* window = bd->Window; #ifdef __EMSCRIPTEN__ - const bool focused = true; + const bool is_window_focused = true; #else - const bool focused = glfwGetWindowAttrib(bd->Window, GLFW_FOCUSED) != 0; + const bool is_window_focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0; #endif - GLFWwindow* mouse_window = (bd->MouseWindow == bd->Window || focused) ? bd->Window : NULL; - - // Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) - if (io.WantSetMousePos && focused) - glfwSetCursorPos(bd->Window, (double)mouse_pos_prev.x, (double)mouse_pos_prev.y); - - // Set Dear ImGui mouse position from OS position - if (mouse_window != NULL) - { - double mouse_x, mouse_y; - glfwGetCursorPos(mouse_window, &mouse_x, &mouse_y); - io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); + if (is_window_focused) + { + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + if (io.WantSetMousePos) + glfwSetCursorPos(window, (double)io.MousePos.x, (double)io.MousePos.y); + + // (Optional) Fallback to provide mouse position when focused (ImGui_ImplGlfw_CursorPosCallback already provides this when hovered or captured) + if (bd->MouseWindow == nullptr) + { + double mouse_x, mouse_y; + glfwGetCursorPos(window, &mouse_x, &mouse_y); + bd->LastValidMousePos = ImVec2((float)mouse_x, (float)mouse_y); + io.AddMousePosEvent((float)mouse_x, (float)mouse_y); + } + } } } @@ -376,62 +708,82 @@ static void ImGui_ImplGlfw_UpdateMouseCursor() return; ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); - if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) + // (those braces are here to reduce diff with multi-viewports support in 'docking' branch) { - // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor - glfwSetInputMode(bd->Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); - } - else - { - // Show OS mouse cursor - // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. - glfwSetCursor(bd->Window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]); - glfwSetInputMode(bd->Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + GLFWwindow* window = bd->Window; + if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + } + else + { + // Show OS mouse cursor + // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. + glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]); + glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + } } } +// Update gamepad inputs +static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } static void ImGui_ImplGlfw_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); - memset(io.NavInputs, 0, sizeof(io.NavInputs)); - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. return; - // Update gamepad inputs - #define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; } - #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; } + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; +#if GLFW_HAS_GAMEPAD_API && !defined(__EMSCRIPTEN__) + GLFWgamepadstate gamepad; + if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad)) + return; + #define MAP_BUTTON(KEY_NO, BUTTON_NO, _UNUSED) do { io.AddKeyEvent(KEY_NO, gamepad.buttons[BUTTON_NO] != 0); } while (0) + #define MAP_ANALOG(KEY_NO, AXIS_NO, _UNUSED, V0, V1) do { float v = gamepad.axes[AXIS_NO]; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0) +#else int axes_count = 0, buttons_count = 0; const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count); const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count); - MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A - MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B - MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X - MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y - MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left - MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right - MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up - MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down - MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB - MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB - MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB - MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB - MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f); - MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f); - MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f); - MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f); + if (axes_count == 0 || buttons_count == 0) + return; + #define MAP_BUTTON(KEY_NO, _UNUSED, BUTTON_NO) do { io.AddKeyEvent(KEY_NO, (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS)); } while (0) + #define MAP_ANALOG(KEY_NO, _UNUSED, AXIS_NO, V0, V1) do { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0) +#endif + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + MAP_BUTTON(ImGuiKey_GamepadStart, GLFW_GAMEPAD_BUTTON_START, 7); + MAP_BUTTON(ImGuiKey_GamepadBack, GLFW_GAMEPAD_BUTTON_BACK, 6); + MAP_BUTTON(ImGuiKey_GamepadFaceLeft, GLFW_GAMEPAD_BUTTON_X, 2); // Xbox X, PS Square + MAP_BUTTON(ImGuiKey_GamepadFaceRight, GLFW_GAMEPAD_BUTTON_B, 1); // Xbox B, PS Circle + MAP_BUTTON(ImGuiKey_GamepadFaceUp, GLFW_GAMEPAD_BUTTON_Y, 3); // Xbox Y, PS Triangle + MAP_BUTTON(ImGuiKey_GamepadFaceDown, GLFW_GAMEPAD_BUTTON_A, 0); // Xbox A, PS Cross + MAP_BUTTON(ImGuiKey_GamepadDpadLeft, GLFW_GAMEPAD_BUTTON_DPAD_LEFT, 13); + MAP_BUTTON(ImGuiKey_GamepadDpadRight, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, 11); + MAP_BUTTON(ImGuiKey_GamepadDpadUp, GLFW_GAMEPAD_BUTTON_DPAD_UP, 10); + MAP_BUTTON(ImGuiKey_GamepadDpadDown, GLFW_GAMEPAD_BUTTON_DPAD_DOWN, 12); + MAP_BUTTON(ImGuiKey_GamepadL1, GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, 4); + MAP_BUTTON(ImGuiKey_GamepadR1, GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, 5); + MAP_ANALOG(ImGuiKey_GamepadL2, GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, 4, -0.75f, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadR2, GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, 5, -0.75f, +1.0f); + MAP_BUTTON(ImGuiKey_GamepadL3, GLFW_GAMEPAD_BUTTON_LEFT_THUMB, 8); + MAP_BUTTON(ImGuiKey_GamepadR3, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, 9); + MAP_ANALOG(ImGuiKey_GamepadLStickLeft, GLFW_GAMEPAD_AXIS_LEFT_X, 0, -0.25f, -1.0f); + MAP_ANALOG(ImGuiKey_GamepadLStickRight, GLFW_GAMEPAD_AXIS_LEFT_X, 0, +0.25f, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadLStickUp, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, -0.25f, -1.0f); + MAP_ANALOG(ImGuiKey_GamepadLStickDown, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, +0.25f, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickLeft, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, -0.25f, -1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickRight, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, +0.25f, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickUp, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, -0.25f, -1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickDown, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, +0.25f, +1.0f); #undef MAP_BUTTON #undef MAP_ANALOG - if (axes_count > 0 && buttons_count > 0) - io.BackendFlags |= ImGuiBackendFlags_HasGamepad; - else - io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; } void ImGui_ImplGlfw_NewFrame() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplGlfw_InitForXXX()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplGlfw_InitForXXX()?"); // Setup display size (every frame to accommodate for window resizing) int w, h; @@ -440,16 +792,63 @@ void ImGui_ImplGlfw_NewFrame() glfwGetFramebufferSize(bd->Window, &display_w, &display_h); io.DisplaySize = ImVec2((float)w, (float)h); if (w > 0 && h > 0) - io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); + io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h); // Setup time step + // (Accept glfwGetTime() not returning a monotonically increasing value. Seems to happens on disconnecting peripherals and probably on VMs and Emscripten, see #6491, #6189, #6114, #3644) double current_time = glfwGetTime(); + if (current_time <= bd->Time) + current_time = bd->Time + 0.00001f; io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f); bd->Time = current_time; - ImGui_ImplGlfw_UpdateMousePosAndButtons(); + ImGui_ImplGlfw_UpdateMouseData(); ImGui_ImplGlfw_UpdateMouseCursor(); // Update game controllers (if enabled and available) ImGui_ImplGlfw_UpdateGamepads(); } + +#ifdef __EMSCRIPTEN__ +static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data) +{ + ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data; + double canvas_width, canvas_height; + emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height); + glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height); + return true; +} + +static EM_BOOL ImGui_ImplEmscripten_FullscreenChangeCallback(int event_type, const EmscriptenFullscreenChangeEvent* event, void* user_data) +{ + ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data; + double canvas_width, canvas_height; + emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height); + glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height); + return true; +} + +// 'canvas_selector' is a CSS selector. The event listener is applied to the first element that matches the query. +// STRING MUST PERSIST FOR THE APPLICATION DURATION. PLEASE USE A STRING LITERAL OR ENSURE POINTER WILL STAY VALID. +void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector) +{ + IM_ASSERT(canvas_selector != nullptr); + ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplGlfw_InitForXXX()?"); + + bd->CanvasSelector = canvas_selector; + emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, bd, false, ImGui_ImplGlfw_OnCanvasSizeChange); + emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, bd, false, ImGui_ImplEmscripten_FullscreenChangeCallback); + + // Change the size of the GLFW window according to the size of the canvas + ImGui_ImplGlfw_OnCanvasSizeChange(EMSCRIPTEN_EVENT_RESIZE, {}, bd); +} +#endif + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_glfw.h b/third_party/imgui/backends/imgui_impl_glfw.h index 5e1fb06df29..6a9acd05b27 100644 --- a/third_party/imgui/backends/imgui_impl_glfw.h +++ b/third_party/imgui/backends/imgui_impl_glfw.h @@ -4,21 +4,22 @@ // Implemented features: // [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only). +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW. -// [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 - -// About GLSL version: -// The 'glsl_version' initialization parameter defaults to "#version 150" if NULL. -// Only override if your GL version doesn't handle this GLSL version. Keep NULL if unsure! +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE struct GLFWwindow; struct GLFWmonitor; @@ -29,13 +30,29 @@ IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool ins IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); -// GLFW callbacks -// - When calling Init with 'install_callbacks=true': GLFW callbacks will be installed for you. They will call user's previously installed callbacks, if any. -// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call those function yourself from your own GLFW callbacks. -IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); -IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); +// Emscripten related initialization phase methods +#ifdef __EMSCRIPTEN__ +IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector); +#endif + +// GLFW callbacks install +// - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any. +// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks. +IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window); +IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window); + +// GFLW callbacks options: +// - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user) +IMGUI_IMPL_API void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows); + +// GLFW callbacks (individual callbacks to call yourself if you didn't install callbacks) +IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84 +IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84 +IMGUI_IMPL_API void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87 IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_glut.cpp b/third_party/imgui/backends/imgui_impl_glut.cpp index 85bea776596..5dada3037a3 100644 --- a/third_party/imgui/backends/imgui_impl_glut.cpp +++ b/third_party/imgui/backends/imgui_impl_glut.cpp @@ -5,26 +5,39 @@ // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! // !!! Nowadays, prefer using GLFW or SDL instead! +// Implemented features: +// [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I +// [ ] Platform: Missing horizontal mouse wheel support. // [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2023-04-17: BREAKING: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame(). Needs to be called from the main application loop, like with every other backends. +// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). +// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. +// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2019-04-03: Misc: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. // 2019-03-25: Misc: Made io.DeltaTime always above zero. // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-03-22: Added GLUT Platform binding. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_glut.h" +#define GL_SILENCE_DEPRECATION #ifdef __APPLE__ #include #else @@ -37,6 +50,120 @@ static int g_Time = 0; // Current time, in milliseconds +// Glut has 1 function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above. +static ImGuiKey ImGui_ImplGLUT_KeyToImGuiKey(int key) +{ + switch (key) + { + case '\t': return ImGuiKey_Tab; + case 256 + GLUT_KEY_LEFT: return ImGuiKey_LeftArrow; + case 256 + GLUT_KEY_RIGHT: return ImGuiKey_RightArrow; + case 256 + GLUT_KEY_UP: return ImGuiKey_UpArrow; + case 256 + GLUT_KEY_DOWN: return ImGuiKey_DownArrow; + case 256 + GLUT_KEY_PAGE_UP: return ImGuiKey_PageUp; + case 256 + GLUT_KEY_PAGE_DOWN: return ImGuiKey_PageDown; + case 256 + GLUT_KEY_HOME: return ImGuiKey_Home; + case 256 + GLUT_KEY_END: return ImGuiKey_End; + case 256 + GLUT_KEY_INSERT: return ImGuiKey_Insert; + case 127: return ImGuiKey_Delete; + case 8: return ImGuiKey_Backspace; + case ' ': return ImGuiKey_Space; + case 13: return ImGuiKey_Enter; + case 27: return ImGuiKey_Escape; + case 39: return ImGuiKey_Apostrophe; + case 44: return ImGuiKey_Comma; + case 45: return ImGuiKey_Minus; + case 46: return ImGuiKey_Period; + case 47: return ImGuiKey_Slash; + case 59: return ImGuiKey_Semicolon; + case 61: return ImGuiKey_Equal; + case 91: return ImGuiKey_LeftBracket; + case 92: return ImGuiKey_Backslash; + case 93: return ImGuiKey_RightBracket; + case 96: return ImGuiKey_GraveAccent; + //case 0: return ImGuiKey_CapsLock; + //case 0: return ImGuiKey_ScrollLock; + case 256 + 0x006D: return ImGuiKey_NumLock; + //case 0: return ImGuiKey_PrintScreen; + //case 0: return ImGuiKey_Pause; + //case '0': return ImGuiKey_Keypad0; + //case '1': return ImGuiKey_Keypad1; + //case '2': return ImGuiKey_Keypad2; + //case '3': return ImGuiKey_Keypad3; + //case '4': return ImGuiKey_Keypad4; + //case '5': return ImGuiKey_Keypad5; + //case '6': return ImGuiKey_Keypad6; + //case '7': return ImGuiKey_Keypad7; + //case '8': return ImGuiKey_Keypad8; + //case '9': return ImGuiKey_Keypad9; + //case 46: return ImGuiKey_KeypadDecimal; + //case 47: return ImGuiKey_KeypadDivide; + case 42: return ImGuiKey_KeypadMultiply; + //case 45: return ImGuiKey_KeypadSubtract; + case 43: return ImGuiKey_KeypadAdd; + //case 13: return ImGuiKey_KeypadEnter; + //case 0: return ImGuiKey_KeypadEqual; + case 256 + 0x0072: return ImGuiKey_LeftCtrl; + case 256 + 0x0070: return ImGuiKey_LeftShift; + case 256 + 0x0074: return ImGuiKey_LeftAlt; + //case 0: return ImGuiKey_LeftSuper; + case 256 + 0x0073: return ImGuiKey_RightCtrl; + case 256 + 0x0071: return ImGuiKey_RightShift; + case 256 + 0x0075: return ImGuiKey_RightAlt; + //case 0: return ImGuiKey_RightSuper; + //case 0: return ImGuiKey_Menu; + case '0': return ImGuiKey_0; + case '1': return ImGuiKey_1; + case '2': return ImGuiKey_2; + case '3': return ImGuiKey_3; + case '4': return ImGuiKey_4; + case '5': return ImGuiKey_5; + case '6': return ImGuiKey_6; + case '7': return ImGuiKey_7; + case '8': return ImGuiKey_8; + case '9': return ImGuiKey_9; + case 'A': case 'a': return ImGuiKey_A; + case 'B': case 'b': return ImGuiKey_B; + case 'C': case 'c': return ImGuiKey_C; + case 'D': case 'd': return ImGuiKey_D; + case 'E': case 'e': return ImGuiKey_E; + case 'F': case 'f': return ImGuiKey_F; + case 'G': case 'g': return ImGuiKey_G; + case 'H': case 'h': return ImGuiKey_H; + case 'I': case 'i': return ImGuiKey_I; + case 'J': case 'j': return ImGuiKey_J; + case 'K': case 'k': return ImGuiKey_K; + case 'L': case 'l': return ImGuiKey_L; + case 'M': case 'm': return ImGuiKey_M; + case 'N': case 'n': return ImGuiKey_N; + case 'O': case 'o': return ImGuiKey_O; + case 'P': case 'p': return ImGuiKey_P; + case 'Q': case 'q': return ImGuiKey_Q; + case 'R': case 'r': return ImGuiKey_R; + case 'S': case 's': return ImGuiKey_S; + case 'T': case 't': return ImGuiKey_T; + case 'U': case 'u': return ImGuiKey_U; + case 'V': case 'v': return ImGuiKey_V; + case 'W': case 'w': return ImGuiKey_W; + case 'X': case 'x': return ImGuiKey_X; + case 'Y': case 'y': return ImGuiKey_Y; + case 'Z': case 'z': return ImGuiKey_Z; + case 256 + GLUT_KEY_F1: return ImGuiKey_F1; + case 256 + GLUT_KEY_F2: return ImGuiKey_F2; + case 256 + GLUT_KEY_F3: return ImGuiKey_F3; + case 256 + GLUT_KEY_F4: return ImGuiKey_F4; + case 256 + GLUT_KEY_F5: return ImGuiKey_F5; + case 256 + GLUT_KEY_F6: return ImGuiKey_F6; + case 256 + GLUT_KEY_F7: return ImGuiKey_F7; + case 256 + GLUT_KEY_F8: return ImGuiKey_F8; + case 256 + GLUT_KEY_F9: return ImGuiKey_F9; + case 256 + GLUT_KEY_F10: return ImGuiKey_F10; + case 256 + GLUT_KEY_F11: return ImGuiKey_F11; + case 256 + GLUT_KEY_F12: return ImGuiKey_F12; + default: return ImGuiKey_None; + } +} + bool ImGui_ImplGLUT_Init() { ImGuiIO& io = ImGui::GetIO(); @@ -46,33 +173,8 @@ bool ImGui_ImplGLUT_Init() #else io.BackendPlatformName = "imgui_impl_glut"; #endif - g_Time = 0; - // Glut has 1 function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above. - io.KeyMap[ImGuiKey_Tab] = '\t'; // == 9 == CTRL+I - io.KeyMap[ImGuiKey_LeftArrow] = 256 + GLUT_KEY_LEFT; - io.KeyMap[ImGuiKey_RightArrow] = 256 + GLUT_KEY_RIGHT; - io.KeyMap[ImGuiKey_UpArrow] = 256 + GLUT_KEY_UP; - io.KeyMap[ImGuiKey_DownArrow] = 256 + GLUT_KEY_DOWN; - io.KeyMap[ImGuiKey_PageUp] = 256 + GLUT_KEY_PAGE_UP; - io.KeyMap[ImGuiKey_PageDown] = 256 + GLUT_KEY_PAGE_DOWN; - io.KeyMap[ImGuiKey_Home] = 256 + GLUT_KEY_HOME; - io.KeyMap[ImGuiKey_End] = 256 + GLUT_KEY_END; - io.KeyMap[ImGuiKey_Insert] = 256 + GLUT_KEY_INSERT; - io.KeyMap[ImGuiKey_Delete] = 127; - io.KeyMap[ImGuiKey_Backspace] = 8; // == CTRL+H - io.KeyMap[ImGuiKey_Space] = ' '; - io.KeyMap[ImGuiKey_Enter] = 13; // == CTRL+M - io.KeyMap[ImGuiKey_Escape] = 27; - io.KeyMap[ImGuiKey_KeyPadEnter] = 13; // == CTRL+M - 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'; - return true; } @@ -93,6 +195,8 @@ void ImGui_ImplGLUT_InstallFuncs() void ImGui_ImplGLUT_Shutdown() { + ImGuiIO& io = ImGui::GetIO(); + io.BackendPlatformName = nullptr; } void ImGui_ImplGLUT_NewFrame() @@ -105,18 +209,22 @@ void ImGui_ImplGLUT_NewFrame() delta_time_ms = 1; io.DeltaTime = delta_time_ms / 1000.0f; g_Time = current_time; +} - // Start the frame - ImGui::NewFrame(); +static void ImGui_ImplGLUT_UpdateKeyModifiers() +{ + ImGuiIO& io = ImGui::GetIO(); + int glut_key_mods = glutGetModifiers(); + io.AddKeyEvent(ImGuiMod_Ctrl, (glut_key_mods & GLUT_ACTIVE_CTRL) != 0); + io.AddKeyEvent(ImGuiMod_Shift, (glut_key_mods & GLUT_ACTIVE_SHIFT) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (glut_key_mods & GLUT_ACTIVE_ALT) != 0); } -static void ImGui_ImplGLUT_UpdateKeyboardMods() +static void ImGui_ImplGLUT_AddKeyEvent(ImGuiKey key, bool down, int native_keycode) { ImGuiIO& io = ImGui::GetIO(); - int mods = glutGetModifiers(); - io.KeyCtrl = (mods & GLUT_ACTIVE_CTRL) != 0; - io.KeyShift = (mods & GLUT_ACTIVE_SHIFT) != 0; - io.KeyAlt = (mods & GLUT_ACTIVE_ALT) != 0; + io.AddKeyEvent(key, down); + io.SetKeyEventNativeData(key, native_keycode, -1); // To support legacy indexing (<1.87 user code) } void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) @@ -127,79 +235,58 @@ void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) if (c >= 32) io.AddInputCharacter((unsigned int)c); - // Store letters in KeysDown[] array as both uppercase and lowercase + Handle GLUT translating CTRL+A..CTRL+Z as 1..26. - // This is a hacky mess but GLUT is unable to distinguish e.g. a TAB key from CTRL+I so this is probably the best we can do here. - if (c >= 1 && c <= 26) - io.KeysDown[c] = io.KeysDown[c - 1 + 'a'] = io.KeysDown[c - 1 + 'A'] = true; - else if (c >= 'a' && c <= 'z') - io.KeysDown[c] = io.KeysDown[c - 'a' + 'A'] = true; - else if (c >= 'A' && c <= 'Z') - io.KeysDown[c] = io.KeysDown[c - 'A' + 'a'] = true; - else - io.KeysDown[c] = true; - ImGui_ImplGLUT_UpdateKeyboardMods(); + ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c); + ImGui_ImplGLUT_AddKeyEvent(key, true, c); + ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y) { //printf("char_up_func %d '%c'\n", c, c); - ImGuiIO& io = ImGui::GetIO(); - if (c >= 1 && c <= 26) - io.KeysDown[c] = io.KeysDown[c - 1 + 'a'] = io.KeysDown[c - 1 + 'A'] = false; - else if (c >= 'a' && c <= 'z') - io.KeysDown[c] = io.KeysDown[c - 'a' + 'A'] = false; - else if (c >= 'A' && c <= 'Z') - io.KeysDown[c] = io.KeysDown[c - 'A' + 'a'] = false; - else - io.KeysDown[c] = false; - ImGui_ImplGLUT_UpdateKeyboardMods(); + ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c); + ImGui_ImplGLUT_AddKeyEvent(key, false, c); + ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y) { //printf("key_down_func %d\n", key); - ImGuiIO& io = ImGui::GetIO(); - if (key + 256 < IM_ARRAYSIZE(io.KeysDown)) - io.KeysDown[key + 256] = true; - ImGui_ImplGLUT_UpdateKeyboardMods(); + ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256); + ImGui_ImplGLUT_AddKeyEvent(imgui_key, true, key + 256); + ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y) { //printf("key_up_func %d\n", key); - ImGuiIO& io = ImGui::GetIO(); - if (key + 256 < IM_ARRAYSIZE(io.KeysDown)) - io.KeysDown[key + 256] = false; - ImGui_ImplGLUT_UpdateKeyboardMods(); + ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256); + ImGui_ImplGLUT_AddKeyEvent(imgui_key, false, key + 256); + ImGui_ImplGLUT_UpdateKeyModifiers(); (void)x; (void)y; // Unused } void ImGui_ImplGLUT_MouseFunc(int glut_button, int state, int x, int y) { ImGuiIO& io = ImGui::GetIO(); - io.MousePos = ImVec2((float)x, (float)y); + io.AddMousePosEvent((float)x, (float)y); int button = -1; if (glut_button == GLUT_LEFT_BUTTON) button = 0; if (glut_button == GLUT_RIGHT_BUTTON) button = 1; if (glut_button == GLUT_MIDDLE_BUTTON) button = 2; - if (button != -1 && state == GLUT_DOWN) - io.MouseDown[button] = true; - if (button != -1 && state == GLUT_UP) - io.MouseDown[button] = false; + if (button != -1 && (state == GLUT_DOWN || state == GLUT_UP)) + io.AddMouseButtonEvent(button, state == GLUT_DOWN); } #ifdef __FREEGLUT_EXT_H__ void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y) { ImGuiIO& io = ImGui::GetIO(); - io.MousePos = ImVec2((float)x, (float)y); - if (dir > 0) - io.MouseWheel += 1.0; - else if (dir < 0) - io.MouseWheel -= 1.0; + io.AddMousePosEvent((float)x, (float)y); + if (dir != 0) + io.AddMouseWheelEvent(0.0f, dir > 0 ? 1.0f : -1.0f); (void)button; // Unused } #endif @@ -213,5 +300,9 @@ void ImGui_ImplGLUT_ReshapeFunc(int w, int h) void ImGui_ImplGLUT_MotionFunc(int x, int y) { ImGuiIO& io = ImGui::GetIO(); - io.MousePos = ImVec2((float)x, (float)y); + io.AddMousePosEvent((float)x, (float)y); } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_glut.h b/third_party/imgui/backends/imgui_impl_glut.h index 96c779fde76..062110edd62 100644 --- a/third_party/imgui/backends/imgui_impl_glut.h +++ b/third_party/imgui/backends/imgui_impl_glut.h @@ -5,18 +5,25 @@ // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! // !!! Nowadays, prefer using GLFW or SDL instead! +// Implemented features: +// [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // Issues: // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I +// [ ] Platform: Missing horizontal mouse wheel support. // [ ] Platform: Missing mouse cursor shape/visibility support. // [ ] Platform: Missing clipboard support (not supported by Glut). // [ ] Platform: Missing gamepad support. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once +#ifndef IMGUI_DISABLE #include "imgui.h" // IMGUI_IMPL_API IMGUI_IMPL_API bool ImGui_ImplGLUT_Init(); @@ -26,7 +33,7 @@ IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame(); // You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically, // or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency.. -//---------------------------------------- GLUT name --------------------------------------------- Decent Name --------- +//------------------------------------ GLUT name ---------------------------------------------- Decent Name --------- IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc @@ -35,3 +42,5 @@ IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_metal.h b/third_party/imgui/backends/imgui_impl_metal.h index c0c601814f7..53706d1f716 100644 --- a/third_party/imgui/backends/imgui_impl_metal.h +++ b/third_party/imgui/backends/imgui_impl_metal.h @@ -3,14 +3,24 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// ObjC API +//----------------------------------------------------------------------------- + +#ifdef __OBJC__ @class MTLRenderPassDescriptor; @protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder; @@ -18,7 +28,7 @@ IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id device); IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor); -IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, +IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id commandBuffer, id commandEncoder); @@ -27,3 +37,36 @@ IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(id device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id device); IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); + +#endif + +//----------------------------------------------------------------------------- +// C++ API +//----------------------------------------------------------------------------- + +// Enable Metal C++ binding support with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file +// More info about using Metal from C++: https://developer.apple.com/metal/cpp/ + +#ifdef IMGUI_IMPL_METAL_CPP +#include +#ifndef __OBJC__ + +IMGUI_IMPL_API bool ImGui_ImplMetal_Init(MTL::Device* device); +IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor); +IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, + MTL::CommandBuffer* commandBuffer, + MTL::RenderCommandEncoder* commandEncoder); + +// Called by Init/NewFrame/Shutdown +IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device); +IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); +IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device); +IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); + +#endif +#endif + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_metal.mm b/third_party/imgui/backends/imgui_impl_metal.mm index 26ddc92259b..fd5686be6cd 100644 --- a/third_party/imgui/backends/imgui_impl_metal.mm +++ b/third_party/imgui/backends/imgui_impl_metal.mm @@ -3,15 +3,25 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. +// 2022-07-05: Metal: Add dispatch synchronization. +// 2022-06-30: Metal: Use __bridge for ARC based systems. +// 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler. +// 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts. +// 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code). +// 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file. // 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464) // 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer. @@ -23,117 +33,338 @@ // 2018-07-05: Metal: Added new Metal backend implementation. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_metal.h" - +#import #import -// #import // Not supported in XCode 9.2. Maybe a macro to detect the SDK version can be used (something like #if MACOS_SDK >= 10.13 ...) -#import #pragma mark - Support classes // A wrapper around a MTLBuffer object that knows the last time it was reused @interface MetalBuffer : NSObject @property (nonatomic, strong) id buffer; -@property (nonatomic, assign) NSTimeInterval lastReuseTime; +@property (nonatomic, assign) double lastReuseTime; - (instancetype)initWithBuffer:(id)buffer; @end // An object that encapsulates the data necessary to uniquely identify a // render pipeline state. These are used as cache keys. @interface FramebufferDescriptor : NSObject -@property (nonatomic, assign) unsigned long sampleCount; +@property (nonatomic, assign) unsigned long sampleCount; @property (nonatomic, assign) MTLPixelFormat colorPixelFormat; @property (nonatomic, assign) MTLPixelFormat depthPixelFormat; @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat; -- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor *)renderPassDescriptor; +- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor; @end // A singleton that stores long-lived objects that are needed by the Metal // renderer backend. Stores the render pipeline state cache and the default // font texture, and manages the reusable buffer cache. @interface MetalContext : NSObject -@property (nonatomic, strong) id depthStencilState; -@property (nonatomic, strong) FramebufferDescriptor *framebufferDescriptor; // framebuffer descriptor for current frame; transient -@property (nonatomic, strong) NSMutableDictionary *renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors -@property (nonatomic, strong, nullable) id fontTexture; -@property (nonatomic, strong) NSMutableArray *bufferCache; -@property (nonatomic, assign) NSTimeInterval lastBufferCachePurge; -- (void)makeDeviceObjectsWithDevice:(id)device; -- (void)makeFontTextureWithDevice:(id)device; -- (MetalBuffer *)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; -- (void)enqueueReusableBuffer:(MetalBuffer *)buffer; -- (id)renderPipelineStateForFrameAndDevice:(id)device; -- (void)emptyRenderPipelineStateCache; -- (void)setupRenderState:(ImDrawData *)drawData - commandBuffer:(id)commandBuffer - commandEncoder:(id)commandEncoder - renderPipelineState:(id)renderPipelineState - vertexBuffer:(MetalBuffer *)vertexBuffer - vertexBufferOffset:(size_t)vertexBufferOffset; -- (void)renderDrawData:(ImDrawData *)drawData - commandBuffer:(id)commandBuffer - commandEncoder:(id)commandEncoder; +@property (nonatomic, strong) id device; +@property (nonatomic, strong) id depthStencilState; +@property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; // framebuffer descriptor for current frame; transient +@property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors +@property (nonatomic, strong, nullable) id fontTexture; +@property (nonatomic, strong) NSMutableArray* bufferCache; +@property (nonatomic, assign) double lastBufferCachePurge; +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device; @end -static MetalContext *g_sharedMetalContext = nil; +struct ImGui_ImplMetal_Data +{ + MetalContext* SharedMetalContext; + + ImGui_ImplMetal_Data() { memset(this, 0, sizeof(*this)); } +}; + +static ImGui_ImplMetal_Data* ImGui_ImplMetal_CreateBackendData() { return IM_NEW(ImGui_ImplMetal_Data)(); } +static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); } + +static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); } + +#ifdef IMGUI_IMPL_METAL_CPP + +#pragma mark - Dear ImGui Metal C++ Backend API + +bool ImGui_ImplMetal_Init(MTL::Device* device) +{ + return ImGui_ImplMetal_Init((__bridge id)(device)); +} + +void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor) +{ + ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor)); +} + +void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, + MTL::CommandBuffer* commandBuffer, + MTL::RenderCommandEncoder* commandEncoder) +{ + ImGui_ImplMetal_RenderDrawData(draw_data, + (__bridge id)(commandBuffer), + (__bridge id)(commandEncoder)); + +} + +bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device) +{ + return ImGui_ImplMetal_CreateFontsTexture((__bridge id)(device)); +} + +bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device) +{ + return ImGui_ImplMetal_CreateDeviceObjects((__bridge id)(device)); +} + +#endif // #ifdef IMGUI_IMPL_METAL_CPP -#pragma mark - ImGui API implementation +#pragma mark - Dear ImGui Metal Backend API bool ImGui_ImplMetal_Init(id device) { + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_CreateBackendData(); ImGuiIO& io = ImGui::GetIO(); + io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_metal"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - g_sharedMetalContext = [[MetalContext alloc] init]; - }); - - ImGui_ImplMetal_CreateDeviceObjects(device); + bd->SharedMetalContext = [[MetalContext alloc] init]; + bd->SharedMetalContext.device = device; return true; } void ImGui_ImplMetal_Shutdown() { + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGui_ImplMetal_DestroyDeviceObjects(); + ImGui_ImplMetal_DestroyBackendData(); + + ImGuiIO& io = ImGui::GetIO(); + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; } -void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor *renderPassDescriptor) +void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor) { - IM_ASSERT(g_sharedMetalContext != nil && "No Metal context. Did you call ImGui_ImplMetal_Init() ?"); + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + IM_ASSERT(bd->SharedMetalContext != nil && "No Metal context. Did you call ImGui_ImplMetal_Init() ?"); + bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; - g_sharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; + if (bd->SharedMetalContext.depthStencilState == nil) + ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device); +} + +static void ImGui_ImplMetal_SetupRenderState(ImDrawData* drawData, id commandBuffer, + id commandEncoder, id renderPipelineState, + MetalBuffer* vertexBuffer, size_t vertexBufferOffset) +{ + IM_UNUSED(commandBuffer); + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + [commandEncoder setCullMode:MTLCullModeNone]; + [commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState]; + + // Setup viewport, orthographic projection matrix + // Our visible imgui space lies from draw_data->DisplayPos (top left) to + // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps. + MTLViewport viewport = + { + .originX = 0.0, + .originY = 0.0, + .width = (double)(drawData->DisplaySize.x * drawData->FramebufferScale.x), + .height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y), + .znear = 0.0, + .zfar = 1.0 + }; + [commandEncoder setViewport:viewport]; + + float L = drawData->DisplayPos.x; + float R = drawData->DisplayPos.x + drawData->DisplaySize.x; + float T = drawData->DisplayPos.y; + float B = drawData->DisplayPos.y + drawData->DisplaySize.y; + float N = (float)viewport.znear; + float F = (float)viewport.zfar; + const float ortho_projection[4][4] = + { + { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, + { 0.0f, 0.0f, 1/(F-N), 0.0f }, + { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f }, + }; + [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1]; + + [commandEncoder setRenderPipelineState:renderPipelineState]; + + [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0]; + [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0]; } // Metal Render function. -void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder) +void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id commandBuffer, id commandEncoder) { - [g_sharedMetalContext renderDrawData:draw_data commandBuffer:commandBuffer commandEncoder:commandEncoder]; + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + MetalContext* ctx = bd->SharedMetalContext; + + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x); + int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0) + return; + + // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame + // The hit rate for this cache should be very near 100%. + id renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor]; + if (renderPipelineState == nil) + { + // No luck; make a new render pipeline state + renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device]; + + // Cache render pipeline state for later reuse + ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState; + } + + size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert); + size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx); + MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; + MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; + + ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0); + + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists + size_t vertexBufferOffset = 0; + size_t indexBufferOffset = 0; + for (int n = 0; n < drawData->CmdListsCount; n++) + { + const ImDrawList* cmd_list = drawData->CmdLists[n]; + + memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, cmd_list->VtxBuffer.Data, (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); + memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, cmd_list->IdxBuffer.Data, (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset); + else + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + + // Clamp to viewport as setScissorRect() won't accept values that are off bounds + if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } + if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } + if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + if (pcmd->ElemCount == 0) // drawIndexedPrimitives() validation doesn't accept this + continue; + + // Apply scissor/clipping rectangle + MTLScissorRect scissorRect = + { + .x = NSUInteger(clip_min.x), + .y = NSUInteger(clip_min.y), + .width = NSUInteger(clip_max.x - clip_min.x), + .height = NSUInteger(clip_max.y - clip_min.y) + }; + [commandEncoder setScissorRect:scissorRect]; + + // Bind texture, Draw + if (ImTextureID tex_id = pcmd->GetTexID()) + [commandEncoder setFragmentTexture:(__bridge id)(tex_id) atIndex:0]; + + [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0]; + [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle + indexCount:pcmd->ElemCount + indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 + indexBuffer:indexBuffer.buffer + indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)]; + } + } + + vertexBufferOffset += (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert); + indexBufferOffset += (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx); + } + + [commandBuffer addCompletedHandler:^(id) + { + dispatch_async(dispatch_get_main_queue(), ^{ + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + if (bd != nullptr) + { + @synchronized(bd->SharedMetalContext.bufferCache) + { + [bd->SharedMetalContext.bufferCache addObject:vertexBuffer]; + [bd->SharedMetalContext.bufferCache addObject:indexBuffer]; + } + } + }); + }]; } bool ImGui_ImplMetal_CreateFontsTexture(id device) { - [g_sharedMetalContext makeFontTextureWithDevice:device]; - + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); - io.Fonts->SetTexID((__bridge void *)g_sharedMetalContext.fontTexture); // ImTextureID == void* - return (g_sharedMetalContext.fontTexture != nil); + // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here. + // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth. + // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures. + // You can make that change in your implementation. + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:(NSUInteger)width + height:(NSUInteger)height + mipmapped:NO]; + textureDescriptor.usage = MTLTextureUsageShaderRead; +#if TARGET_OS_OSX || TARGET_OS_MACCATALYST + textureDescriptor.storageMode = MTLStorageModeManaged; +#else + textureDescriptor.storageMode = MTLStorageModeShared; +#endif + id texture = [device newTextureWithDescriptor:textureDescriptor]; + [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4]; + bd->SharedMetalContext.fontTexture = texture; + io.Fonts->SetTexID((__bridge void*)bd->SharedMetalContext.fontTexture); // ImTextureID == void* + + return (bd->SharedMetalContext.fontTexture != nil); } void ImGui_ImplMetal_DestroyFontsTexture() { + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); - g_sharedMetalContext.fontTexture = nil; - io.Fonts->SetTexID(nullptr); + bd->SharedMetalContext.fontTexture = nil; + io.Fonts->SetTexID(0); } bool ImGui_ImplMetal_CreateDeviceObjects(id device) { - [g_sharedMetalContext makeDeviceObjectsWithDevice:device]; - + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init]; + depthStencilDescriptor.depthWriteEnabled = NO; + depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways; + bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor]; ImGui_ImplMetal_CreateFontsTexture(device); return true; @@ -141,8 +372,9 @@ bool ImGui_ImplMetal_CreateDeviceObjects(id device) void ImGui_ImplMetal_DestroyDeviceObjects() { + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); ImGui_ImplMetal_DestroyFontsTexture(); - [g_sharedMetalContext emptyRenderPipelineStateCache]; + [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects]; } #pragma mark - MetalBuffer implementation @@ -153,7 +385,7 @@ - (instancetype)initWithBuffer:(id)buffer if ((self = [super init])) { _buffer = buffer; - _lastReuseTime = [NSDate date].timeIntervalSince1970; + _lastReuseTime = GetMachAbsoluteTimeInSeconds(); } return self; } @@ -162,7 +394,7 @@ - (instancetype)initWithBuffer:(id)buffer #pragma mark - FramebufferDescriptor implementation @implementation FramebufferDescriptor -- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor *)renderPassDescriptor +- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor { if ((self = [super init])) { @@ -174,9 +406,9 @@ - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor *)renderPa return self; } -- (nonnull id)copyWithZone:(nullable NSZone *)zone +- (nonnull id)copyWithZone:(nullable NSZone*)zone { - FramebufferDescriptor *copy = [[FramebufferDescriptor allocWithZone:zone] init]; + FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; copy.sampleCount = self.sampleCount; copy.colorPixelFormat = self.colorPixelFormat; copy.depthPixelFormat = self.depthPixelFormat; @@ -196,7 +428,7 @@ - (NSUInteger)hash - (BOOL)isEqual:(id)object { - FramebufferDescriptor *other = object; + FramebufferDescriptor* other = object; if (![other isKindOfClass:[FramebufferDescriptor class]]) return NO; return other.sampleCount == self.sampleCount && @@ -210,79 +442,46 @@ - (BOOL)isEqual:(id)object #pragma mark - MetalContext implementation @implementation MetalContext -- (instancetype)init { +- (instancetype)init +{ if ((self = [super init])) { - _renderPipelineStateCache = [NSMutableDictionary dictionary]; - _bufferCache = [NSMutableArray array]; - _lastBufferCachePurge = [NSDate date].timeIntervalSince1970; + self.renderPipelineStateCache = [NSMutableDictionary dictionary]; + self.bufferCache = [NSMutableArray array]; + _lastBufferCachePurge = GetMachAbsoluteTimeInSeconds(); } return self; } -- (void)makeDeviceObjectsWithDevice:(id)device -{ - MTLDepthStencilDescriptor *depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init]; - depthStencilDescriptor.depthWriteEnabled = NO; - depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways; - self.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor]; -} - -// We are retrieving and uploading the font atlas as a 4-channels RGBA texture here. -// In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth. -// However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures. -// You can make that change in your implementation. -- (void)makeFontTextureWithDevice:(id)device -{ - ImGuiIO &io = ImGui::GetIO(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm - width:(NSUInteger)width - height:(NSUInteger)height - mipmapped:NO]; - textureDescriptor.usage = MTLTextureUsageShaderRead; -#if TARGET_OS_OSX || TARGET_OS_MACCATALYST - textureDescriptor.storageMode = MTLStorageModeManaged; -#else - textureDescriptor.storageMode = MTLStorageModeShared; -#endif - id texture = [device newTextureWithDescriptor:textureDescriptor]; - [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4]; - self.fontTexture = texture; -} - -- (MetalBuffer *)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device { - NSTimeInterval now = [NSDate date].timeIntervalSince1970; + uint64_t now = GetMachAbsoluteTimeInSeconds(); - // Purge old buffers that haven't been useful for a while - if (now - self.lastBufferCachePurge > 1.0) + @synchronized(self.bufferCache) { - NSMutableArray *survivors = [NSMutableArray array]; - for (MetalBuffer *candidate in self.bufferCache) + // Purge old buffers that haven't been useful for a while + if (now - self.lastBufferCachePurge > 1.0) { - if (candidate.lastReuseTime > self.lastBufferCachePurge) - { - [survivors addObject:candidate]; - } + NSMutableArray* survivors = [NSMutableArray array]; + for (MetalBuffer* candidate in self.bufferCache) + if (candidate.lastReuseTime > self.lastBufferCachePurge) + [survivors addObject:candidate]; + self.bufferCache = [survivors mutableCopy]; + self.lastBufferCachePurge = now; } - self.bufferCache = [survivors mutableCopy]; - self.lastBufferCachePurge = now; - } - // See if we have a buffer we can reuse - MetalBuffer *bestCandidate = nil; - for (MetalBuffer *candidate in self.bufferCache) - if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime)) - bestCandidate = candidate; + // See if we have a buffer we can reuse + MetalBuffer* bestCandidate = nil; + for (MetalBuffer* candidate in self.bufferCache) + if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime)) + bestCandidate = candidate; - if (bestCandidate != nil) - { - [self.bufferCache removeObject:bestCandidate]; - bestCandidate.lastReuseTime = now; - return bestCandidate; + if (bestCandidate != nil) + { + [self.bufferCache removeObject:bestCandidate]; + bestCandidate.lastReuseTime = now; + return bestCandidate; + } } // No luck; make a new buffer @@ -290,33 +489,12 @@ - (MetalBuffer *)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)renderPipelineStateForFrameAndDevice:(id)device +// Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device { - // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame - // The hit rate for this cache should be very near 100%. - id renderPipelineState = self.renderPipelineStateCache[self.framebufferDescriptor]; + NSError* error = nil; - if (renderPipelineState == nil) - { - // No luck; make a new render pipeline state - renderPipelineState = [self _renderPipelineStateForFramebufferDescriptor:self.framebufferDescriptor device:device]; - // Cache render pipeline state for later reuse - self.renderPipelineStateCache[self.framebufferDescriptor] = renderPipelineState; - } - - return renderPipelineState; -} - -- (id)_renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor *)descriptor device:(id)device -{ - NSError *error = nil; - - NSString *shaderSource = @"" + NSString* shaderSource = @"" "#include \n" "using namespace metal;\n" "\n" @@ -368,25 +546,25 @@ - (void)enqueueReusableBuffer:(MetalBuffer *)buffer return nil; } - MTLVertexDescriptor *vertexDescriptor = [MTLVertexDescriptor vertexDescriptor]; - vertexDescriptor.attributes[0].offset = IM_OFFSETOF(ImDrawVert, pos); + MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor]; + vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos); vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position vertexDescriptor.attributes[0].bufferIndex = 0; - vertexDescriptor.attributes[1].offset = IM_OFFSETOF(ImDrawVert, uv); + vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv); vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords vertexDescriptor.attributes[1].bufferIndex = 0; - vertexDescriptor.attributes[2].offset = IM_OFFSETOF(ImDrawVert, col); + vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col); vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color vertexDescriptor.attributes[2].bufferIndex = 0; vertexDescriptor.layouts[0].stepRate = 1; vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex; vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert); - MTLRenderPipelineDescriptor *pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; + MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; pipelineDescriptor.vertexFunction = vertexFunction; pipelineDescriptor.fragmentFunction = fragmentFunction; pipelineDescriptor.vertexDescriptor = vertexDescriptor; - pipelineDescriptor.sampleCount = self.framebufferDescriptor.sampleCount; + pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount; pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat; pipelineDescriptor.colorAttachments[0].blendingEnabled = YES; pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd; @@ -400,157 +578,13 @@ - (void)enqueueReusableBuffer:(MetalBuffer *)buffer id renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error]; if (error != nil) - { NSLog(@"Error: failed to create Metal pipeline state: %@", error); - } return renderPipelineState; } -- (void)emptyRenderPipelineStateCache -{ - [self.renderPipelineStateCache removeAllObjects]; -} - -- (void)setupRenderState:(ImDrawData *)drawData - commandBuffer:(id)commandBuffer - commandEncoder:(id)commandEncoder - renderPipelineState:(id)renderPipelineState - vertexBuffer:(MetalBuffer *)vertexBuffer - vertexBufferOffset:(size_t)vertexBufferOffset -{ - [commandEncoder setCullMode:MTLCullModeNone]; - [commandEncoder setDepthStencilState:g_sharedMetalContext.depthStencilState]; - - // Setup viewport, orthographic projection matrix - // Our visible imgui space lies from draw_data->DisplayPos (top left) to - // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps. - MTLViewport viewport = - { - .originX = 0.0, - .originY = 0.0, - .width = (double)(drawData->DisplaySize.x * drawData->FramebufferScale.x), - .height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y), - .znear = 0.0, - .zfar = 1.0 - }; - [commandEncoder setViewport:viewport]; - - float L = drawData->DisplayPos.x; - float R = drawData->DisplayPos.x + drawData->DisplaySize.x; - float T = drawData->DisplayPos.y; - float B = drawData->DisplayPos.y + drawData->DisplaySize.y; - float N = (float)viewport.znear; - float F = (float)viewport.zfar; - const float ortho_projection[4][4] = - { - { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, - { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, - { 0.0f, 0.0f, 1/(F-N), 0.0f }, - { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f }, - }; - [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1]; - - [commandEncoder setRenderPipelineState:renderPipelineState]; - - [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0]; - [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0]; -} - -- (void)renderDrawData:(ImDrawData *)drawData - commandBuffer:(id)commandBuffer - commandEncoder:(id)commandEncoder -{ - // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x); - int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y); - if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0) - return; - - id renderPipelineState = [self renderPipelineStateForFrameAndDevice:commandBuffer.device]; - - size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert); - size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx); - MetalBuffer* vertexBuffer = [self dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; - MetalBuffer* indexBuffer = [self dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; - - [self setupRenderState:drawData commandBuffer:commandBuffer commandEncoder:commandEncoder renderPipelineState:renderPipelineState vertexBuffer:vertexBuffer vertexBufferOffset:0]; - - // Will project scissor/clipping rectangles into framebuffer space - ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports - ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2) - - // Render command lists - size_t vertexBufferOffset = 0; - size_t indexBufferOffset = 0; - for (int n = 0; n < drawData->CmdListsCount; n++) - { - const ImDrawList* cmd_list = drawData->CmdLists[n]; - - memcpy((char *)vertexBuffer.buffer.contents + vertexBufferOffset, cmd_list->VtxBuffer.Data, (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); - memcpy((char *)indexBuffer.buffer.contents + indexBufferOffset, cmd_list->IdxBuffer.Data, (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); - - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) - { - const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback) - { - // User callback, registered via ImDrawList::AddCallback() - // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) - if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - [self setupRenderState:drawData commandBuffer:commandBuffer commandEncoder:commandEncoder renderPipelineState:renderPipelineState vertexBuffer:vertexBuffer vertexBufferOffset:vertexBufferOffset]; - else - pcmd->UserCallback(cmd_list, pcmd); - } - else - { - // Project scissor/clipping rectangles into framebuffer space - ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); - ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); - - // Clamp to viewport as setScissorRect() won't accept values that are off bounds - if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } - if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } - if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } - if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } - if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) - continue; - - // Apply scissor/clipping rectangle - MTLScissorRect scissorRect = - { - .x = NSUInteger(clip_min.x), - .y = NSUInteger(clip_min.y), - .width = NSUInteger(clip_max.x - clip_min.x), - .height = NSUInteger(clip_max.y - clip_min.y) - }; - [commandEncoder setScissorRect:scissorRect]; - - // Bind texture, Draw - if (ImTextureID tex_id = pcmd->GetTexID()) - [commandEncoder setFragmentTexture:(__bridge id)(tex_id) atIndex:0]; - - [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0]; - [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle - indexCount:pcmd->ElemCount - indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 - indexBuffer:indexBuffer.buffer - indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)]; - } - } - - vertexBufferOffset += (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert); - indexBufferOffset += (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx); - } +@end - __weak id weakSelf = self; - [commandBuffer addCompletedHandler:^(id) - { - dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf enqueueReusableBuffer:vertexBuffer]; - [weakSelf enqueueReusableBuffer:indexBuffer]; - }); - }]; -} +//----------------------------------------------------------------------------- -@end +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_opengl2.cpp b/third_party/imgui/backends/imgui_impl_opengl2.cpp index 17a6faebb5e..17935b1f3f0 100644 --- a/third_party/imgui/backends/imgui_impl_opengl2.cpp +++ b/third_party/imgui/backends/imgui_impl_opengl2.cpp @@ -6,8 +6,11 @@ // 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in imgui_impl_opengl3.cpp** @@ -19,7 +22,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2021-12-08: OpenGL: Fixed mishandling of the the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2021-12-08: OpenGL: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-01-03: OpenGL: Backup, setup and restore GL_SHADE_MODEL state, disable GL_STENCIL_TEST and disable GL_NORMAL_ARRAY client state to increase compatibility with legacy OpenGL applications. @@ -36,11 +40,15 @@ // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_opengl2.h" -#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier -#include // intptr_t -#else #include // intptr_t + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" #endif // Include OpenGL header (without an OpenGL loader) requires a bit of fiddling @@ -61,21 +69,21 @@ struct ImGui_ImplOpenGL2_Data { GLuint FontTexture; - ImGui_ImplOpenGL2_Data() { memset(this, 0, sizeof(*this)); } + ImGui_ImplOpenGL2_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplOpenGL2_Data* ImGui_ImplOpenGL2_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL2_Data*)ImGui::GetIO().BackendRendererUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions bool ImGui_ImplOpenGL2_Init() { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplOpenGL2_Data* bd = IM_NEW(ImGui_ImplOpenGL2_Data)(); @@ -88,19 +96,19 @@ bool ImGui_ImplOpenGL2_Init() void ImGui_ImplOpenGL2_Shutdown() { ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL2_DestroyDeviceObjects(); - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; IM_DELETE(bd); } void ImGui_ImplOpenGL2_NewFrame() { ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplOpenGL2_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplOpenGL2_Init()?"); if (!bd->FontTexture) ImGui_ImplOpenGL2_CreateDeviceObjects(); @@ -183,9 +191,9 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; - glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos))); - glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv))); - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col))); + glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, pos))); + glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, uv))); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, col))); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { @@ -208,7 +216,7 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) continue; // Apply scissor/clipping rectangle (Y is inverted in OpenGL) - glScissor((int)clip_min.x, (int)(fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)); + glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)); // Bind texture, Draw glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()); @@ -244,6 +252,7 @@ bool ImGui_ImplOpenGL2_CreateFontsTexture() io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGenTextures(1, &bd->FontTexture); @@ -283,3 +292,11 @@ void ImGui_ImplOpenGL2_DestroyDeviceObjects() { ImGui_ImplOpenGL2_DestroyFontsTexture(); } + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_opengl2.h b/third_party/imgui/backends/imgui_impl_opengl2.h index d00d27f1f8c..9c756c71d6b 100644 --- a/third_party/imgui/backends/imgui_impl_opengl2.h +++ b/third_party/imgui/backends/imgui_impl_opengl2.h @@ -4,10 +4,13 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in imgui_impl_opengl3.cpp** @@ -19,6 +22,7 @@ #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown(); @@ -30,3 +34,5 @@ IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateFontsTexture(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_opengl3.cpp b/third_party/imgui/backends/imgui_impl_opengl3.cpp index 0ed8348d199..b3a510bcd52 100644 --- a/third_party/imgui/backends/imgui_impl_opengl3.cpp +++ b/third_party/imgui/backends/imgui_impl_opengl3.cpp @@ -5,15 +5,37 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! -// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices. +// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). + +// About WebGL/ES: +// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. +// - This is done automatically on iOS, Android and Emscripten targets. +// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink. +// 2023-11-08: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983) +// 2023-10-05: OpenGL: Rename symbols in our internal loader so that LTO compilation with another copy of gl3w is possible. (#6875, #6668, #4445) +// 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333) +// 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375) +// 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333) +// 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224) +// 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530) +// 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224) +// 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes). +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-09-27: OpenGL: Added ability to '#define IMGUI_IMPL_OPENGL_DEBUG'. +// 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127). +// 2022-05-13: OpenGL: Fixed state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states. // 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers. // 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions. // 2021-08-19: OpenGL: Embed and use our own minimal GL loader (imgui_impl_opengl3_loader.h), removing requirement and support for third-party loader. @@ -54,7 +76,7 @@ // 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples. // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. // 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state. -// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a NULL pointer. +// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a nullptr pointer. // 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150". // 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context. // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself. @@ -88,17 +110,37 @@ #endif #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_opengl3.h" #include -#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier -#include // intptr_t -#else #include // intptr_t +#if defined(__APPLE__) +#include +#endif + +// Clang/GCC warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) +#endif +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind +#pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' +#pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader) #endif // GL includes #if defined(IMGUI_IMPL_OPENGL_ES2) -#include +#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) +#include // Use GL ES 2 +#else +#include // Use GL ES 2 +#endif #if defined(__EMSCRIPTEN__) #ifndef GL_GLEXT_PROTOTYPES #define GL_GLEXT_PROTOTYPES @@ -106,9 +148,6 @@ #include #endif #elif defined(IMGUI_IMPL_OPENGL_ES3) -#if defined(__APPLE__) -#include -#endif #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) #include // Use GL ES 3 #else @@ -137,9 +176,20 @@ #define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES #endif -// Desktop GL 2.0+ has glPolygonMode() which GL ES and WebGL don't have. -#ifdef GL_POLYGON_MODE -#define IMGUI_IMPL_HAS_POLYGON_MODE +// Desktop GL 2.0+ has extension and glPolygonMode() which GL ES and WebGL don't have.. +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) +#define IMGUI_IMPL_OPENGL_HAS_EXTENSIONS // has glGetIntegerv(GL_NUM_EXTENSIONS) +#define IMGUI_IMPL_OPENGL_HAS_POLYGON_MODE // has glPolygonMode() +#endif + +// Desktop GL 2.1+ and GL ES 3.0+ have glBindBuffer() with GL_PIXEL_UNPACK_BUFFER target. +#if !defined(IMGUI_IMPL_OPENGL_ES2) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK +#endif + +// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state +#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1) +#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART #endif // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have. @@ -147,19 +197,18 @@ #define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET #endif -// Desktop GL 3.3+ has glBindSampler() -#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_3) +// Desktop GL 3.3+ and GL ES 3.0+ have glBindSampler() +#if !defined(IMGUI_IMPL_OPENGL_ES2) && (defined(IMGUI_IMPL_OPENGL_ES3) || defined(GL_VERSION_3_3)) #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER #endif -// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state -#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1) -#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART -#endif - -// Desktop GL use extension detection -#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) -#define IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS +// [Debugging] +//#define IMGUI_IMPL_OPENGL_DEBUG +#ifdef IMGUI_IMPL_OPENGL_DEBUG +#include +#define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check +#else +#define GL_CALL(_CALL) _CALL // Call without error check #endif // OpenGL Data @@ -167,6 +216,10 @@ struct ImGui_ImplOpenGL3_Data { GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2) char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings. + bool GlProfileIsES2; + bool GlProfileIsES3; + bool GlProfileIsCompat; + GLint GlProfileMask; GLuint FontTexture; GLuint ShaderHandle; GLint AttribLocationTex; // Uniforms location @@ -178,22 +231,47 @@ struct ImGui_ImplOpenGL3_Data GLsizeiptr VertexBufferSize; GLsizeiptr IndexBufferSize; bool HasClipOrigin; + bool UseBufferSubData; - ImGui_ImplOpenGL3_Data() { memset(this, 0, sizeof(*this)); } + ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +// OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only) +#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY +struct ImGui_ImplOpenGL3_VtxAttribState +{ + GLint Enabled, Size, Type, Normalized, Stride; + GLvoid* Ptr; + + void GetState(GLint index) + { + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized); + glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride); + glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr); + } + void SetState(GLint index) + { + glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr); + if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index); + } +}; +#endif + // Functions bool ImGui_ImplOpenGL3_Init(const char* glsl_version) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Initialize our loader #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM) @@ -210,7 +288,12 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) io.BackendRendererName = "imgui_impl_opengl3"; // Query for GL version (e.g. 320 for GL 3.2) -#if !defined(IMGUI_IMPL_OPENGL_ES2) +#if defined(IMGUI_IMPL_OPENGL_ES2) + // GLES 2 + bd->GlVersion = 200; + bd->GlProfileIsES2 = true; +#else + // Desktop or GLES 3 GLint major = 0; GLint minor = 0; glGetIntegerv(GL_MAJOR_VERSION, &major); @@ -222,8 +305,29 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) sscanf(gl_version, "%d.%d", &major, &minor); } bd->GlVersion = (GLuint)(major * 100 + minor * 10); -#else - bd->GlVersion = 200; // GLES 2 +#if defined(GL_CONTEXT_PROFILE_MASK) + if (bd->GlVersion >= 320) + glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask); + bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0; +#endif + +#if defined(IMGUI_IMPL_OPENGL_ES3) + bd->GlProfileIsES3 = true; +#endif + + bd->UseBufferSubData = false; + /* + // Query vendor to enable glBufferSubData kludge +#ifdef _WIN32 + if (const char* vendor = (const char*)glGetString(GL_VENDOR)) + if (strncmp(vendor, "Intel", 5) == 0) + bd->UseBufferSubData = true; +#endif + */ +#endif + +#ifdef IMGUI_IMPL_OPENGL_DEBUG + printf("GlVersion = %d\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG] #endif #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET @@ -232,8 +336,8 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) #endif // Store GLSL version string so we can refer to it later in case we recreate shaders. - // Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure. - if (glsl_version == NULL) + // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure. + if (glsl_version == nullptr) { #if defined(IMGUI_IMPL_OPENGL_ES2) glsl_version = "#version 100"; @@ -256,13 +360,13 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) // Detect extensions we support bd->HasClipOrigin = (bd->GlVersion >= 450); -#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS +#ifdef IMGUI_IMPL_OPENGL_HAS_EXTENSIONS GLint num_extensions = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); for (GLint i = 0; i < num_extensions; i++) { const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i); - if (extension != NULL && strcmp(extension, "GL_ARB_clip_control") == 0) + if (extension != nullptr && strcmp(extension, "GL_ARB_clip_control") == 0) bd->HasClipOrigin = true; } #endif @@ -273,19 +377,20 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) void ImGui_ImplOpenGL3_Shutdown() { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL3_DestroyDeviceObjects(); - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplOpenGL3_NewFrame() { ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplOpenGL3_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplOpenGL3_Init()?"); if (!bd->ShaderHandle) ImGui_ImplOpenGL3_CreateDeviceObjects(); @@ -307,7 +412,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid if (bd->GlVersion >= 310) glDisable(GL_PRIMITIVE_RESTART); #endif -#ifdef IMGUI_IMPL_HAS_POLYGON_MODE +#ifdef IMGUI_IMPL_OPENGL_HAS_POLYGON_MODE glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif @@ -324,7 +429,7 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. - glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); + GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height)); float L = draw_data->DisplayPos.x; float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; @@ -344,8 +449,8 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER - if (bd->GlVersion >= 330) - glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 may set that otherwise. + if (bd->GlVersion >= 330 || bd->GlProfileIsES3) + glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise. #endif (void)vertex_array_object; @@ -354,14 +459,14 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid #endif // Bind vertex/index buffers and setup attributes for ImDrawVert - glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle); - glEnableVertexAttribArray(bd->AttribLocationVtxPos); - glEnableVertexAttribArray(bd->AttribLocationVtxUV); - glEnableVertexAttribArray(bd->AttribLocationVtxColor); - glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)); - glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)); - glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)); + GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle)); + GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle)); + GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos)); + GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV)); + GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor)); + GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos))); + GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv))); + GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col))); } // OpenGL3 Render function. @@ -383,13 +488,20 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program); GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER - GLuint last_sampler; if (bd->GlVersion >= 330) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } + GLuint last_sampler; if (bd->GlVersion >= 330 || bd->GlProfileIsES3) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; } #endif GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer); +#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + // This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+. + GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); + ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos); + ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV); + ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor); +#endif #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object); #endif -#ifdef IMGUI_IMPL_HAS_POLYGON_MODE +#ifdef IMGUI_IMPL_OPENGL_HAS_POLYGON_MODE GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); #endif GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); @@ -414,7 +526,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound. GLuint vertex_array_object = 0; #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY - glGenVertexArrays(1, &vertex_array_object); + GL_CALL(glGenVertexArrays(1, &vertex_array_object)); #endif ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); @@ -428,25 +540,40 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) const ImDrawList* cmd_list = draw_data->CmdLists[n]; // Upload vertex/index buffers - GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert); - GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx); - if (bd->VertexBufferSize < vtx_buffer_size) + // - OpenGL drivers are in a very sorry state nowadays.... + // During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports + // of leaks on Intel GPU when using multi-viewports on Windows. + // - After this we kept hearing of various display corruptions issues. We started disabling on non-Intel GPU, but issues still got reported on Intel. + // - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code. + // We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path. + // - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues. + const GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert); + const GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx); + if (bd->UseBufferSubData) { - bd->VertexBufferSize = vtx_buffer_size; - glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, NULL, GL_STREAM_DRAW); + if (bd->VertexBufferSize < vtx_buffer_size) + { + bd->VertexBufferSize = vtx_buffer_size; + GL_CALL(glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, nullptr, GL_STREAM_DRAW)); + } + if (bd->IndexBufferSize < idx_buffer_size) + { + bd->IndexBufferSize = idx_buffer_size; + GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW)); + } + GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data)); + GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data)); } - if (bd->IndexBufferSize < idx_buffer_size) + else { - bd->IndexBufferSize = idx_buffer_size; - glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, NULL, GL_STREAM_DRAW); + GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW)); + GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW)); } - glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != NULL) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) @@ -464,30 +591,31 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) continue; // Apply scissor/clipping rectangle (Y is inverted in OpenGL) - glScissor((int)clip_min.x, (int)(fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)); + GL_CALL(glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y))); // Bind texture, Draw - glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()); + GL_CALL(glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID())); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET if (bd->GlVersion >= 320) - glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset); + GL_CALL(glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset)); else #endif - glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx))); + GL_CALL(glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)))); } } } // Destroy the temporary VAO #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY - glDeleteVertexArrays(1, &vertex_array_object); + GL_CALL(glDeleteVertexArrays(1, &vertex_array_object)); #endif // Restore modified GL state - glUseProgram(last_program); + // This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220. + if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER - if (bd->GlVersion >= 330) + if (bd->GlVersion >= 330 || bd->GlProfileIsES3) glBindSampler(0, last_sampler); #endif glActiveTexture(last_active_texture); @@ -495,6 +623,12 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) glBindVertexArray(last_vertex_array_object); #endif glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); +#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); + last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos); + last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV); + last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor); +#endif glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha); if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); @@ -506,9 +640,19 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } #endif -#ifdef IMGUI_IMPL_HAS_POLYGON_MODE - glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); -#endif +#ifdef IMGUI_IMPL_OPENGL_HAS_POLYGON_MODE + // Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons + if (bd->GlVersion <= 310 || bd->GlProfileIsCompat) + { + glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); + glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]); + } + else + { + glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); + } +#endif // IMGUI_IMPL_OPENGL_HAS_POLYGON_MODE + glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); (void)bd; // Not all compilation paths use this @@ -525,22 +669,23 @@ bool ImGui_ImplOpenGL3_CreateFontsTexture() io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) GLint last_texture; - glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); - glGenTextures(1, &bd->FontTexture); - glBindTexture(GL_TEXTURE_2D, bd->FontTexture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture)); + GL_CALL(glGenTextures(1, &bd->FontTexture)); + GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); + GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); #ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); #endif - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels)); // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); // Restore state - glBindTexture(GL_TEXTURE_2D, last_texture); + GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture)); return true; } @@ -570,7 +715,7 @@ static bool CheckShader(GLuint handle, const char* desc) { ImVector buf; buf.resize((int)(log_length + 1)); - glGetShaderInfoLog(handle, log_length, NULL, (GLchar*)buf.begin()); + glGetShaderInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin()); fprintf(stderr, "%s\n", buf.begin()); } return (GLboolean)status == GL_TRUE; @@ -589,7 +734,7 @@ static bool CheckProgram(GLuint handle, const char* desc) { ImVector buf; buf.resize((int)(log_length + 1)); - glGetProgramInfoLog(handle, log_length, NULL, (GLchar*)buf.begin()); + glGetProgramInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin()); fprintf(stderr, "%s\n", buf.begin()); } return (GLboolean)status == GL_TRUE; @@ -603,6 +748,10 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() GLint last_texture, last_array_buffer; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK + GLint last_pixel_unpack_buffer; + if (bd->GlVersion >= 210) { glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &last_pixel_unpack_buffer); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } +#endif #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); @@ -713,8 +862,8 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() "}\n"; // Select shaders matching our GLSL versions - const GLchar* vertex_shader = NULL; - const GLchar* fragment_shader = NULL; + const GLchar* vertex_shader = nullptr; + const GLchar* fragment_shader = nullptr; if (glsl_version < 130) { vertex_shader = vertex_shader_glsl_120; @@ -739,13 +888,13 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() // Create shaders const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader }; GLuint vert_handle = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vert_handle, 2, vertex_shader_with_version, NULL); + glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr); glCompileShader(vert_handle); CheckShader(vert_handle, "vertex shader"); const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader }; GLuint frag_handle = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(frag_handle, 2, fragment_shader_with_version, NULL); + glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr); glCompileShader(frag_handle); CheckShader(frag_handle, "fragment shader"); @@ -776,6 +925,9 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); +#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK + if (bd->GlVersion >= 210) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, last_pixel_unpack_buffer); } +#endif #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY glBindVertexArray(last_vertex_array); #endif @@ -791,3 +943,14 @@ void ImGui_ImplOpenGL3_DestroyDeviceObjects() if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; } ImGui_ImplOpenGL3_DestroyFontsTexture(); } + +//----------------------------------------------------------------------------- + +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_opengl3.h b/third_party/imgui/backends/imgui_impl_opengl3.h index 98c9aca1005..23eb924791e 100644 --- a/third_party/imgui/backends/imgui_impl_opengl3.h +++ b/third_party/imgui/backends/imgui_impl_opengl3.h @@ -5,23 +5,32 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! -// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices. +// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). + +// About WebGL/ES: +// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES. +// - This is done automatically on iOS, Android and Emscripten targets. +// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // About GLSL version: -// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string. +// The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string. // On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" // Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE // Backend API -IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = NULL); +IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr); IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); @@ -46,10 +55,12 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); #endif #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" -#elif defined(__EMSCRIPTEN__) +#elif defined(__EMSCRIPTEN__) || defined(__amigaos4__) #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" #else // Otherwise imgui_impl_opengl3_loader.h will be used. #endif #endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_opengl3_loader.h b/third_party/imgui/backends/imgui_impl_opengl3_loader.h index 8452301ef91..4019f937fb2 100644 --- a/third_party/imgui/backends/imgui_impl_opengl3_loader.h +++ b/third_party/imgui/backends/imgui_impl_opengl3_loader.h @@ -9,6 +9,14 @@ // YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY. // THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE. // +// IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions): +// IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCUDING 'imgui_impl_opengl3_loader.h' +// IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER. +// (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS) +// YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT. +// BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp +// WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT. +// // Regenerate with: // python gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt // @@ -110,7 +118,7 @@ extern "C" { ** included as . ** ** glcorearb.h includes only APIs in the latest OpenGL core profile -** implementation together with APIs in newer ARB extensions which +** implementation together with APIs in newer ARB extensions which ** can be supported by the core profile. It does not, and never will ** include functionality removed from the core profile, such as ** fixed-function vertex and fragment processing. @@ -146,6 +154,8 @@ typedef khronos_uint8_t GLubyte; #define GL_ONE 1 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 #define GL_FRONT_AND_BACK 0x0408 #define GL_POLYGON_MODE 0x0B40 #define GL_CULL_FACE 0x0B44 @@ -164,6 +174,8 @@ typedef khronos_uint8_t GLubyte; #define GL_FLOAT 0x1406 #define GL_RGBA 0x1908 #define GL_FILL 0x1B02 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 #define GL_LINEAR 0x2601 @@ -177,6 +189,7 @@ typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask); typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap); typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap); +typedef void (APIENTRYP PFNGLFLUSHPROC) (void); typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void); @@ -193,6 +206,7 @@ GLAPI void APIENTRY glClear (GLbitfield mask); GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI void APIENTRY glDisable (GLenum cap); GLAPI void APIENTRY glEnable (GLenum cap); +GLAPI void APIENTRY glFlush (void); GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param); GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); GLAPI GLenum APIENTRY glGetError (void); @@ -244,7 +258,10 @@ typedef khronos_intptr_t GLintptr; #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_STREAM_DRAW 0x88E0 +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); @@ -264,7 +281,13 @@ typedef khronos_int16_t GLshort; typedef khronos_int8_t GLbyte; typedef khronos_uint16_t GLushort; #define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_COMPILE_STATUS 0x8B81 @@ -280,6 +303,7 @@ typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); @@ -287,6 +311,9 @@ typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei buf typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); @@ -302,6 +329,7 @@ GLAPI GLuint APIENTRY glCreateShader (GLenum type); GLAPI void APIENTRY glDeleteProgram (GLuint program); GLAPI void APIENTRY glDeleteShader (GLuint shader); GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index); GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index); GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); @@ -309,6 +337,9 @@ GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsize GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgram (GLuint program); GLAPI void APIENTRY glLinkProgram (GLuint program); GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); GLAPI void APIENTRY glUseProgram (GLuint program); @@ -346,6 +377,8 @@ GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); typedef struct __GLsync *GLsync; typedef khronos_uint64_t GLuint64; typedef khronos_int64_t GLint64; +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_CONTEXT_PROFILE_MASK 0x9126 typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); #ifdef GL_GLEXT_PROTOTYPES @@ -436,123 +469,133 @@ GL3W_API int imgl3wIsSupported(int major, int minor); GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc); /* gl3w internal state */ -union GL3WProcs { - GL3WglProc ptr[53]; +union ImGL3WProcs { + GL3WglProc ptr[59]; struct { - PFNGLACTIVETEXTUREPROC ActiveTexture; - PFNGLATTACHSHADERPROC AttachShader; - PFNGLBINDBUFFERPROC BindBuffer; - PFNGLBINDSAMPLERPROC BindSampler; - PFNGLBINDTEXTUREPROC BindTexture; - PFNGLBINDVERTEXARRAYPROC BindVertexArray; - PFNGLBLENDEQUATIONPROC BlendEquation; - PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate; - PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate; - PFNGLBUFFERDATAPROC BufferData; - PFNGLBUFFERSUBDATAPROC BufferSubData; - PFNGLCLEARPROC Clear; - PFNGLCLEARCOLORPROC ClearColor; - PFNGLCOMPILESHADERPROC CompileShader; - PFNGLCREATEPROGRAMPROC CreateProgram; - PFNGLCREATESHADERPROC CreateShader; - PFNGLDELETEBUFFERSPROC DeleteBuffers; - PFNGLDELETEPROGRAMPROC DeleteProgram; - PFNGLDELETESHADERPROC DeleteShader; - PFNGLDELETETEXTURESPROC DeleteTextures; - PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays; - PFNGLDETACHSHADERPROC DetachShader; - PFNGLDISABLEPROC Disable; - PFNGLDRAWELEMENTSPROC DrawElements; - PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex; - PFNGLENABLEPROC Enable; - PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray; - PFNGLGENBUFFERSPROC GenBuffers; - PFNGLGENTEXTURESPROC GenTextures; - PFNGLGENVERTEXARRAYSPROC GenVertexArrays; - PFNGLGETATTRIBLOCATIONPROC GetAttribLocation; - PFNGLGETERRORPROC GetError; - PFNGLGETINTEGERVPROC GetIntegerv; - PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog; - PFNGLGETPROGRAMIVPROC GetProgramiv; - PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog; - PFNGLGETSHADERIVPROC GetShaderiv; - PFNGLGETSTRINGPROC GetString; - PFNGLGETSTRINGIPROC GetStringi; - PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation; - PFNGLISENABLEDPROC IsEnabled; - PFNGLLINKPROGRAMPROC LinkProgram; - PFNGLPIXELSTOREIPROC PixelStorei; - PFNGLPOLYGONMODEPROC PolygonMode; - PFNGLREADPIXELSPROC ReadPixels; - PFNGLSCISSORPROC Scissor; - PFNGLSHADERSOURCEPROC ShaderSource; - PFNGLTEXIMAGE2DPROC TexImage2D; - PFNGLTEXPARAMETERIPROC TexParameteri; - PFNGLUNIFORM1IPROC Uniform1i; - PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv; - PFNGLUSEPROGRAMPROC UseProgram; - PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer; - PFNGLVIEWPORTPROC Viewport; + PFNGLACTIVETEXTUREPROC ActiveTexture; + PFNGLATTACHSHADERPROC AttachShader; + PFNGLBINDBUFFERPROC BindBuffer; + PFNGLBINDSAMPLERPROC BindSampler; + PFNGLBINDTEXTUREPROC BindTexture; + PFNGLBINDVERTEXARRAYPROC BindVertexArray; + PFNGLBLENDEQUATIONPROC BlendEquation; + PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate; + PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate; + PFNGLBUFFERDATAPROC BufferData; + PFNGLBUFFERSUBDATAPROC BufferSubData; + PFNGLCLEARPROC Clear; + PFNGLCLEARCOLORPROC ClearColor; + PFNGLCOMPILESHADERPROC CompileShader; + PFNGLCREATEPROGRAMPROC CreateProgram; + PFNGLCREATESHADERPROC CreateShader; + PFNGLDELETEBUFFERSPROC DeleteBuffers; + PFNGLDELETEPROGRAMPROC DeleteProgram; + PFNGLDELETESHADERPROC DeleteShader; + PFNGLDELETETEXTURESPROC DeleteTextures; + PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays; + PFNGLDETACHSHADERPROC DetachShader; + PFNGLDISABLEPROC Disable; + PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray; + PFNGLDRAWELEMENTSPROC DrawElements; + PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex; + PFNGLENABLEPROC Enable; + PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray; + PFNGLFLUSHPROC Flush; + PFNGLGENBUFFERSPROC GenBuffers; + PFNGLGENTEXTURESPROC GenTextures; + PFNGLGENVERTEXARRAYSPROC GenVertexArrays; + PFNGLGETATTRIBLOCATIONPROC GetAttribLocation; + PFNGLGETERRORPROC GetError; + PFNGLGETINTEGERVPROC GetIntegerv; + PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog; + PFNGLGETPROGRAMIVPROC GetProgramiv; + PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog; + PFNGLGETSHADERIVPROC GetShaderiv; + PFNGLGETSTRINGPROC GetString; + PFNGLGETSTRINGIPROC GetStringi; + PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation; + PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv; + PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv; + PFNGLISENABLEDPROC IsEnabled; + PFNGLISPROGRAMPROC IsProgram; + PFNGLLINKPROGRAMPROC LinkProgram; + PFNGLPIXELSTOREIPROC PixelStorei; + PFNGLPOLYGONMODEPROC PolygonMode; + PFNGLREADPIXELSPROC ReadPixels; + PFNGLSCISSORPROC Scissor; + PFNGLSHADERSOURCEPROC ShaderSource; + PFNGLTEXIMAGE2DPROC TexImage2D; + PFNGLTEXPARAMETERIPROC TexParameteri; + PFNGLUNIFORM1IPROC Uniform1i; + PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv; + PFNGLUSEPROGRAMPROC UseProgram; + PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer; + PFNGLVIEWPORTPROC Viewport; } gl; }; -GL3W_API extern union GL3WProcs imgl3wProcs; +GL3W_API extern union ImGL3WProcs imgl3wProcs; /* OpenGL functions */ -#define glActiveTexture imgl3wProcs.gl.ActiveTexture -#define glAttachShader imgl3wProcs.gl.AttachShader -#define glBindBuffer imgl3wProcs.gl.BindBuffer -#define glBindSampler imgl3wProcs.gl.BindSampler -#define glBindTexture imgl3wProcs.gl.BindTexture -#define glBindVertexArray imgl3wProcs.gl.BindVertexArray -#define glBlendEquation imgl3wProcs.gl.BlendEquation -#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate -#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate -#define glBufferData imgl3wProcs.gl.BufferData -#define glBufferSubData imgl3wProcs.gl.BufferSubData -#define glClear imgl3wProcs.gl.Clear -#define glClearColor imgl3wProcs.gl.ClearColor -#define glCompileShader imgl3wProcs.gl.CompileShader -#define glCreateProgram imgl3wProcs.gl.CreateProgram -#define glCreateShader imgl3wProcs.gl.CreateShader -#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers -#define glDeleteProgram imgl3wProcs.gl.DeleteProgram -#define glDeleteShader imgl3wProcs.gl.DeleteShader -#define glDeleteTextures imgl3wProcs.gl.DeleteTextures -#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays -#define glDetachShader imgl3wProcs.gl.DetachShader -#define glDisable imgl3wProcs.gl.Disable -#define glDrawElements imgl3wProcs.gl.DrawElements -#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex -#define glEnable imgl3wProcs.gl.Enable -#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray -#define glGenBuffers imgl3wProcs.gl.GenBuffers -#define glGenTextures imgl3wProcs.gl.GenTextures -#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays -#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation -#define glGetError imgl3wProcs.gl.GetError -#define glGetIntegerv imgl3wProcs.gl.GetIntegerv -#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog -#define glGetProgramiv imgl3wProcs.gl.GetProgramiv -#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog -#define glGetShaderiv imgl3wProcs.gl.GetShaderiv -#define glGetString imgl3wProcs.gl.GetString -#define glGetStringi imgl3wProcs.gl.GetStringi -#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation -#define glIsEnabled imgl3wProcs.gl.IsEnabled -#define glLinkProgram imgl3wProcs.gl.LinkProgram -#define glPixelStorei imgl3wProcs.gl.PixelStorei -#define glPolygonMode imgl3wProcs.gl.PolygonMode -#define glReadPixels imgl3wProcs.gl.ReadPixels -#define glScissor imgl3wProcs.gl.Scissor -#define glShaderSource imgl3wProcs.gl.ShaderSource -#define glTexImage2D imgl3wProcs.gl.TexImage2D -#define glTexParameteri imgl3wProcs.gl.TexParameteri -#define glUniform1i imgl3wProcs.gl.Uniform1i -#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv -#define glUseProgram imgl3wProcs.gl.UseProgram -#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer -#define glViewport imgl3wProcs.gl.Viewport +#define glActiveTexture imgl3wProcs.gl.ActiveTexture +#define glAttachShader imgl3wProcs.gl.AttachShader +#define glBindBuffer imgl3wProcs.gl.BindBuffer +#define glBindSampler imgl3wProcs.gl.BindSampler +#define glBindTexture imgl3wProcs.gl.BindTexture +#define glBindVertexArray imgl3wProcs.gl.BindVertexArray +#define glBlendEquation imgl3wProcs.gl.BlendEquation +#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate +#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate +#define glBufferData imgl3wProcs.gl.BufferData +#define glBufferSubData imgl3wProcs.gl.BufferSubData +#define glClear imgl3wProcs.gl.Clear +#define glClearColor imgl3wProcs.gl.ClearColor +#define glCompileShader imgl3wProcs.gl.CompileShader +#define glCreateProgram imgl3wProcs.gl.CreateProgram +#define glCreateShader imgl3wProcs.gl.CreateShader +#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers +#define glDeleteProgram imgl3wProcs.gl.DeleteProgram +#define glDeleteShader imgl3wProcs.gl.DeleteShader +#define glDeleteTextures imgl3wProcs.gl.DeleteTextures +#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays +#define glDetachShader imgl3wProcs.gl.DetachShader +#define glDisable imgl3wProcs.gl.Disable +#define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray +#define glDrawElements imgl3wProcs.gl.DrawElements +#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex +#define glEnable imgl3wProcs.gl.Enable +#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray +#define glFlush imgl3wProcs.gl.Flush +#define glGenBuffers imgl3wProcs.gl.GenBuffers +#define glGenTextures imgl3wProcs.gl.GenTextures +#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays +#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation +#define glGetError imgl3wProcs.gl.GetError +#define glGetIntegerv imgl3wProcs.gl.GetIntegerv +#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog +#define glGetProgramiv imgl3wProcs.gl.GetProgramiv +#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog +#define glGetShaderiv imgl3wProcs.gl.GetShaderiv +#define glGetString imgl3wProcs.gl.GetString +#define glGetStringi imgl3wProcs.gl.GetStringi +#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation +#define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv +#define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv +#define glIsEnabled imgl3wProcs.gl.IsEnabled +#define glIsProgram imgl3wProcs.gl.IsProgram +#define glLinkProgram imgl3wProcs.gl.LinkProgram +#define glPixelStorei imgl3wProcs.gl.PixelStorei +#define glPolygonMode imgl3wProcs.gl.PolygonMode +#define glReadPixels imgl3wProcs.gl.ReadPixels +#define glScissor imgl3wProcs.gl.Scissor +#define glShaderSource imgl3wProcs.gl.ShaderSource +#define glTexImage2D imgl3wProcs.gl.TexImage2D +#define glTexParameteri imgl3wProcs.gl.TexParameteri +#define glUniform1i imgl3wProcs.gl.Uniform1i +#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv +#define glUseProgram imgl3wProcs.gl.UseProgram +#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer +#define glViewport imgl3wProcs.gl.Viewport #ifdef __cplusplus } @@ -567,7 +610,7 @@ extern "C" { #include -#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #if defined(_WIN32) #ifndef WIN32_LEAN_AND_MEAN @@ -625,7 +668,12 @@ static GL3WglProc (*glx_get_proc_address)(const GLubyte *); static int open_libgl(void) { - libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL); + // While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983 + libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL); + if (!libgl) + libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL); + if (!libgl) + libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL); if (!libgl) return GL3W_ERROR_LIBRARY_OPEN; *(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB"); @@ -652,7 +700,13 @@ static int parse_version(void) return GL3W_ERROR_INIT; glGetIntegerv(GL_MAJOR_VERSION, &version.major); glGetIntegerv(GL_MINOR_VERSION, &version.minor); - if (version.major < 3) + if (version.major == 0 && version.minor == 0) + { + // Query GL_VERSION in desktop GL 2.x, the string will start with "." + if (const char* gl_version = (const char*)glGetString(GL_VERSION)) + sscanf(gl_version, "%d.%d", &version.major, &version.minor); + } + if (version.major < 2) return GL3W_ERROR_OPENGL_VERSION; return GL3W_OK; } @@ -676,7 +730,7 @@ int imgl3wInit2(GL3WGetProcAddressProc proc) int imgl3wIsSupported(int major, int minor) { - if (major < 3) + if (major < 2) return 0; if (version.major == major) return version.minor >= minor; @@ -709,10 +763,12 @@ static const char *proc_names[] = { "glDeleteVertexArrays", "glDetachShader", "glDisable", + "glDisableVertexAttribArray", "glDrawElements", "glDrawElementsBaseVertex", "glEnable", "glEnableVertexAttribArray", + "glFlush", "glGenBuffers", "glGenTextures", "glGenVertexArrays", @@ -726,7 +782,10 @@ static const char *proc_names[] = { "glGetString", "glGetStringi", "glGetUniformLocation", + "glGetVertexAttribPointerv", + "glGetVertexAttribiv", "glIsEnabled", + "glIsProgram", "glLinkProgram", "glPixelStorei", "glPolygonMode", @@ -742,12 +801,12 @@ static const char *proc_names[] = { "glViewport", }; -GL3W_API union GL3WProcs imgl3wProcs; +GL3W_API union ImGL3WProcs imgl3wProcs; static void load_procs(GL3WGetProcAddressProc proc) { size_t i; - for (i = 0; i < ARRAY_SIZE(proc_names); i++) + for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++) imgl3wProcs.ptr[i] = proc(proc_names[i]); } diff --git a/third_party/imgui/backends/imgui_impl_osx.h b/third_party/imgui/backends/imgui_impl_osx.h index 6cfe7eb2e4f..4033ad93e8a 100644 --- a/third_party/imgui/backends/imgui_impl_osx.h +++ b/third_party/imgui/backends/imgui_impl_osx.h @@ -1,19 +1,28 @@ // dear imgui: Platform Backend for OSX / Cocoa // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) -// [ALPHA] Early backend, not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. +// - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. +// - Requires linking with the GameController framework ("-framework GameController"). // Implemented features: // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Mouse support. Can discriminate Mouse/Pen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend). // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [X] Platform: Keyboard arrays indexed using kVK_* codes, e.g. ImGui::IsKeyPressed(kVK_Space). +// [X] Platform: IME support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +#ifdef __OBJC__ @class NSEvent; @class NSView; @@ -21,4 +30,22 @@ IMGUI_IMPL_API bool ImGui_ImplOSX_Init(NSView* _Nonnull view); IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view); -IMGUI_IMPL_API bool ImGui_ImplOSX_HandleEvent(NSEvent* _Nonnull event, NSView* _Nullable view); + +#endif + +//----------------------------------------------------------------------------- +// C++ API +//----------------------------------------------------------------------------- + +#ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS +// #include +#ifndef __OBJC__ + +IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view); +IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view); + +#endif +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_osx.mm b/third_party/imgui/backends/imgui_impl_osx.mm index e1222fa7618..b13d15aef50 100644 --- a/third_party/imgui/backends/imgui_impl_osx.mm +++ b/third_party/imgui/backends/imgui_impl_osx.mm @@ -1,27 +1,50 @@ // dear imgui: Platform Backend for OSX / Cocoa // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) -// [ALPHA] Early backend, not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. +// - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. +// - Requires linking with the GameController framework ("-framework GameController"). // Implemented features: // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Mouse support. Can discriminate Mouse/Pen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend). // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// [X] Platform: Keyboard arrays indexed using kVK_* codes, e.g. ImGui::IsKeyPressed(kVK_Space). +// [X] Platform: IME support. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// 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 #import "imgui.h" +#ifndef IMGUI_DISABLE #import "imgui_impl_osx.h" #import -#import #import #import +#import // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen. +// 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen. +// 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mices). +// 2022-11-02: Fixed mouse coordinates before clicking the host window. +// 2022-10-06: Fixed mouse inputs on flipped views. +// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). +// 2022-05-03: Inputs: Removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. +// 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts. +// 2022-03-22: Inputs: Monitor NSKeyUp events to catch missing keyUp for key when user press Cmd + key +// 2022-02-07: Inputs: Forward keyDown/keyUp events to OS when unused by dear imgui. +// 2022-01-31: Fixed building with old Xcode versions that are missing gamepad features. +// 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-12: Inputs: Added basic Platform IME support, hooking the io.SetPlatformImeDataFn() function. +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2021-12-13: *BREAKING CHANGE* Add NSView parameter to ImGui_ImplOSX_Init(). Generally fix keyboard support. Using kVK_* codes for keyboard keys. // 2021-12-13: Add game controller support. // 2021-09-21: Use mach_absolute_time as CFAbsoluteTimeGetCurrent can jump backwards. @@ -40,18 +63,36 @@ // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. // 2018-07-07: Initial version. -@class ImFocusObserver; +#define APPLE_HAS_BUTTON_OPTIONS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 130000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500 || __TV_OS_VERSION_MIN_REQUIRED >= 130000) +#define APPLE_HAS_CONTROLLER (__IPHONE_OS_VERSION_MIN_REQUIRED >= 140000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 110000 || __TV_OS_VERSION_MIN_REQUIRED >= 140000) +#define APPLE_HAS_THUMBSTICKS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 120100 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101401 || __TV_OS_VERSION_MIN_REQUIRED >= 120100) + +@class ImGuiObserver; @class KeyEventResponder; // Data -static double g_HostClockPeriod = 0.0; -static double g_Time = 0.0; -static NSCursor* g_MouseCursors[ImGuiMouseCursor_COUNT] = {}; -static bool g_MouseCursorHidden = false; -static bool g_MouseJustPressed[ImGuiMouseButton_COUNT] = {}; -static bool g_MouseDown[ImGuiMouseButton_COUNT] = {}; -static ImFocusObserver* g_FocusObserver = nil; -static KeyEventResponder* g_KeyEventResponder = nil; +struct ImGui_ImplOSX_Data +{ + CFTimeInterval Time; + NSCursor* MouseCursors[ImGuiMouseCursor_COUNT]; + bool MouseCursorHidden; + ImGuiObserver* Observer; + KeyEventResponder* KeyEventResponder; + NSTextInputContext* InputContext; + id Monitor; + + ImGui_ImplOSX_Data() { memset(this, 0, sizeof(*this)); } +}; + +static ImGui_ImplOSX_Data* ImGui_ImplOSX_CreateBackendData() { return IM_NEW(ImGui_ImplOSX_Data)(); } +static ImGui_ImplOSX_Data* ImGui_ImplOSX_GetBackendData() { return (ImGui_ImplOSX_Data*)ImGui::GetIO().BackendPlatformUserData; } +static void ImGui_ImplOSX_DestroyBackendData() { IM_DELETE(ImGui_ImplOSX_GetBackendData()); } + +static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); } + +// Forward Declarations +static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view); +static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view); // Undocumented methods for creating cursors. @interface NSCursor() @@ -61,25 +102,6 @@ + (id)_windowResizeNorthSouthCursor; + (id)_windowResizeEastWestCursor; @end -static void InitHostClockPeriod() -{ - struct mach_timebase_info info; - mach_timebase_info(&info); - g_HostClockPeriod = 1e-9 * ((double)info.denom / (double)info.numer); // Period is the reciprocal of frequency. -} - -static double GetMachAbsoluteTimeInSeconds() -{ - return (double)mach_absolute_time() * g_HostClockPeriod; -} - -static void resetKeys() -{ - ImGuiIO& io = ImGui::GetIO(); - memset(io.KeysDown, 0, sizeof(io.KeysDown)); - io.KeyCtrl = io.KeyShift = io.KeyAlt = io.KeySuper = false; -} - /** KeyEventResponder implements the NSTextInputClient protocol as is required by the macOS text input manager. @@ -96,6 +118,29 @@ @interface KeyEventResponder: NSView @end @implementation KeyEventResponder +{ + float _posX; + float _posY; + NSRect _imeRect; +} + +#pragma mark - Public + +- (void)setImePosX:(float)posX imePosY:(float)posY +{ + _posX = posX; + _posY = posY; +} + +- (void)updateImePosWithView:(NSView *)view +{ + NSWindow *window = view.window; + if (!window) + return; + NSRect contentRect = [window contentRectForFrameRect:window.frame]; + NSRect rect = NSMakeRect(_posX, contentRect.size.height - _posY, 0, 0); + _imeRect = [window convertRectToScreen:rect]; +} - (void)viewDidMoveToWindow { @@ -105,10 +150,19 @@ - (void)viewDidMoveToWindow - (void)keyDown:(NSEvent*)event { + if (!ImGui_ImplOSX_HandleEvent(event, self)) + [super keyDown:event]; + // Call to the macOS input manager system. [self interpretKeyEvents:@[event]]; } +- (void)keyUp:(NSEvent*)event +{ + if (!ImGui_ImplOSX_HandleEvent(event, self)) + [super keyUp:event]; +} + - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange { ImGuiIO& io = ImGui::GetIO(); @@ -143,7 +197,7 @@ - (NSUInteger)characterIndexForPoint:(NSPoint)point - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(nullable NSRangePointer)actualRange { - return NSZeroRect; + return _imeRect; } - (BOOL)hasMarkedText @@ -176,14 +230,14 @@ - (void)unmarkText @end -@interface ImFocusObserver : NSObject +@interface ImGuiObserver : NSObject - (void)onApplicationBecomeActive:(NSNotification*)aNotification; - (void)onApplicationBecomeInactive:(NSNotification*)aNotification; @end -@implementation ImFocusObserver +@implementation ImGuiObserver - (void)onApplicationBecomeActive:(NSNotification*)aNotification { @@ -195,62 +249,170 @@ - (void)onApplicationBecomeInactive:(NSNotification*)aNotification { ImGuiIO& io = ImGui::GetIO(); io.AddFocusEvent(false); - - // Unfocused applications do not receive input events, therefore we must manually - // release any pressed keys when application loses focus, otherwise they would remain - // stuck in a pressed state. https://github.com/ocornut/imgui/issues/3832 - resetKeys(); } @end // Functions +static ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code) +{ + switch (key_code) + { + case kVK_ANSI_A: return ImGuiKey_A; + case kVK_ANSI_S: return ImGuiKey_S; + case kVK_ANSI_D: return ImGuiKey_D; + case kVK_ANSI_F: return ImGuiKey_F; + case kVK_ANSI_H: return ImGuiKey_H; + case kVK_ANSI_G: return ImGuiKey_G; + case kVK_ANSI_Z: return ImGuiKey_Z; + case kVK_ANSI_X: return ImGuiKey_X; + case kVK_ANSI_C: return ImGuiKey_C; + case kVK_ANSI_V: return ImGuiKey_V; + case kVK_ANSI_B: return ImGuiKey_B; + case kVK_ANSI_Q: return ImGuiKey_Q; + case kVK_ANSI_W: return ImGuiKey_W; + case kVK_ANSI_E: return ImGuiKey_E; + case kVK_ANSI_R: return ImGuiKey_R; + case kVK_ANSI_Y: return ImGuiKey_Y; + case kVK_ANSI_T: return ImGuiKey_T; + case kVK_ANSI_1: return ImGuiKey_1; + case kVK_ANSI_2: return ImGuiKey_2; + case kVK_ANSI_3: return ImGuiKey_3; + case kVK_ANSI_4: return ImGuiKey_4; + case kVK_ANSI_6: return ImGuiKey_6; + case kVK_ANSI_5: return ImGuiKey_5; + case kVK_ANSI_Equal: return ImGuiKey_Equal; + case kVK_ANSI_9: return ImGuiKey_9; + case kVK_ANSI_7: return ImGuiKey_7; + case kVK_ANSI_Minus: return ImGuiKey_Minus; + case kVK_ANSI_8: return ImGuiKey_8; + case kVK_ANSI_0: return ImGuiKey_0; + case kVK_ANSI_RightBracket: return ImGuiKey_RightBracket; + case kVK_ANSI_O: return ImGuiKey_O; + case kVK_ANSI_U: return ImGuiKey_U; + case kVK_ANSI_LeftBracket: return ImGuiKey_LeftBracket; + case kVK_ANSI_I: return ImGuiKey_I; + case kVK_ANSI_P: return ImGuiKey_P; + case kVK_ANSI_L: return ImGuiKey_L; + case kVK_ANSI_J: return ImGuiKey_J; + case kVK_ANSI_Quote: return ImGuiKey_Apostrophe; + case kVK_ANSI_K: return ImGuiKey_K; + case kVK_ANSI_Semicolon: return ImGuiKey_Semicolon; + case kVK_ANSI_Backslash: return ImGuiKey_Backslash; + case kVK_ANSI_Comma: return ImGuiKey_Comma; + case kVK_ANSI_Slash: return ImGuiKey_Slash; + case kVK_ANSI_N: return ImGuiKey_N; + case kVK_ANSI_M: return ImGuiKey_M; + case kVK_ANSI_Period: return ImGuiKey_Period; + case kVK_ANSI_Grave: return ImGuiKey_GraveAccent; + case kVK_ANSI_KeypadDecimal: return ImGuiKey_KeypadDecimal; + case kVK_ANSI_KeypadMultiply: return ImGuiKey_KeypadMultiply; + case kVK_ANSI_KeypadPlus: return ImGuiKey_KeypadAdd; + case kVK_ANSI_KeypadClear: return ImGuiKey_NumLock; + case kVK_ANSI_KeypadDivide: return ImGuiKey_KeypadDivide; + case kVK_ANSI_KeypadEnter: return ImGuiKey_KeypadEnter; + case kVK_ANSI_KeypadMinus: return ImGuiKey_KeypadSubtract; + case kVK_ANSI_KeypadEquals: return ImGuiKey_KeypadEqual; + case kVK_ANSI_Keypad0: return ImGuiKey_Keypad0; + case kVK_ANSI_Keypad1: return ImGuiKey_Keypad1; + case kVK_ANSI_Keypad2: return ImGuiKey_Keypad2; + case kVK_ANSI_Keypad3: return ImGuiKey_Keypad3; + case kVK_ANSI_Keypad4: return ImGuiKey_Keypad4; + case kVK_ANSI_Keypad5: return ImGuiKey_Keypad5; + case kVK_ANSI_Keypad6: return ImGuiKey_Keypad6; + case kVK_ANSI_Keypad7: return ImGuiKey_Keypad7; + case kVK_ANSI_Keypad8: return ImGuiKey_Keypad8; + case kVK_ANSI_Keypad9: return ImGuiKey_Keypad9; + case kVK_Return: return ImGuiKey_Enter; + case kVK_Tab: return ImGuiKey_Tab; + case kVK_Space: return ImGuiKey_Space; + case kVK_Delete: return ImGuiKey_Backspace; + case kVK_Escape: return ImGuiKey_Escape; + case kVK_CapsLock: return ImGuiKey_CapsLock; + case kVK_Control: return ImGuiKey_LeftCtrl; + case kVK_Shift: return ImGuiKey_LeftShift; + case kVK_Option: return ImGuiKey_LeftAlt; + case kVK_Command: return ImGuiKey_LeftSuper; + case kVK_RightControl: return ImGuiKey_RightCtrl; + case kVK_RightShift: return ImGuiKey_RightShift; + case kVK_RightOption: return ImGuiKey_RightAlt; + case kVK_RightCommand: return ImGuiKey_RightSuper; +// case kVK_Function: return ImGuiKey_; +// case kVK_VolumeUp: return ImGuiKey_; +// case kVK_VolumeDown: return ImGuiKey_; +// case kVK_Mute: return ImGuiKey_; + case kVK_F1: return ImGuiKey_F1; + case kVK_F2: return ImGuiKey_F2; + case kVK_F3: return ImGuiKey_F3; + case kVK_F4: return ImGuiKey_F4; + case kVK_F5: return ImGuiKey_F5; + case kVK_F6: return ImGuiKey_F6; + case kVK_F7: return ImGuiKey_F7; + case kVK_F8: return ImGuiKey_F8; + case kVK_F9: return ImGuiKey_F9; + case kVK_F10: return ImGuiKey_F10; + case kVK_F11: return ImGuiKey_F11; + case kVK_F12: return ImGuiKey_F12; + case kVK_F13: return ImGuiKey_F13; + case kVK_F14: return ImGuiKey_F14; + case kVK_F15: return ImGuiKey_F15; + case kVK_F16: return ImGuiKey_F16; + case kVK_F17: return ImGuiKey_F17; + case kVK_F18: return ImGuiKey_F18; + case kVK_F19: return ImGuiKey_F19; + case kVK_F20: return ImGuiKey_F20; + case 0x6E: return ImGuiKey_Menu; + case kVK_Help: return ImGuiKey_Insert; + case kVK_Home: return ImGuiKey_Home; + case kVK_PageUp: return ImGuiKey_PageUp; + case kVK_ForwardDelete: return ImGuiKey_Delete; + case kVK_End: return ImGuiKey_End; + case kVK_PageDown: return ImGuiKey_PageDown; + case kVK_LeftArrow: return ImGuiKey_LeftArrow; + case kVK_RightArrow: return ImGuiKey_RightArrow; + case kVK_DownArrow: return ImGuiKey_DownArrow; + case kVK_UpArrow: return ImGuiKey_UpArrow; + default: return ImGuiKey_None; + } +} + +#ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS + +IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view) { + return ImGui_ImplOSX_Init((__bridge NSView*)(view)); +} + +IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view) { + return ImGui_ImplOSX_NewFrame((__bridge NSView*)(view)); +} + +#endif + + bool ImGui_ImplOSX_Init(NSView* view) { ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_CreateBackendData(); + io.BackendPlatformUserData = (void*)bd; // Setup backend capabilities flags 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 set io.MouseHoveredViewport correctly (optional, not easy) io.BackendPlatformName = "imgui_impl_osx"; - // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeyDown[] array. - io.KeyMap[ImGuiKey_Tab] = kVK_Tab; - io.KeyMap[ImGuiKey_LeftArrow] = kVK_LeftArrow; - io.KeyMap[ImGuiKey_RightArrow] = kVK_RightArrow; - io.KeyMap[ImGuiKey_UpArrow] = kVK_UpArrow; - io.KeyMap[ImGuiKey_DownArrow] = kVK_DownArrow; - io.KeyMap[ImGuiKey_PageUp] = kVK_PageUp; - io.KeyMap[ImGuiKey_PageDown] = kVK_PageDown; - io.KeyMap[ImGuiKey_Home] = kVK_Home; - io.KeyMap[ImGuiKey_End] = kVK_End; - io.KeyMap[ImGuiKey_Insert] = kVK_F13; - io.KeyMap[ImGuiKey_Delete] = kVK_ForwardDelete; - io.KeyMap[ImGuiKey_Backspace] = kVK_Delete; - io.KeyMap[ImGuiKey_Space] = kVK_Space; - io.KeyMap[ImGuiKey_Enter] = kVK_Return; - io.KeyMap[ImGuiKey_Escape] = kVK_Escape; - io.KeyMap[ImGuiKey_KeyPadEnter] = kVK_ANSI_KeypadEnter; - io.KeyMap[ImGuiKey_A] = kVK_ANSI_A; - io.KeyMap[ImGuiKey_C] = kVK_ANSI_C; - io.KeyMap[ImGuiKey_V] = kVK_ANSI_V; - io.KeyMap[ImGuiKey_X] = kVK_ANSI_X; - io.KeyMap[ImGuiKey_Y] = kVK_ANSI_Y; - io.KeyMap[ImGuiKey_Z] = kVK_ANSI_Z; + bd->Observer = [ImGuiObserver new]; // Load cursors. Some of them are undocumented. - g_MouseCursorHidden = false; - g_MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor]; - g_MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor]; - g_MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor]; - g_MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor]; - g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor]; + bd->MouseCursorHidden = false; + bd->MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor]; + bd->MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor]; + bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor]; + bd->MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor]; + bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor]; + bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor]; + bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor]; + bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor]; + bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor]; // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled // by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line. @@ -267,11 +429,11 @@ bool ImGui_ImplOSX_Init(NSView* view) NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]]; if (![available isEqualToString:NSPasteboardTypeString]) - return NULL; + return nullptr; NSString* string = [pasteboard stringForType:NSPasteboardTypeString]; if (string == nil) - return NULL; + return nullptr; const char* string_c = (const char*)[string UTF8String]; size_t string_len = strlen(string_c); @@ -281,40 +443,65 @@ bool ImGui_ImplOSX_Init(NSView* view) return s_clipboard.Data; }; - g_FocusObserver = [[ImFocusObserver alloc] init]; - [[NSNotificationCenter defaultCenter] addObserver:g_FocusObserver + [[NSNotificationCenter defaultCenter] addObserver:bd->Observer selector:@selector(onApplicationBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:g_FocusObserver + [[NSNotificationCenter defaultCenter] addObserver:bd->Observer selector:@selector(onApplicationBecomeInactive:) name:NSApplicationDidResignActiveNotification object:nil]; // Add the NSTextInputClient to the view hierarchy, // to receive keyboard events and translate them to input text. - g_KeyEventResponder = [[KeyEventResponder alloc] initWithFrame:NSZeroRect]; - [view addSubview:g_KeyEventResponder]; + bd->KeyEventResponder = [[KeyEventResponder alloc] initWithFrame:NSZeroRect]; + bd->InputContext = [[NSTextInputContext alloc] initWithClient:bd->KeyEventResponder]; + [view addSubview:bd->KeyEventResponder]; + ImGui_ImplOSX_AddTrackingArea(view); + + io.SetPlatformImeDataFn = [](ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void + { + ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); + if (data->WantVisible) + { + [bd->InputContext activate]; + } + else + { + [bd->InputContext discardMarkedText]; + [bd->InputContext invalidateCharacterCoordinates]; + [bd->InputContext deactivate]; + } + [bd->KeyEventResponder setImePosX:data->InputPos.x imePosY:data->InputPos.y + data->InputLineHeight]; + }; return true; } void ImGui_ImplOSX_Shutdown() { - g_FocusObserver = NULL; -} + ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); -static void ImGui_ImplOSX_UpdateMouseCursorAndButtons() -{ - // Update buttons - ImGuiIO& io = ImGui::GetIO(); - for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) + bd->Observer = nullptr; + if (bd->Monitor != nullptr) { - // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. - io.MouseDown[i] = g_MouseJustPressed[i] || g_MouseDown[i]; - g_MouseJustPressed[i] = false; + [NSEvent removeMonitor:bd->Monitor]; + bd->Monitor = nullptr; } + ImGui_ImplOSX_DestroyBackendData(); + + ImGuiIO& io = ImGui::GetIO(); + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasGamepad); +} + +static void ImGui_ImplOSX_UpdateMouseCursor() +{ + ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); + ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return; @@ -322,41 +509,39 @@ static void ImGui_ImplOSX_UpdateMouseCursorAndButtons() if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor - if (!g_MouseCursorHidden) + if (!bd->MouseCursorHidden) { - g_MouseCursorHidden = true; + bd->MouseCursorHidden = true; [NSCursor hide]; } } else { - NSCursor* desired = g_MouseCursors[imgui_cursor] ?: g_MouseCursors[ImGuiMouseCursor_Arrow]; + NSCursor* desired = bd->MouseCursors[imgui_cursor] ?: bd->MouseCursors[ImGuiMouseCursor_Arrow]; // -[NSCursor set] generates measureable overhead if called unconditionally. if (desired != NSCursor.currentCursor) { [desired set]; } - if (g_MouseCursorHidden) + if (bd->MouseCursorHidden) { - g_MouseCursorHidden = false; + bd->MouseCursorHidden = false; [NSCursor unhide]; } } } -void ImGui_ImplOSX_UpdateGamepads() +static void ImGui_ImplOSX_UpdateGamepads() { ImGuiIO& io = ImGui::GetIO(); - memset(io.NavInputs, 0, sizeof(io.NavInputs)); - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. return; - GCController* controller; - if (@available(macOS 11.0, *)) - controller = GCController.current; - else - controller = GCController.controllers.firstObject; - +#if APPLE_HAS_CONTROLLER + GCController* controller = GCController.current; +#else + GCController* controller = GCController.controllers.firstObject; +#endif if (controller == nil || controller.extendedGamepad == nil) { io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; @@ -365,33 +550,59 @@ void ImGui_ImplOSX_UpdateGamepads() GCExtendedGamepad* gp = controller.extendedGamepad; -#define MAP_BUTTON(NAV_NO, NAME) { io.NavInputs[NAV_NO] = gp.NAME.isPressed ? 1.0 : 0.0; } - MAP_BUTTON(ImGuiNavInput_Activate, buttonA); - MAP_BUTTON(ImGuiNavInput_Cancel, buttonB); - MAP_BUTTON(ImGuiNavInput_Menu, buttonX); - MAP_BUTTON(ImGuiNavInput_Input, buttonY); - MAP_BUTTON(ImGuiNavInput_DpadLeft, dpad.left); - MAP_BUTTON(ImGuiNavInput_DpadRight, dpad.right); - MAP_BUTTON(ImGuiNavInput_DpadUp, dpad.up); - MAP_BUTTON(ImGuiNavInput_DpadDown, dpad.down); - MAP_BUTTON(ImGuiNavInput_FocusPrev, leftShoulder); - MAP_BUTTON(ImGuiNavInput_FocusNext, rightShoulder); - MAP_BUTTON(ImGuiNavInput_TweakSlow, leftTrigger); - MAP_BUTTON(ImGuiNavInput_TweakFast, rightTrigger); -#undef MAP_BUTTON - - io.NavInputs[ImGuiNavInput_LStickLeft] = gp.leftThumbstick.left.value; - io.NavInputs[ImGuiNavInput_LStickRight] = gp.leftThumbstick.right.value; - io.NavInputs[ImGuiNavInput_LStickUp] = gp.leftThumbstick.up.value; - io.NavInputs[ImGuiNavInput_LStickDown] = gp.leftThumbstick.down.value; + // Update gamepad inputs + #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) + #define MAP_BUTTON(KEY_NO, BUTTON_NAME) { io.AddKeyEvent(KEY_NO, gp.BUTTON_NAME.isPressed); } + #define MAP_ANALOG(KEY_NO, AXIS_NAME, V0, V1) { float vn = (float)(gp.AXIS_NAME.value - V0) / (float)(V1 - V0); vn = IM_SATURATE(vn); io.AddKeyAnalogEvent(KEY_NO, vn > 0.1f, vn); } + const float thumb_dead_zone = 0.0f; + +#if APPLE_HAS_BUTTON_OPTIONS + MAP_BUTTON(ImGuiKey_GamepadBack, buttonOptions); +#endif + MAP_BUTTON(ImGuiKey_GamepadFaceLeft, buttonX); // Xbox X, PS Square + MAP_BUTTON(ImGuiKey_GamepadFaceRight, buttonB); // Xbox B, PS Circle + MAP_BUTTON(ImGuiKey_GamepadFaceUp, buttonY); // Xbox Y, PS Triangle + MAP_BUTTON(ImGuiKey_GamepadFaceDown, buttonA); // Xbox A, PS Cross + MAP_BUTTON(ImGuiKey_GamepadDpadLeft, dpad.left); + MAP_BUTTON(ImGuiKey_GamepadDpadRight, dpad.right); + MAP_BUTTON(ImGuiKey_GamepadDpadUp, dpad.up); + MAP_BUTTON(ImGuiKey_GamepadDpadDown, dpad.down); + MAP_ANALOG(ImGuiKey_GamepadL1, leftShoulder, 0.0f, 1.0f); + MAP_ANALOG(ImGuiKey_GamepadR1, rightShoulder, 0.0f, 1.0f); + MAP_ANALOG(ImGuiKey_GamepadL2, leftTrigger, 0.0f, 1.0f); + MAP_ANALOG(ImGuiKey_GamepadR2, rightTrigger, 0.0f, 1.0f); +#if APPLE_HAS_THUMBSTICKS + MAP_BUTTON(ImGuiKey_GamepadL3, leftThumbstickButton); + MAP_BUTTON(ImGuiKey_GamepadR3, rightThumbstickButton); +#endif + MAP_ANALOG(ImGuiKey_GamepadLStickLeft, leftThumbstick.xAxis, -thumb_dead_zone, -1.0f); + MAP_ANALOG(ImGuiKey_GamepadLStickRight, leftThumbstick.xAxis, +thumb_dead_zone, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadLStickUp, leftThumbstick.yAxis, +thumb_dead_zone, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadLStickDown, leftThumbstick.yAxis, -thumb_dead_zone, -1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickLeft, rightThumbstick.xAxis, -thumb_dead_zone, -1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickRight, rightThumbstick.xAxis, +thumb_dead_zone, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickUp, rightThumbstick.yAxis, +thumb_dead_zone, +1.0f); + MAP_ANALOG(ImGuiKey_GamepadRStickDown, rightThumbstick.yAxis, -thumb_dead_zone, -1.0f); + #undef MAP_BUTTON + #undef MAP_ANALOG io.BackendFlags |= ImGuiBackendFlags_HasGamepad; } +static void ImGui_ImplOSX_UpdateImePosWithView(NSView* view) +{ + ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); + ImGuiIO& io = ImGui::GetIO(); + if (io.WantTextInput) + [bd->KeyEventResponder updateImePosWithView:view]; +} + void ImGui_ImplOSX_NewFrame(NSView* view) { - // Setup display size + ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); + + // Setup display size if (view) { const float dpi = (float)[view.window backingScaleFactor]; @@ -400,63 +611,77 @@ void ImGui_ImplOSX_NewFrame(NSView* view) } // Setup time step - if (g_Time == 0.0) - { - InitHostClockPeriod(); - g_Time = GetMachAbsoluteTimeInSeconds(); - } + if (bd->Time == 0.0) + bd->Time = GetMachAbsoluteTimeInSeconds(); + double current_time = GetMachAbsoluteTimeInSeconds(); - io.DeltaTime = (float)(current_time - g_Time); - g_Time = current_time; + io.DeltaTime = (float)(current_time - bd->Time); + bd->Time = current_time; - ImGui_ImplOSX_UpdateMouseCursorAndButtons(); + ImGui_ImplOSX_UpdateMouseCursor(); ImGui_ImplOSX_UpdateGamepads(); + ImGui_ImplOSX_UpdateImePosWithView(view); } -NSString* NSStringFromPhase(NSEventPhase phase) +// Must only be called for a mouse event, otherwise an exception occurs +// (Note that NSEventTypeScrollWheel is considered "other input". Oddly enough an exception does not occur with it, but the value will sometimes be wrong!) +static ImGuiMouseSource GetMouseSource(NSEvent* event) { - static NSString* strings[] = + switch (event.subtype) { - @"none", - @"began", - @"stationary", - @"changed", - @"ended", - @"cancelled", - @"mayBegin", - }; - - int pos = phase == NSEventPhaseNone ? 0 : __builtin_ctzl((NSUInteger)phase) + 1; - - return strings[pos]; + case NSEventSubtypeTabletPoint: + return ImGuiMouseSource_Pen; + // macOS considers input from relative touch devices (like the trackpad or Apple Magic Mouse) to be touch input. + // This doesn't really make sense for Dear ImGui, which expects absolute touch devices only. + // There does not seem to be a simple way to disambiguate things here so we consider NSEventSubtypeTouch events to always come from mice. + // See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html#//apple_ref/doc/uid/10000060i-CH13-SW24 + //case NSEventSubtypeTouch: + // return ImGuiMouseSource_TouchScreen; + case NSEventSubtypeMouseEvent: + default: + return ImGuiMouseSource_Mouse; + } } -bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) +static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) { ImGuiIO& io = ImGui::GetIO(); if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown)) - g_MouseDown[button] = g_MouseJustPressed[button] = true; + if (button >= 0 && button < ImGuiMouseButton_COUNT) + { + io.AddMouseSourceEvent(GetMouseSource(event)); + io.AddMouseButtonEvent(button, true); + } return io.WantCaptureMouse; } if (event.type == NSEventTypeLeftMouseUp || event.type == NSEventTypeRightMouseUp || event.type == NSEventTypeOtherMouseUp) { int button = (int)[event buttonNumber]; - if (button >= 0 && button < IM_ARRAYSIZE(g_MouseDown)) - g_MouseDown[button] = false; + if (button >= 0 && button < ImGuiMouseButton_COUNT) + { + io.AddMouseSourceEvent(GetMouseSource(event)); + io.AddMouseButtonEvent(button, false); + } return io.WantCaptureMouse; } if (event.type == NSEventTypeMouseMoved || event.type == NSEventTypeLeftMouseDragged || event.type == NSEventTypeRightMouseDragged || event.type == NSEventTypeOtherMouseDragged) { NSPoint mousePoint = event.locationInWindow; + if (event.window == nil) + mousePoint = [[view window] convertPointFromScreen:mousePoint]; mousePoint = [view convertPoint:mousePoint fromView:nil]; - mousePoint = NSMakePoint(mousePoint.x, view.bounds.size.height - mousePoint.y); - io.MousePos = ImVec2((float)mousePoint.x, (float)mousePoint.y); + if ([view isFlipped]) + mousePoint = NSMakePoint(mousePoint.x, mousePoint.y); + else + mousePoint = NSMakePoint(mousePoint.x, view.bounds.size.height - mousePoint.y); + io.AddMouseSourceEvent(GetMouseSource(event)); + io.AddMousePosEvent((float)mousePoint.x, (float)mousePoint.y); + return io.WantCaptureMouse; } if (event.type == NSEventTypeScrollWheel) @@ -486,59 +711,101 @@ bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view) wheel_dy = [event scrollingDeltaY]; if ([event hasPreciseScrollingDeltas]) { - wheel_dx *= 0.1; - wheel_dy *= 0.1; + wheel_dx *= 0.01; + wheel_dy *= 0.01; } } else #endif // MAC_OS_X_VERSION_MAX_ALLOWED { - wheel_dx = [event deltaX]; - wheel_dy = [event deltaY]; + wheel_dx = [event deltaX] * 0.1; + wheel_dy = [event deltaY] * 0.1; } + if (wheel_dx != 0.0 || wheel_dy != 0.0) + io.AddMouseWheelEvent((float)wheel_dx, (float)wheel_dy); - //NSLog(@"dx=%0.3ff, dy=%0.3f, phase=%@", wheel_dx, wheel_dy, NSStringFromPhase(event.phase)); - - if (fabs(wheel_dx) > 0.0) - io.MouseWheelH += (float)wheel_dx * 0.1f; - if (fabs(wheel_dy) > 0.0) - io.MouseWheel += (float)wheel_dy * 0.1f; return io.WantCaptureMouse; } if (event.type == NSEventTypeKeyDown || event.type == NSEventTypeKeyUp) { - unsigned short code = event.keyCode; - IM_ASSERT(code >= 0 && code < IM_ARRAYSIZE(io.KeysDown)); - io.KeysDown[code] = event.type == NSEventTypeKeyDown; - NSEventModifierFlags flags = event.modifierFlags; - io.KeyCtrl = (flags & NSEventModifierFlagControl) != 0; - io.KeyShift = (flags & NSEventModifierFlagShift) != 0; - io.KeyAlt = (flags & NSEventModifierFlagOption) != 0; - io.KeySuper = (flags & NSEventModifierFlagCommand) != 0; + if ([event isARepeat]) + return io.WantCaptureKeyboard; + + int key_code = (int)[event keyCode]; + ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code); + io.AddKeyEvent(key, event.type == NSEventTypeKeyDown); + io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code) + return io.WantCaptureKeyboard; } if (event.type == NSEventTypeFlagsChanged) { - NSEventModifierFlags flags = event.modifierFlags; - switch (event.keyCode) + unsigned short key_code = [event keyCode]; + NSEventModifierFlags modifier_flags = [event modifierFlags]; + + io.AddKeyEvent(ImGuiMod_Shift, (modifier_flags & NSEventModifierFlagShift) != 0); + io.AddKeyEvent(ImGuiMod_Ctrl, (modifier_flags & NSEventModifierFlagControl) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (modifier_flags & NSEventModifierFlagOption) != 0); + io.AddKeyEvent(ImGuiMod_Super, (modifier_flags & NSEventModifierFlagCommand) != 0); + + ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code); + if (key != ImGuiKey_None) { - case kVK_Control: - io.KeyCtrl = (flags & NSEventModifierFlagControl) != 0; - break; - case kVK_Shift: - io.KeyShift = (flags & NSEventModifierFlagShift) != 0; - break; - case kVK_Option: - io.KeyAlt = (flags & NSEventModifierFlagOption) != 0; - break; - case kVK_Command: - io.KeySuper = (flags & NSEventModifierFlagCommand) != 0; - break; + // macOS does not generate down/up event for modifiers. We're trying + // to use hardware dependent masks to extract that information. + // 'imgui_mask' is left as a fallback. + NSEventModifierFlags mask = 0; + switch (key) + { + case ImGuiKey_LeftCtrl: mask = 0x0001; break; + case ImGuiKey_RightCtrl: mask = 0x2000; break; + case ImGuiKey_LeftShift: mask = 0x0002; break; + case ImGuiKey_RightShift: mask = 0x0004; break; + case ImGuiKey_LeftSuper: mask = 0x0008; break; + case ImGuiKey_RightSuper: mask = 0x0010; break; + case ImGuiKey_LeftAlt: mask = 0x0020; break; + case ImGuiKey_RightAlt: mask = 0x0040; break; + default: + return io.WantCaptureKeyboard; + } + + NSEventModifierFlags modifier_flags = [event modifierFlags]; + io.AddKeyEvent(key, (modifier_flags & mask) != 0); + io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code) } + return io.WantCaptureKeyboard; } return false; } + +static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view) +{ + // If we want to receive key events, we either need to be in the responder chain of the key view, + // or else we can install a local monitor. The consequence of this heavy-handed approach is that + // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our + // window, we'd want to be much more careful than just ingesting the complete event stream. + // To match the behavior of other backends, we pass every event down to the OS. + ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); + if (bd->Monitor) + return; + NSEventMask eventMask = 0; + eventMask |= NSEventMaskMouseMoved | NSEventMaskScrollWheel; + eventMask |= NSEventMaskLeftMouseDown | NSEventMaskLeftMouseUp | NSEventMaskLeftMouseDragged; + eventMask |= NSEventMaskRightMouseDown | NSEventMaskRightMouseUp | NSEventMaskRightMouseDragged; + eventMask |= NSEventMaskOtherMouseDown | NSEventMaskOtherMouseUp | NSEventMaskOtherMouseDragged; + eventMask |= NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged; + bd->Monitor = [NSEvent addLocalMonitorForEventsMatchingMask:eventMask + handler:^NSEvent* _Nullable(NSEvent* event) + { + ImGui_ImplOSX_HandleEvent(event, view); + return event; + }]; +} + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdl.cpp b/third_party/imgui/backends/imgui_impl_sdl.cpp deleted file mode 100644 index b725e0ac2ec..00000000000 --- a/third_party/imgui/backends/imgui_impl_sdl.cpp +++ /dev/null @@ -1,449 +0,0 @@ -// dear imgui: Platform Backend for SDL2 -// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) -// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) -// (Prefer SDL 2.0.5+ for full feature support.) - -// Implemented features: -// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// [X] Platform: Clipboard support. -// [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE). -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// Missing features: -// [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME. - -// 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. -// 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) -// 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST. -// 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+) -// 2021-06-29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary. -// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). -// 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950) -// 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends. -// 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2). -// 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state). -// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. -// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. -// 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application). -// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. -// 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls. -// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. -// 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'. -// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls. -// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. -// 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples. -// 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter. -// 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText). -// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. -// 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value. -// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. -// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. -// 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS). -// 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes. -// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. -// 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS. -// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert. -// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). -// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. - -#include "imgui.h" -#include "imgui_impl_sdl.h" - -// SDL -#include -#include -#if defined(__APPLE__) -#include -#endif - -#if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) -#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 -#else -#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 -#endif -#define SDL_HAS_MOUSE_FOCUS_CLICKTHROUGH SDL_VERSION_ATLEAST(2,0,5) -#define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) - -// SDL Data -struct ImGui_ImplSDL2_Data -{ - SDL_Window* Window; - Uint64 Time; - bool MousePressed[3]; - SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; - char* ClipboardTextData; - bool MouseCanUseGlobalState; - - ImGui_ImplSDL2_Data() { memset(this, 0, sizeof(*this)); } -}; - -// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts -// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. -// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. -// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. -static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData() -{ - return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : NULL; -} - -// Functions -static const char* ImGui_ImplSDL2_GetClipboardText(void*) -{ - ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); - if (bd->ClipboardTextData) - SDL_free(bd->ClipboardTextData); - bd->ClipboardTextData = SDL_GetClipboardText(); - return bd->ClipboardTextData; -} - -static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text) -{ - SDL_SetClipboardText(text); -} - -// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. -// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. -// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. -// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. -// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. -bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) -{ - ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); - - switch (event->type) - { - case SDL_MOUSEWHEEL: - { - if (event->wheel.x > 0) io.MouseWheelH += 1; - if (event->wheel.x < 0) io.MouseWheelH -= 1; - if (event->wheel.y > 0) io.MouseWheel += 1; - if (event->wheel.y < 0) io.MouseWheel -= 1; - return true; - } - case SDL_MOUSEBUTTONDOWN: - { - if (event->button.button == SDL_BUTTON_LEFT) { bd->MousePressed[0] = true; } - if (event->button.button == SDL_BUTTON_RIGHT) { bd->MousePressed[1] = true; } - if (event->button.button == SDL_BUTTON_MIDDLE) { bd->MousePressed[2] = true; } - return true; - } - case SDL_TEXTINPUT: - { - io.AddInputCharactersUTF8(event->text.text); - return true; - } - case SDL_KEYDOWN: - case SDL_KEYUP: - { - int key = event->key.keysym.scancode; - IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown)); - io.KeysDown[key] = (event->type == SDL_KEYDOWN); - io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); - io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); - io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); -#ifdef _WIN32 - io.KeySuper = false; -#else - io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0); -#endif - return true; - } - case SDL_WINDOWEVENT: - { - if (event->window.event == SDL_WINDOWEVENT_FOCUS_GAINED) - io.AddFocusEvent(true); - else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST) - io.AddFocusEvent(false); - return true; - } - } - return false; -} - -static bool ImGui_ImplSDL2_Init(SDL_Window* window) -{ - ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!"); - - // Check and store if we are on a SDL backend that supports global mouse position - // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) - bool mouse_can_use_global_state = false; -#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE - const char* sdl_backend = SDL_GetCurrentVideoDriver(); - const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; - for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) - if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) - mouse_can_use_global_state = true; -#endif - - // Setup backend capabilities flags - ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)(); - io.BackendPlatformUserData = (void*)bd; - io.BackendPlatformName = "imgui_impl_sdl"; - io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) - io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) - - bd->Window = window; - bd->MouseCanUseGlobalState = mouse_can_use_global_state; - - // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array. - io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB; - io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; - io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; - io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; - io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; - io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; - io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; - io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; - io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; - io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT; - io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE; - io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; - io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE; - io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; - io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE; - io.KeyMap[ImGuiKey_KeyPadEnter] = SDL_SCANCODE_KP_ENTER; - io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A; - io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C; - io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V; - io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X; - io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y; - io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z; - - io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; - io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; - io.ClipboardUserData = NULL; - - // Load mouse cursors - bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); - bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); - bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL); - bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS); - bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE); - bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); - bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); - bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); - bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO); - -#ifdef _WIN32 - SDL_SysWMinfo info; - SDL_VERSION(&info.version); - if (SDL_GetWindowWMInfo(window, &info)) - io.ImeWindowHandle = info.info.win.window; -#else - (void)window; -#endif - - // Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. - // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. - // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. - // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: - // you can ignore SDL_MOUSEBUTTONDOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED) -#if SDL_HAS_MOUSE_FOCUS_CLICKTHROUGH - SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); -#endif - - return true; -} - -bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) -{ - IM_UNUSED(sdl_gl_context); // Viewport branch will need this. - return ImGui_ImplSDL2_Init(window); -} - -bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) -{ -#if !SDL_HAS_VULKAN - IM_ASSERT(0 && "Unsupported"); -#endif - return ImGui_ImplSDL2_Init(window); -} - -bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) -{ -#if !defined(_WIN32) - IM_ASSERT(0 && "Unsupported"); -#endif - return ImGui_ImplSDL2_Init(window); -} - -bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window) -{ - return ImGui_ImplSDL2_Init(window); -} - -bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window) -{ - return ImGui_ImplSDL2_Init(window); -} - -void ImGui_ImplSDL2_Shutdown() -{ - ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); - IM_ASSERT(bd != NULL && "No platform backend to shutdown, or already shutdown?"); - ImGuiIO& io = ImGui::GetIO(); - - if (bd->ClipboardTextData) - SDL_free(bd->ClipboardTextData); - for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) - SDL_FreeCursor(bd->MouseCursors[cursor_n]); - - io.BackendPlatformName = NULL; - io.BackendPlatformUserData = NULL; - IM_DELETE(bd); -} - -static void ImGui_ImplSDL2_UpdateMousePosAndButtons() -{ - ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); - ImGuiIO& io = ImGui::GetIO(); - - ImVec2 mouse_pos_prev = io.MousePos; - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - - // Update mouse buttons - int mouse_x_local, mouse_y_local; - Uint32 mouse_buttons = SDL_GetMouseState(&mouse_x_local, &mouse_y_local); - io.MouseDown[0] = bd->MousePressed[0] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. - io.MouseDown[1] = bd->MousePressed[1] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; - io.MouseDown[2] = bd->MousePressed[2] || (mouse_buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; - bd->MousePressed[0] = bd->MousePressed[1] = bd->MousePressed[2] = false; - - // Obtain focused and hovered window. We forward mouse input when focused or when hovered (and no other window is capturing) -#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE - SDL_Window* focused_window = SDL_GetKeyboardFocus(); - SDL_Window* hovered_window = SDL_HAS_MOUSE_FOCUS_CLICKTHROUGH ? SDL_GetMouseFocus() : NULL; // This is better but is only reliably useful with SDL 2.0.5+ and SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH. - SDL_Window* mouse_window = NULL; - if (hovered_window && bd->Window == hovered_window) - mouse_window = hovered_window; - else if (focused_window && bd->Window == focused_window) - mouse_window = focused_window; - - // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside - SDL_CaptureMouse(ImGui::IsAnyMouseDown() ? SDL_TRUE : SDL_FALSE); -#else - // SDL 2.0.3 and non-windowed systems: single-viewport only - SDL_Window* mouse_window = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) ? bd->Window : NULL; -#endif - - if (mouse_window == NULL) - return; - - // Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) - if (io.WantSetMousePos) - SDL_WarpMouseInWindow(bd->Window, (int)mouse_pos_prev.x, (int)mouse_pos_prev.y); - - // Set Dear ImGui mouse position from OS position + get buttons. (this is the common behavior) - if (bd->MouseCanUseGlobalState) - { - // 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) - // Unlike local position obtained earlier this will be valid when straying out of bounds. - int mouse_x_global, mouse_y_global; - SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); - int window_x, window_y; - SDL_GetWindowPosition(mouse_window, &window_x, &window_y); - io.MousePos = ImVec2((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y)); - } - else - { - io.MousePos = ImVec2((float)mouse_x_local, (float)mouse_y_local); - } -} - -static void ImGui_ImplSDL2_UpdateMouseCursor() -{ - ImGuiIO& io = ImGui::GetIO(); - if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) - return; - ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); - - ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); - if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) - { - // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor - SDL_ShowCursor(SDL_FALSE); - } - else - { - // Show OS mouse cursor - SDL_SetCursor(bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]); - SDL_ShowCursor(SDL_TRUE); - } -} - -static void ImGui_ImplSDL2_UpdateGamepads() -{ - ImGuiIO& io = ImGui::GetIO(); - memset(io.NavInputs, 0, sizeof(io.NavInputs)); - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) - return; - - // Get gamepad - SDL_GameController* game_controller = SDL_GameControllerOpen(0); - if (!game_controller) - { - io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; - return; - } - - // Update gamepad inputs - #define MAP_BUTTON(NAV_NO, BUTTON_NO) { io.NavInputs[NAV_NO] = (SDL_GameControllerGetButton(game_controller, BUTTON_NO) != 0) ? 1.0f : 0.0f; } - #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; } - const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value. - MAP_BUTTON(ImGuiNavInput_Activate, SDL_CONTROLLER_BUTTON_A); // Cross / A - MAP_BUTTON(ImGuiNavInput_Cancel, SDL_CONTROLLER_BUTTON_B); // Circle / B - MAP_BUTTON(ImGuiNavInput_Menu, SDL_CONTROLLER_BUTTON_X); // Square / X - MAP_BUTTON(ImGuiNavInput_Input, SDL_CONTROLLER_BUTTON_Y); // Triangle / Y - MAP_BUTTON(ImGuiNavInput_DpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); // D-Pad Left - MAP_BUTTON(ImGuiNavInput_DpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); // D-Pad Right - MAP_BUTTON(ImGuiNavInput_DpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); // D-Pad Up - MAP_BUTTON(ImGuiNavInput_DpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); // D-Pad Down - MAP_BUTTON(ImGuiNavInput_FocusPrev, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB - MAP_BUTTON(ImGuiNavInput_FocusNext, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB - MAP_BUTTON(ImGuiNavInput_TweakSlow, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); // L1 / LB - MAP_BUTTON(ImGuiNavInput_TweakFast, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); // R1 / RB - MAP_ANALOG(ImGuiNavInput_LStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768); - MAP_ANALOG(ImGuiNavInput_LStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767); - MAP_ANALOG(ImGuiNavInput_LStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32767); - MAP_ANALOG(ImGuiNavInput_LStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767); - - io.BackendFlags |= ImGuiBackendFlags_HasGamepad; - #undef MAP_BUTTON - #undef MAP_ANALOG -} - -void ImGui_ImplSDL2_NewFrame() -{ - ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplSDL2_Init()?"); - ImGuiIO& io = ImGui::GetIO(); - - // Setup display size (every frame to accommodate for window resizing) - int w, h; - int display_w, display_h; - SDL_GetWindowSize(bd->Window, &w, &h); - if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) - w = h = 0; - SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h); - io.DisplaySize = ImVec2((float)w, (float)h); - if (w > 0 && h > 0) - io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); - - // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) - static Uint64 frequency = SDL_GetPerformanceFrequency(); - Uint64 current_time = SDL_GetPerformanceCounter(); - io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); - bd->Time = current_time; - - ImGui_ImplSDL2_UpdateMousePosAndButtons(); - ImGui_ImplSDL2_UpdateMouseCursor(); - - // Update game controllers (if enabled and available) - ImGui_ImplSDL2_UpdateGamepads(); -} diff --git a/third_party/imgui/backends/imgui_impl_sdl.h b/third_party/imgui/backends/imgui_impl_sdl.h deleted file mode 100644 index d2439eb7b25..00000000000 --- a/third_party/imgui/backends/imgui_impl_sdl.h +++ /dev/null @@ -1,35 +0,0 @@ -// dear imgui: Platform Backend for SDL2 -// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) -// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) - -// Implemented features: -// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// [X] Platform: Clipboard support. -// [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE). -// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. -// Missing features: -// [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME. - -// 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. -// 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 - -struct SDL_Window; -typedef union SDL_Event SDL_Event; - -IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); -IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window); -IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); -IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window); -IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window); -IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(); -IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); - -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -static inline void ImGui_ImplSDL2_NewFrame(SDL_Window*) { ImGui_ImplSDL2_NewFrame(); } // 1.84: removed unnecessary parameter -#endif diff --git a/third_party/imgui/backends/imgui_impl_sdl2.cpp b/third_party/imgui/backends/imgui_impl_sdl2.cpp new file mode 100644 index 00000000000..7abeb0e89fb --- /dev/null +++ b/third_party/imgui/backends/imgui_impl_sdl2.cpp @@ -0,0 +1,753 @@ +// dear imgui: Platform Backend for SDL2 +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) +// (Prefer SDL 2.0.5+ for full feature support.) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode(). +// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. +// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) +// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) +// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) +// 2023-02-07: Implement IME handler (io.SetPlatformImeDataFn will call SDL_SetTextInputRect()/SDL_StartTextInput()). +// 2023-02-07: *BREAKING CHANGE* Renamed this backend file from imgui_impl_sdl.cpp/.h to imgui_impl_sdl2.cpp/.h in prevision for the future release of SDL3. +// 2023-02-02: Avoid calling SDL_SetCursor() when cursor has not changed, as the function is surprisingly costly on Mac with latest SDL (may be fixed in next SDL version). +// 2023-02-02: Added support for SDL 2.0.18+ preciseX/preciseY mouse wheel data for smooth scrolling + Scaling X value on Emscripten (bug?). (#4019, #6096) +// 2023-02-02: Removed SDL_MOUSEWHEEL value clamping, as values seem correct in latest Emscripten. (#4019) +// 2023-02-01: Flipping SDL_MOUSEWHEEL 'wheel.x' value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463) +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-09-26: Inputs: Disable SDL 2.0.22 new "auto capture" (SDL_HINT_MOUSE_AUTO_CAPTURE) which prevents drag and drop across windows for multi-viewport support + don't capture when drag and dropping. (#5710) +// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). +// 2022-03-22: Inputs: Fix mouse position issues when dragging outside of boundaries. SDL_CaptureMouse() erroneously still gives out LEAVE events when hovering OS decorations. +// 2022-03-22: Inputs: Added support for extra mouse buttons (SDL_BUTTON_X1/SDL_BUTTON_X2). +// 2022-02-04: Added SDL_Renderer* parameter to ImGui_ImplSDL2_InitForSDLRenderer(), so we can use SDL_GetRendererOutputSize() instead of SDL_GL_GetDrawableSize() when bound to a SDL_Renderer. +// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. +// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. +// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). +// 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates. +// 2022-01-12: Update mouse inputs using SDL_MOUSEMOTION/SDL_WINDOWEVENT_LEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API. +// 2022-01-12: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. +// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. +// 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST. +// 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+) +// 2021-06-29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary. +// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950) +// 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends. +// 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2). +// 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state). +// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. +// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. +// 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application). +// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. +// 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls. +// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. +// 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'. +// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls. +// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. +// 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples. +// 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter. +// 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText). +// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. +// 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value. +// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. +// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. +// 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS). +// 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes. +// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. +// 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS. +// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert. +// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). +// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_sdl2.h" + +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#endif + +// SDL +#include +#include +#if defined(__APPLE__) +#include +#endif + +#if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 +#else +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 +#endif +#define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6) + +// SDL Data +struct ImGui_ImplSDL2_Data +{ + SDL_Window* Window; + SDL_Renderer* Renderer; + Uint64 Time; + char* ClipboardTextData; + + // Mouse handling + Uint32 MouseWindowID; + int MouseButtonsDown; + SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; + SDL_Cursor* MouseLastCursor; + int MouseLastLeaveFrame; + bool MouseCanUseGlobalState; + + // Gamepad handling + ImVector Gamepads; + ImGui_ImplSDL2_GamepadMode GamepadMode; + bool WantUpdateGamepadsList; + + ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. +// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; +} + +// Functions +static const char* ImGui_ImplSDL2_GetClipboardText(void*) +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + bd->ClipboardTextData = SDL_GetClipboardText(); + return bd->ClipboardTextData; +} + +static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text) +{ + SDL_SetClipboardText(text); +} + +// Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow(). +static void ImGui_ImplSDL2_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeData* data) +{ + if (data->WantVisible) + { + SDL_Rect r; + r.x = (int)data->InputPos.x; + r.y = (int)data->InputPos.y; + r.w = 1; + r.h = (int)data->InputLineHeight; + SDL_SetTextInputRect(&r); + } +} + +static ImGuiKey ImGui_ImplSDL2_KeycodeToImGuiKey(int keycode) +{ + switch (keycode) + { + case SDLK_TAB: return ImGuiKey_Tab; + case SDLK_LEFT: return ImGuiKey_LeftArrow; + case SDLK_RIGHT: return ImGuiKey_RightArrow; + case SDLK_UP: return ImGuiKey_UpArrow; + case SDLK_DOWN: return ImGuiKey_DownArrow; + case SDLK_PAGEUP: return ImGuiKey_PageUp; + case SDLK_PAGEDOWN: return ImGuiKey_PageDown; + case SDLK_HOME: return ImGuiKey_Home; + case SDLK_END: return ImGuiKey_End; + case SDLK_INSERT: return ImGuiKey_Insert; + case SDLK_DELETE: return ImGuiKey_Delete; + case SDLK_BACKSPACE: return ImGuiKey_Backspace; + case SDLK_SPACE: return ImGuiKey_Space; + case SDLK_RETURN: return ImGuiKey_Enter; + case SDLK_ESCAPE: return ImGuiKey_Escape; + case SDLK_QUOTE: return ImGuiKey_Apostrophe; + case SDLK_COMMA: return ImGuiKey_Comma; + case SDLK_MINUS: return ImGuiKey_Minus; + case SDLK_PERIOD: return ImGuiKey_Period; + case SDLK_SLASH: return ImGuiKey_Slash; + case SDLK_SEMICOLON: return ImGuiKey_Semicolon; + case SDLK_EQUALS: return ImGuiKey_Equal; + case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; + case SDLK_BACKSLASH: return ImGuiKey_Backslash; + case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; + case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent; + case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; + case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; + case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; + case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; + case SDLK_PAUSE: return ImGuiKey_Pause; + case SDLK_KP_0: return ImGuiKey_Keypad0; + case SDLK_KP_1: return ImGuiKey_Keypad1; + case SDLK_KP_2: return ImGuiKey_Keypad2; + case SDLK_KP_3: return ImGuiKey_Keypad3; + case SDLK_KP_4: return ImGuiKey_Keypad4; + case SDLK_KP_5: return ImGuiKey_Keypad5; + case SDLK_KP_6: return ImGuiKey_Keypad6; + case SDLK_KP_7: return ImGuiKey_Keypad7; + case SDLK_KP_8: return ImGuiKey_Keypad8; + case SDLK_KP_9: return ImGuiKey_Keypad9; + case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal; + case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide; + case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; + case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract; + case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd; + case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter; + case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual; + case SDLK_LCTRL: return ImGuiKey_LeftCtrl; + case SDLK_LSHIFT: return ImGuiKey_LeftShift; + case SDLK_LALT: return ImGuiKey_LeftAlt; + case SDLK_LGUI: return ImGuiKey_LeftSuper; + case SDLK_RCTRL: return ImGuiKey_RightCtrl; + case SDLK_RSHIFT: return ImGuiKey_RightShift; + case SDLK_RALT: return ImGuiKey_RightAlt; + case SDLK_RGUI: return ImGuiKey_RightSuper; + case SDLK_APPLICATION: return ImGuiKey_Menu; + case SDLK_0: return ImGuiKey_0; + case SDLK_1: return ImGuiKey_1; + case SDLK_2: return ImGuiKey_2; + case SDLK_3: return ImGuiKey_3; + case SDLK_4: return ImGuiKey_4; + case SDLK_5: return ImGuiKey_5; + case SDLK_6: return ImGuiKey_6; + case SDLK_7: return ImGuiKey_7; + case SDLK_8: return ImGuiKey_8; + case SDLK_9: return ImGuiKey_9; + case SDLK_a: return ImGuiKey_A; + case SDLK_b: return ImGuiKey_B; + case SDLK_c: return ImGuiKey_C; + case SDLK_d: return ImGuiKey_D; + case SDLK_e: return ImGuiKey_E; + case SDLK_f: return ImGuiKey_F; + case SDLK_g: return ImGuiKey_G; + case SDLK_h: return ImGuiKey_H; + case SDLK_i: return ImGuiKey_I; + case SDLK_j: return ImGuiKey_J; + case SDLK_k: return ImGuiKey_K; + case SDLK_l: return ImGuiKey_L; + case SDLK_m: return ImGuiKey_M; + case SDLK_n: return ImGuiKey_N; + case SDLK_o: return ImGuiKey_O; + case SDLK_p: return ImGuiKey_P; + case SDLK_q: return ImGuiKey_Q; + case SDLK_r: return ImGuiKey_R; + case SDLK_s: return ImGuiKey_S; + case SDLK_t: return ImGuiKey_T; + case SDLK_u: return ImGuiKey_U; + case SDLK_v: return ImGuiKey_V; + case SDLK_w: return ImGuiKey_W; + case SDLK_x: return ImGuiKey_X; + case SDLK_y: return ImGuiKey_Y; + case SDLK_z: return ImGuiKey_Z; + case SDLK_F1: return ImGuiKey_F1; + case SDLK_F2: return ImGuiKey_F2; + case SDLK_F3: return ImGuiKey_F3; + case SDLK_F4: return ImGuiKey_F4; + case SDLK_F5: return ImGuiKey_F5; + case SDLK_F6: return ImGuiKey_F6; + case SDLK_F7: return ImGuiKey_F7; + case SDLK_F8: return ImGuiKey_F8; + case SDLK_F9: return ImGuiKey_F9; + case SDLK_F10: return ImGuiKey_F10; + case SDLK_F11: return ImGuiKey_F11; + case SDLK_F12: return ImGuiKey_F12; + case SDLK_F13: return ImGuiKey_F13; + case SDLK_F14: return ImGuiKey_F14; + case SDLK_F15: return ImGuiKey_F15; + case SDLK_F16: return ImGuiKey_F16; + case SDLK_F17: return ImGuiKey_F17; + case SDLK_F18: return ImGuiKey_F18; + case SDLK_F19: return ImGuiKey_F19; + case SDLK_F20: return ImGuiKey_F20; + case SDLK_F21: return ImGuiKey_F21; + case SDLK_F22: return ImGuiKey_F22; + case SDLK_F23: return ImGuiKey_F23; + case SDLK_F24: return ImGuiKey_F24; + case SDLK_AC_BACK: return ImGuiKey_AppBack; + case SDLK_AC_FORWARD: return ImGuiKey_AppForward; + } + return ImGuiKey_None; +} + +static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0); + io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0); + io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0); +} + +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. +// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. +bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + + switch (event->type) + { + case SDL_MOUSEMOTION: + { + ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); + io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); + return true; + } + case SDL_MOUSEWHEEL: + { + //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); +#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten! + float wheel_x = -event->wheel.preciseX; + float wheel_y = event->wheel.preciseY; +#else + float wheel_x = -(float)event->wheel.x; + float wheel_y = (float)event->wheel.y; +#endif +#ifdef __EMSCRIPTEN__ + wheel_x /= 100.0f; +#endif + io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseWheelEvent(wheel_x, wheel_y); + return true; + } + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + { + int mouse_button = -1; + if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } + if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } + if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; } + if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; } + if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; } + if (mouse_button == -1) + break; + io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN)); + bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button)); + return true; + } + case SDL_TEXTINPUT: + { + io.AddInputCharactersUTF8(event->text.text); + return true; + } + case SDL_KEYDOWN: + case SDL_KEYUP: + { + ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); + ImGuiKey key = ImGui_ImplSDL2_KeycodeToImGuiKey(event->key.keysym.sym); + io.AddKeyEvent(key, (event->type == SDL_KEYDOWN)); + io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + return true; + } + case SDL_WINDOWEVENT: + { + // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right. + // - However we won't get a correct LEAVE event for a captured window. + // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, + // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why + // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details. + Uint8 window_event = event->window.event; + if (window_event == SDL_WINDOWEVENT_ENTER) + { + bd->MouseWindowID = event->window.windowID; + bd->MouseLastLeaveFrame = 0; + } + if (window_event == SDL_WINDOWEVENT_LEAVE) + bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1; + if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED) + io.AddFocusEvent(true); + else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST) + io.AddFocusEvent(false); + return true; + } + case SDL_CONTROLLERDEVICEADDED: + case SDL_CONTROLLERDEVICEREMOVED: + { + bd->WantUpdateGamepadsList = true; + return true; + } + } + return false; +} + +static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer) +{ + ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + + // Check and store if we are on a SDL backend that supports global mouse position + // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) + bool mouse_can_use_global_state = false; +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + const char* sdl_backend = SDL_GetCurrentVideoDriver(); + const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; + for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) + if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) + mouse_can_use_global_state = true; +#endif + + // Setup backend capabilities flags + ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)(); + io.BackendPlatformUserData = (void*)bd; + io.BackendPlatformName = "imgui_impl_sdl2"; + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + + bd->Window = window; + bd->Renderer = renderer; + bd->MouseCanUseGlobalState = mouse_can_use_global_state; + + io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText; + io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText; + io.ClipboardUserData = nullptr; + io.SetPlatformImeDataFn = ImGui_ImplSDL2_SetPlatformImeData; + + // Gamepad handling + bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst; + bd->WantUpdateGamepadsList = true; + + // Load mouse cursors + bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); + bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); + bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL); + bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS); + bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); + bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); + bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); + bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO); + + // Set platform dependent data in viewport + // Our mouse update function expect PlatformHandle to be filled for the main viewport + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + main_viewport->PlatformHandleRaw = nullptr; + SDL_SysWMinfo info; + SDL_VERSION(&info.version); + if (SDL_GetWindowWMInfo(window, &info)) + { +#if defined(SDL_VIDEO_DRIVER_WINDOWS) + main_viewport->PlatformHandleRaw = (void*)info.info.win.window; +#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) + main_viewport->PlatformHandleRaw = (void*)info.info.cocoa.window; +#endif + } + + // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. + // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. + // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. + // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: + // you can ignore SDL_MOUSEBUTTONDOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED) +#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH + SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); +#endif + + // From 2.0.18: Enable native IME. + // IMPORTANT: This is used at the time of SDL_CreateWindow() so this will only affects secondary windows, if any. + // For the main window to be affected, your application needs to call this manually before calling SDL_CreateWindow(). +#ifdef SDL_HINT_IME_SHOW_UI + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); +#endif + + // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710) +#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE + SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); +#endif + + return true; +} + +bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) +{ + IM_UNUSED(sdl_gl_context); // Viewport branch will need this. + return ImGui_ImplSDL2_Init(window, nullptr); +} + +bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window) +{ +#if !SDL_HAS_VULKAN + IM_ASSERT(0 && "Unsupported"); +#endif + return ImGui_ImplSDL2_Init(window, nullptr); +} + +bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window) +{ +#if !defined(_WIN32) + IM_ASSERT(0 && "Unsupported"); +#endif + return ImGui_ImplSDL2_Init(window, nullptr); +} + +bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window) +{ + return ImGui_ImplSDL2_Init(window, nullptr); +} + +bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) +{ + return ImGui_ImplSDL2_Init(window, renderer); +} + +bool ImGui_ImplSDL2_InitForOther(SDL_Window* window) +{ + return ImGui_ImplSDL2_Init(window, nullptr); +} + +static void ImGui_ImplSDL2_CloseGamepads(); + +void ImGui_ImplSDL2_Shutdown() +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) + SDL_FreeCursor(bd->MouseCursors[cursor_n]); + ImGui_ImplSDL2_CloseGamepads(); + + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + IM_DELETE(bd); +} + +static void ImGui_ImplSDL2_UpdateMouseData() +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + ImGuiIO& io = ImGui::GetIO(); + + // We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below) +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside + SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE); + SDL_Window* focused_window = SDL_GetKeyboardFocus(); + const bool is_app_focused = (bd->Window == focused_window); +#else + const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only +#endif + if (is_app_focused) + { + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + if (io.WantSetMousePos) + SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y); + + // (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured) + if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) + { + int window_x, window_y, mouse_x_global, mouse_y_global; + SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); + SDL_GetWindowPosition(bd->Window, &window_x, &window_y); + io.AddMousePosEvent((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y)); + } + } +} + +static void ImGui_ImplSDL2_UpdateMouseCursor() +{ + ImGuiIO& io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) + return; + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + + ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + SDL_ShowCursor(SDL_FALSE); + } + else + { + // Show OS mouse cursor + SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; + if (bd->MouseLastCursor != expected_cursor) + { + SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) + bd->MouseLastCursor = expected_cursor; + } + SDL_ShowCursor(SDL_TRUE); + } +} + +static void ImGui_ImplSDL2_CloseGamepads() +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + if (bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual) + for (SDL_GameController* gamepad : bd->Gamepads) + SDL_GameControllerClose(gamepad); + bd->Gamepads.resize(0); +} + +void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array, int manual_gamepads_count) +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + ImGui_ImplSDL2_CloseGamepads(); + if (mode == ImGui_ImplSDL2_GamepadMode_Manual) + { + IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0); + for (int n = 0; n < manual_gamepads_count; n++) + bd->Gamepads.push_back(manual_gamepads_array[n]); + } + else + { + IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0); + bd->WantUpdateGamepadsList = true; + } + bd->GamepadMode = mode; +} + +static void ImGui_ImplSDL2_UpdateGamepadButton(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerButton button_no) +{ + bool merged_value = false; + for (SDL_GameController* gamepad : bd->Gamepads) + merged_value |= SDL_GameControllerGetButton(gamepad, button_no) != 0; + io.AddKeyEvent(key, merged_value); +} + +static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } +static void ImGui_ImplSDL2_UpdateGamepadAnalog(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerAxis axis_no, float v0, float v1) +{ + float merged_value = 0.0f; + for (SDL_GameController* gamepad : bd->Gamepads) + { + float vn = Saturate((float)(SDL_GameControllerGetAxis(gamepad, axis_no) - v0) / (float)(v1 - v0)); + if (merged_value < vn) + merged_value = vn; + } + io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value); +} + +static void ImGui_ImplSDL2_UpdateGamepads() +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + ImGuiIO& io = ImGui::GetIO(); + + // Update list of controller(s) to use + if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual) + { + ImGui_ImplSDL2_CloseGamepads(); + int joystick_count = SDL_NumJoysticks(); + for (int n = 0; n < joystick_count; n++) + if (SDL_IsGameController(n)) + if (SDL_GameController* gamepad = SDL_GameControllerOpen(n)) + { + bd->Gamepads.push_back(gamepad); + if (bd->GamepadMode == ImGui_ImplSDL2_GamepadMode_AutoFirst) + break; + } + bd->WantUpdateGamepadsList = false; + } + + // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + return; + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; + if (bd->Gamepads.Size == 0) + return; + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + + // Update gamepad inputs + const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value. + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK); + ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767); +} + +void ImGui_ImplSDL2_NewFrame() +{ + ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDL2_Init()?"); + ImGuiIO& io = ImGui::GetIO(); + + // Setup display size (every frame to accommodate for window resizing) + int w, h; + int display_w, display_h; + SDL_GetWindowSize(bd->Window, &w, &h); + if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) + w = h = 0; + if (bd->Renderer != nullptr) + SDL_GetRendererOutputSize(bd->Renderer, &display_w, &display_h); + else + SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h); + io.DisplaySize = ImVec2((float)w, (float)h); + if (w > 0 && h > 0) + io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); + + // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) + // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) + static Uint64 frequency = SDL_GetPerformanceFrequency(); + Uint64 current_time = SDL_GetPerformanceCounter(); + if (current_time <= bd->Time) + current_time = bd->Time + 1; + io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); + bd->Time = current_time; + + if (bd->MouseLastLeaveFrame && bd->MouseLastLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) + { + bd->MouseWindowID = 0; + bd->MouseLastLeaveFrame = 0; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + } + + ImGui_ImplSDL2_UpdateMouseData(); + ImGui_ImplSDL2_UpdateMouseCursor(); + + // Update game controllers (if enabled and available) + ImGui_ImplSDL2_UpdateGamepads(); +} + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdl2.h b/third_party/imgui/backends/imgui_impl_sdl2.h new file mode 100644 index 00000000000..7020a29e060 --- /dev/null +++ b/third_party/imgui/backends/imgui_impl_sdl2.h @@ -0,0 +1,45 @@ +// dear imgui: Platform Backend for SDL2 +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +struct SDL_Window; +struct SDL_Renderer; +struct _SDL_GameController; +typedef union SDL_Event SDL_Event; + +IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); +IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); +IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOther(SDL_Window* window); +IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(); +IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); + +// Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. +// When using manual mode, caller is responsible for opening/closing gamepad. +enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual }; +IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = NULL, int manual_gamepads_count = -1); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdl3.cpp b/third_party/imgui/backends/imgui_impl_sdl3.cpp new file mode 100644 index 00000000000..2e261ef1a07 --- /dev/null +++ b/third_party/imgui/backends/imgui_impl_sdl3.cpp @@ -0,0 +1,697 @@ +// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) +// (IMPORTANT: SDL 3.0.0 is NOT YET RELEASED. IT IS POSSIBLE THAT ITS SPECS/API WILL CHANGE BEFORE RELEASE) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// Missing features: +// [x] Platform: Basic IME support. Position somehow broken in SDL3 + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode(). +// 2023-11-13: Updated for recent SDL3 API changes. +// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys. +// 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391) +// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) +// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) +// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) +// 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_sdl3.h" + +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision +#endif + +// SDL +#include +#if defined(__APPLE__) +#include +#endif +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif + +#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 +#else +#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 +#endif + +// SDL Data +struct ImGui_ImplSDL3_Data +{ + SDL_Window* Window; + SDL_Renderer* Renderer; + Uint64 Time; + char* ClipboardTextData; + + // Mouse handling + Uint32 MouseWindowID; + int MouseButtonsDown; + SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; + SDL_Cursor* MouseLastCursor; + int MousePendingLeaveFrame; + bool MouseCanUseGlobalState; + + // Gamepad handling + ImVector Gamepads; + ImGui_ImplSDL3_GamepadMode GamepadMode; + bool WantUpdateGamepadsList; + + ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +// FIXME: multi-context support is not well tested and probably dysfunctional in this backend. +// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. +static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; +} + +// Functions +static const char* ImGui_ImplSDL3_GetClipboardText(void*) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + bd->ClipboardTextData = SDL_GetClipboardText(); + return bd->ClipboardTextData; +} + +static void ImGui_ImplSDL3_SetClipboardText(void*, const char* text) +{ + SDL_SetClipboardText(text); +} + +static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeData* data) +{ + if (data->WantVisible) + { + SDL_Rect r; + r.x = (int)data->InputPos.x; + r.y = (int)data->InputPos.y; + r.w = 1; + r.h = (int)data->InputLineHeight; + SDL_SetTextInputRect(&r); + } +} + +static ImGuiKey ImGui_ImplSDL3_KeycodeToImGuiKey(int keycode) +{ + switch (keycode) + { + case SDLK_TAB: return ImGuiKey_Tab; + case SDLK_LEFT: return ImGuiKey_LeftArrow; + case SDLK_RIGHT: return ImGuiKey_RightArrow; + case SDLK_UP: return ImGuiKey_UpArrow; + case SDLK_DOWN: return ImGuiKey_DownArrow; + case SDLK_PAGEUP: return ImGuiKey_PageUp; + case SDLK_PAGEDOWN: return ImGuiKey_PageDown; + case SDLK_HOME: return ImGuiKey_Home; + case SDLK_END: return ImGuiKey_End; + case SDLK_INSERT: return ImGuiKey_Insert; + case SDLK_DELETE: return ImGuiKey_Delete; + case SDLK_BACKSPACE: return ImGuiKey_Backspace; + case SDLK_SPACE: return ImGuiKey_Space; + case SDLK_RETURN: return ImGuiKey_Enter; + case SDLK_ESCAPE: return ImGuiKey_Escape; + case SDLK_QUOTE: return ImGuiKey_Apostrophe; + case SDLK_COMMA: return ImGuiKey_Comma; + case SDLK_MINUS: return ImGuiKey_Minus; + case SDLK_PERIOD: return ImGuiKey_Period; + case SDLK_SLASH: return ImGuiKey_Slash; + case SDLK_SEMICOLON: return ImGuiKey_Semicolon; + case SDLK_EQUALS: return ImGuiKey_Equal; + case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; + case SDLK_BACKSLASH: return ImGuiKey_Backslash; + case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; + case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent; + case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; + case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; + case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; + case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; + case SDLK_PAUSE: return ImGuiKey_Pause; + case SDLK_KP_0: return ImGuiKey_Keypad0; + case SDLK_KP_1: return ImGuiKey_Keypad1; + case SDLK_KP_2: return ImGuiKey_Keypad2; + case SDLK_KP_3: return ImGuiKey_Keypad3; + case SDLK_KP_4: return ImGuiKey_Keypad4; + case SDLK_KP_5: return ImGuiKey_Keypad5; + case SDLK_KP_6: return ImGuiKey_Keypad6; + case SDLK_KP_7: return ImGuiKey_Keypad7; + case SDLK_KP_8: return ImGuiKey_Keypad8; + case SDLK_KP_9: return ImGuiKey_Keypad9; + case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal; + case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide; + case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; + case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract; + case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd; + case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter; + case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual; + case SDLK_LCTRL: return ImGuiKey_LeftCtrl; + case SDLK_LSHIFT: return ImGuiKey_LeftShift; + case SDLK_LALT: return ImGuiKey_LeftAlt; + case SDLK_LGUI: return ImGuiKey_LeftSuper; + case SDLK_RCTRL: return ImGuiKey_RightCtrl; + case SDLK_RSHIFT: return ImGuiKey_RightShift; + case SDLK_RALT: return ImGuiKey_RightAlt; + case SDLK_RGUI: return ImGuiKey_RightSuper; + case SDLK_APPLICATION: return ImGuiKey_Menu; + case SDLK_0: return ImGuiKey_0; + case SDLK_1: return ImGuiKey_1; + case SDLK_2: return ImGuiKey_2; + case SDLK_3: return ImGuiKey_3; + case SDLK_4: return ImGuiKey_4; + case SDLK_5: return ImGuiKey_5; + case SDLK_6: return ImGuiKey_6; + case SDLK_7: return ImGuiKey_7; + case SDLK_8: return ImGuiKey_8; + case SDLK_9: return ImGuiKey_9; + case SDLK_a: return ImGuiKey_A; + case SDLK_b: return ImGuiKey_B; + case SDLK_c: return ImGuiKey_C; + case SDLK_d: return ImGuiKey_D; + case SDLK_e: return ImGuiKey_E; + case SDLK_f: return ImGuiKey_F; + case SDLK_g: return ImGuiKey_G; + case SDLK_h: return ImGuiKey_H; + case SDLK_i: return ImGuiKey_I; + case SDLK_j: return ImGuiKey_J; + case SDLK_k: return ImGuiKey_K; + case SDLK_l: return ImGuiKey_L; + case SDLK_m: return ImGuiKey_M; + case SDLK_n: return ImGuiKey_N; + case SDLK_o: return ImGuiKey_O; + case SDLK_p: return ImGuiKey_P; + case SDLK_q: return ImGuiKey_Q; + case SDLK_r: return ImGuiKey_R; + case SDLK_s: return ImGuiKey_S; + case SDLK_t: return ImGuiKey_T; + case SDLK_u: return ImGuiKey_U; + case SDLK_v: return ImGuiKey_V; + case SDLK_w: return ImGuiKey_W; + case SDLK_x: return ImGuiKey_X; + case SDLK_y: return ImGuiKey_Y; + case SDLK_z: return ImGuiKey_Z; + case SDLK_F1: return ImGuiKey_F1; + case SDLK_F2: return ImGuiKey_F2; + case SDLK_F3: return ImGuiKey_F3; + case SDLK_F4: return ImGuiKey_F4; + case SDLK_F5: return ImGuiKey_F5; + case SDLK_F6: return ImGuiKey_F6; + case SDLK_F7: return ImGuiKey_F7; + case SDLK_F8: return ImGuiKey_F8; + case SDLK_F9: return ImGuiKey_F9; + case SDLK_F10: return ImGuiKey_F10; + case SDLK_F11: return ImGuiKey_F11; + case SDLK_F12: return ImGuiKey_F12; + case SDLK_F13: return ImGuiKey_F13; + case SDLK_F14: return ImGuiKey_F14; + case SDLK_F15: return ImGuiKey_F15; + case SDLK_F16: return ImGuiKey_F16; + case SDLK_F17: return ImGuiKey_F17; + case SDLK_F18: return ImGuiKey_F18; + case SDLK_F19: return ImGuiKey_F19; + case SDLK_F20: return ImGuiKey_F20; + case SDLK_F21: return ImGuiKey_F21; + case SDLK_F22: return ImGuiKey_F22; + case SDLK_F23: return ImGuiKey_F23; + case SDLK_F24: return ImGuiKey_F24; + case SDLK_AC_BACK: return ImGuiKey_AppBack; + case SDLK_AC_FORWARD: return ImGuiKey_AppForward; + } + return ImGuiKey_None; +} + +static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods) +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & SDL_KMOD_CTRL) != 0); + io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & SDL_KMOD_SHIFT) != 0); + io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & SDL_KMOD_ALT) != 0); + io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0); +} + +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. +// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. +bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + + switch (event->type) + { + case SDL_EVENT_MOUSE_MOTION: + { + ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y); + io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMousePosEvent(mouse_pos.x, mouse_pos.y); + return true; + } + case SDL_EVENT_MOUSE_WHEEL: + { + //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY); + float wheel_x = -event->wheel.x; + float wheel_y = event->wheel.y; + #ifdef __EMSCRIPTEN__ + wheel_x /= 100.0f; + #endif + io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseWheelEvent(wheel_x, wheel_y); + return true; + } + case SDL_EVENT_MOUSE_BUTTON_DOWN: + case SDL_EVENT_MOUSE_BUTTON_UP: + { + int mouse_button = -1; + if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; } + if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; } + if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; } + if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; } + if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; } + if (mouse_button == -1) + break; + io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + io.AddMouseButtonEvent(mouse_button, (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN)); + bd->MouseButtonsDown = (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button)); + return true; + } + case SDL_EVENT_TEXT_INPUT: + { + io.AddInputCharactersUTF8(event->text.text); + return true; + } + case SDL_EVENT_KEY_DOWN: + case SDL_EVENT_KEY_UP: + { + ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod); + ImGuiKey key = ImGui_ImplSDL3_KeycodeToImGuiKey(event->key.keysym.sym); + io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN)); + io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions. + return true; + } + case SDL_EVENT_WINDOW_MOUSE_ENTER: + { + bd->MouseWindowID = event->window.windowID; + bd->MousePendingLeaveFrame = 0; + return true; + } + // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, + // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why + // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details. + // FIXME: Unconfirmed whether this is still needed with SDL3. + case SDL_EVENT_WINDOW_MOUSE_LEAVE: + { + bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1; + return true; + } + case SDL_EVENT_WINDOW_FOCUS_GAINED: + io.AddFocusEvent(true); + return true; + case SDL_EVENT_WINDOW_FOCUS_LOST: + io.AddFocusEvent(false); + return true; + case SDL_EVENT_GAMEPAD_ADDED: + case SDL_EVENT_GAMEPAD_REMOVED: + { + bd->WantUpdateGamepadsList = true; + return true; + } + } + return false; +} + +static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window) +{ + IM_UNUSED(window); + viewport->PlatformHandleRaw = nullptr; +#if defined(__WIN32__) && !defined(__WINRT__) + viewport->PlatformHandleRaw = (HWND)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.win32.hwnd", nullptr); +#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA) + viewport->PlatformHandleRaw = (void*)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.cocoa.window", nullptr); +#endif +} + +static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) +{ + ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); + IM_UNUSED(sdl_gl_context); // Unused in this branch + + // Check and store if we are on a SDL backend that supports global mouse position + // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) + bool mouse_can_use_global_state = false; +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + const char* sdl_backend = SDL_GetCurrentVideoDriver(); + const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" }; + for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++) + if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0) + mouse_can_use_global_state = true; +#endif + + // Setup backend capabilities flags + ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)(); + io.BackendPlatformUserData = (void*)bd; + io.BackendPlatformName = "imgui_impl_sdl3"; + io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) + io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) + + bd->Window = window; + bd->Renderer = renderer; + bd->MouseCanUseGlobalState = mouse_can_use_global_state; + + io.SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText; + io.GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText; + io.ClipboardUserData = nullptr; + io.SetPlatformImeDataFn = ImGui_ImplSDL3_SetPlatformImeData; + + // Gamepad handling + bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst; + bd->WantUpdateGamepadsList = true; + + // Load mouse cursors + bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); + bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); + bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL); + bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS); + bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE); + bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW); + bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE); + bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND); + bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO); + + // Set platform dependent data in viewport + // Our mouse update function expect PlatformHandle to be filled for the main viewport + ImGuiViewport* main_viewport = ImGui::GetMainViewport(); + ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window); + + // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. + // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. + // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application. + // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click: + // you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED) +#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH + SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); +#endif + + // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710) +#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE + SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0"); +#endif + + return true; +} + +bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) +{ + IM_UNUSED(sdl_gl_context); // Viewport branch will need this. + return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context); +} + +bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window) +{ +#if !defined(_WIN32) + IM_ASSERT(0 && "Unsupported"); +#endif + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) +{ + return ImGui_ImplSDL3_Init(window, renderer, nullptr); +} + +bool ImGui_ImplSDL3_InitForOther(SDL_Window* window) +{ + return ImGui_ImplSDL3_Init(window, nullptr, nullptr); +} + +static void ImGui_ImplSDL3_CloseGamepads(); + +void ImGui_ImplSDL3_Shutdown() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + if (bd->ClipboardTextData) + SDL_free(bd->ClipboardTextData); + for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) + SDL_DestroyCursor(bd->MouseCursors[cursor_n]); + ImGui_ImplSDL3_CloseGamepads(); + + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); + IM_DELETE(bd); +} + +static void ImGui_ImplSDL3_UpdateMouseData() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGuiIO& io = ImGui::GetIO(); + + // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below) +#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE + // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside + SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE); + SDL_Window* focused_window = SDL_GetKeyboardFocus(); + const bool is_app_focused = (bd->Window == focused_window); +#else + SDL_Window* focused_window = bd->Window; + const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only +#endif + if (is_app_focused) + { + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + if (io.WantSetMousePos) + SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y); + + // (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured) + if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0) + { + // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window) + float mouse_x_global, mouse_y_global; + int window_x, window_y; + SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global); + SDL_GetWindowPosition(focused_window, &window_x, &window_y); + io.AddMousePosEvent(mouse_x_global - window_x, mouse_y_global - window_y); + } + } +} + +static void ImGui_ImplSDL3_UpdateMouseCursor() +{ + ImGuiIO& io = ImGui::GetIO(); + if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) + return; + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + + ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None) + { + // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor + SDL_HideCursor(); + } + else + { + // Show OS mouse cursor + SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; + if (bd->MouseLastCursor != expected_cursor) + { + SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) + bd->MouseLastCursor = expected_cursor; + } + SDL_ShowCursor(); + } +} + +static void ImGui_ImplSDL3_CloseGamepads() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) + for (SDL_Gamepad* gamepad : bd->Gamepads) + SDL_CloseGamepad(gamepad); + bd->Gamepads.resize(0); +} + +void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count) +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + ImGui_ImplSDL3_CloseGamepads(); + if (mode == ImGui_ImplSDL3_GamepadMode_Manual) + { + IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0); + for (int n = 0; n < manual_gamepads_count; n++) + bd->Gamepads.push_back(manual_gamepads_array[n]); + } + else + { + IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0); + bd->WantUpdateGamepadsList = true; + } + bd->GamepadMode = mode; +} + +static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no) +{ + bool merged_value = false; + for (SDL_Gamepad* gamepad : bd->Gamepads) + merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0; + io.AddKeyEvent(key, merged_value); +} + +static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } +static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1) +{ + float merged_value = 0.0f; + for (SDL_Gamepad* gamepad : bd->Gamepads) + { + float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0)); + if (merged_value < vn) + merged_value = vn; + } + io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value); +} + +static void ImGui_ImplSDL3_UpdateGamepads() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + + // Update list of gamepads to use + if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual) + { + ImGui_ImplSDL3_CloseGamepads(); + int sdl_gamepads_count = 0; + SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count); + for (int n = 0; n < sdl_gamepads_count; n++) + if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n])) + { + bd->Gamepads.push_back(gamepad); + if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst) + break; + } + bd->WantUpdateGamepadsList = false; + } + + // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. + if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) + return; + io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; + if (bd->Gamepads.Size == 0) + return; + io.BackendFlags |= ImGuiBackendFlags_HasGamepad; + + // Update gamepad inputs + const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value. + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK); + ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768); + ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767); +} + +void ImGui_ImplSDL3_NewFrame() +{ + ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDL3_Init()?"); + ImGuiIO& io = ImGui::GetIO(); + + // Setup display size (every frame to accommodate for window resizing) + int w, h; + int display_w, display_h; + SDL_GetWindowSize(bd->Window, &w, &h); + if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED) + w = h = 0; + SDL_GetWindowSizeInPixels(bd->Window, &display_w, &display_h); + io.DisplaySize = ImVec2((float)w, (float)h); + if (w > 0 && h > 0) + io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); + + // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution) + // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644) + static Uint64 frequency = SDL_GetPerformanceFrequency(); + Uint64 current_time = SDL_GetPerformanceCounter(); + if (current_time <= bd->Time) + current_time = bd->Time + 1; + io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); + bd->Time = current_time; + + if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) + { + bd->MouseWindowID = 0; + bd->MousePendingLeaveFrame = 0; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + } + + ImGui_ImplSDL3_UpdateMouseData(); + ImGui_ImplSDL3_UpdateMouseCursor(); + + // Update game controllers (if enabled and available) + ImGui_ImplSDL3_UpdateGamepads(); +} + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdl3.h b/third_party/imgui/backends/imgui_impl_sdl3.h new file mode 100644 index 00000000000..4898729d4a7 --- /dev/null +++ b/third_party/imgui/backends/imgui_impl_sdl3.h @@ -0,0 +1,47 @@ +// dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) +// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) +// (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) +// (IMPORTANT: SDL 3.0.0 is NOT YET RELEASED. IT IS POSSIBLE THAT ITS SPECS/API WILL CHANGE BEFORE RELEASE) + +// Implemented features: +// [X] Platform: Clipboard support. +// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] +// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. +// Missing features: +// [x] Platform: Basic IME support. Position somehow broken in SDL3 + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +struct SDL_Window; +struct SDL_Renderer; +struct SDL_Gamepad; +typedef union SDL_Event SDL_Event; + +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); +IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOther(SDL_Window* window); +IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame(); +IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); + +// Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this. +// When using manual mode, caller is responsible for opening/closing gamepad. +enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual }; +IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = NULL, int manual_gamepads_count = -1); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdlrenderer.h b/third_party/imgui/backends/imgui_impl_sdlrenderer.h deleted file mode 100644 index 51a1c45f957..00000000000 --- a/third_party/imgui/backends/imgui_impl_sdlrenderer.h +++ /dev/null @@ -1,29 +0,0 @@ -// dear imgui: Renderer Backend for SDL_Renderer -// (Requires: SDL 2.0.17+) - -// Important to understand: SDL_Renderer is an _optional_ component of SDL. -// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. -// If your application will want to render any non trivial amount of graphics other than UI, -// please be aware that SDL_Renderer offers a limited graphic API to the end-user and it might -// be difficult to step out of those boundaries. -// However, we understand it is a convenient choice to get an app started easily. - -// Implemented features: -// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. - -#pragma once -#include "imgui.h" // IMGUI_IMPL_API - -struct SDL_Renderer; - -IMGUI_IMPL_API bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer); -IMGUI_IMPL_API void ImGui_ImplSDLRenderer_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplSDLRenderer_NewFrame(); -IMGUI_IMPL_API void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data); - -// Called by Init/NewFrame/Shutdown -IMGUI_IMPL_API bool ImGui_ImplSDLRenderer_CreateFontsTexture(); -IMGUI_IMPL_API void ImGui_ImplSDLRenderer_DestroyFontsTexture(); -IMGUI_IMPL_API bool ImGui_ImplSDLRenderer_CreateDeviceObjects(); -IMGUI_IMPL_API void ImGui_ImplSDLRenderer_DestroyDeviceObjects(); diff --git a/third_party/imgui/backends/imgui_impl_sdlrenderer.cpp b/third_party/imgui/backends/imgui_impl_sdlrenderer2.cpp similarity index 58% rename from third_party/imgui/backends/imgui_impl_sdlrenderer.cpp rename to third_party/imgui/backends/imgui_impl_sdlrenderer2.cpp index ca4c432f616..7d0ec797836 100644 --- a/third_party/imgui/backends/imgui_impl_sdlrenderer.cpp +++ b/third_party/imgui/backends/imgui_impl_sdlrenderer2.cpp @@ -1,34 +1,41 @@ -// dear imgui: Renderer Backend for SDL_Renderer +// dear imgui: Renderer Backend for SDL_Renderer for SDL2 // (Requires: SDL 2.0.17+) -// Important to understand: SDL_Renderer is an _optional_ component of SDL. +// Note how SDL_Renderer is an _optional_ component of SDL2. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // If your application will want to render any non trivial amount of graphics other than UI, -// please be aware that SDL_Renderer offers a limited graphic API to the end-user and it might -// be difficult to step out of those boundaries. -// However, we understand it is a convenient choice to get an app started easily. +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and +// it might be difficult to step out of those boundaries. // Implemented features: // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// Missing features: +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. -// 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 +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG +// 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3. +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-12-21: Update SDL_RenderGeometryRaw() format to work with SDL 2.0.19. // 2021-12-03: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. // 2021-10-06: Backup and restore modified ClipRect/Viewport. // 2021-09-21: Initial version. #include "imgui.h" -#include "imgui_impl_sdlrenderer.h" -#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier -#include // intptr_t -#else +#ifndef IMGUI_DISABLE +#include "imgui_impl_sdlrenderer2.h" #include // intptr_t + +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #endif // SDL @@ -38,31 +45,31 @@ #endif // SDL_Renderer data -struct ImGui_ImplSDLRenderer_Data +struct ImGui_ImplSDLRenderer2_Data { SDL_Renderer* SDLRenderer; SDL_Texture* FontTexture; - ImGui_ImplSDLRenderer_Data() { memset(this, 0, sizeof(*this)); } + ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. -static ImGui_ImplSDLRenderer_Data* ImGui_ImplSDLRenderer_GetBackendData() +static ImGui_ImplSDLRenderer2_Data* ImGui_ImplSDLRenderer2_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer_Data*)ImGui::GetIO().BackendRendererUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } // Functions -bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer) +bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); - IM_ASSERT(renderer != NULL && "SDL_Renderer not initialized!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); // Setup backend capabilities flags - ImGui_ImplSDLRenderer_Data* bd = IM_NEW(ImGui_ImplSDLRenderer_Data)(); + ImGui_ImplSDLRenderer2_Data* bd = IM_NEW(ImGui_ImplSDLRenderer2_Data)(); io.BackendRendererUserData = (void*)bd; - io.BackendRendererName = "imgui_impl_sdlrenderer"; + io.BackendRendererName = "imgui_impl_sdlrenderer2"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. bd->SDLRenderer = renderer; @@ -70,41 +77,42 @@ bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer) return true; } -void ImGui_ImplSDLRenderer_Shutdown() +void ImGui_ImplSDLRenderer2_Shutdown() { - ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLRenderer_DestroyDeviceObjects(); + ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } -static void ImGui_ImplSDLRenderer_SetupRenderState() +static void ImGui_ImplSDLRenderer2_SetupRenderState() { - ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); + ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); // Clear out any viewports and cliprect set by the user // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. - SDL_RenderSetViewport(bd->SDLRenderer, NULL); - SDL_RenderSetClipRect(bd->SDLRenderer, NULL); + SDL_RenderSetViewport(bd->SDLRenderer, nullptr); + SDL_RenderSetClipRect(bd->SDLRenderer, nullptr); } -void ImGui_ImplSDLRenderer_NewFrame() +void ImGui_ImplSDLRenderer2_NewFrame() { - ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplSDLRenderer_Init()?"); + ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDLRenderer2_Init()?"); if (!bd->FontTexture) - ImGui_ImplSDLRenderer_CreateDeviceObjects(); + ImGui_ImplSDLRenderer2_CreateDeviceObjects(); } -void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data) +void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data) { - ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); + ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); // If there's a scale factor set by the user, use that instead // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass @@ -139,7 +147,7 @@ void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data) ImVec2 clip_scale = render_scale; // Render command lists - ImGui_ImplSDLRenderer_SetupRenderState(); + ImGui_ImplSDLRenderer2_SetupRenderState(); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; @@ -154,7 +162,7 @@ void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data) // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) - ImGui_ImplSDLRenderer_SetupRenderState(); + ImGui_ImplSDLRenderer2_SetupRenderState(); else pcmd->UserCallback(cmd_list, pcmd); } @@ -165,20 +173,20 @@ void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data) ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } - if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } - if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } + if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; } if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) }; SDL_RenderSetClipRect(bd->SDLRenderer, &r); - const float* xy = (const float*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, pos)); - const float* uv = (const float*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, uv)); + const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos)); + const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv)); #if SDL_VERSION_ATLEAST(2,0,19) - const SDL_Color* color = (const SDL_Color*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, col)); // SDL 2.0.19+ + const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+ #else - const int* color = (const int*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, col)); // SDL 2.0.17 and 2.0.18 + const int* color = (const int*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.17 and 2.0.18 #endif // Bind texture, Draw @@ -195,14 +203,14 @@ void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data) // Restore modified SDL_Renderer state SDL_RenderSetViewport(bd->SDLRenderer, &old.Viewport); - SDL_RenderSetClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : NULL); + SDL_RenderSetClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : nullptr); } // Called by Init/NewFrame/Shutdown -bool ImGui_ImplSDLRenderer_CreateFontsTexture() +bool ImGui_ImplSDLRenderer2_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); + ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); // Build texture atlas unsigned char* pixels; @@ -210,14 +218,16 @@ bool ImGui_ImplSDLRenderer_CreateFontsTexture() io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system - bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height); - if (bd->FontTexture == NULL) + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); + if (bd->FontTexture == nullptr) { SDL_Log("error creating texture"); return false; } - SDL_UpdateTexture(bd->FontTexture, NULL, pixels, 4 * width); + SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); + SDL_SetTextureScaleMode(bd->FontTexture, SDL_ScaleModeLinear); // Store our identifier io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); @@ -225,24 +235,32 @@ bool ImGui_ImplSDLRenderer_CreateFontsTexture() return true; } -void ImGui_ImplSDLRenderer_DestroyFontsTexture() +void ImGui_ImplSDLRenderer2_DestroyFontsTexture() { ImGuiIO& io = ImGui::GetIO(); - ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); + ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); if (bd->FontTexture) { io.Fonts->SetTexID(0); SDL_DestroyTexture(bd->FontTexture); - bd->FontTexture = NULL; + bd->FontTexture = nullptr; } } -bool ImGui_ImplSDLRenderer_CreateDeviceObjects() +bool ImGui_ImplSDLRenderer2_CreateDeviceObjects() { - return ImGui_ImplSDLRenderer_CreateFontsTexture(); + return ImGui_ImplSDLRenderer2_CreateFontsTexture(); } -void ImGui_ImplSDLRenderer_DestroyDeviceObjects() +void ImGui_ImplSDLRenderer2_DestroyDeviceObjects() { - ImGui_ImplSDLRenderer_DestroyFontsTexture(); + ImGui_ImplSDLRenderer2_DestroyFontsTexture(); } + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdlrenderer2.h b/third_party/imgui/backends/imgui_impl_sdlrenderer2.h new file mode 100644 index 00000000000..843850ff457 --- /dev/null +++ b/third_party/imgui/backends/imgui_impl_sdlrenderer2.h @@ -0,0 +1,39 @@ +// dear imgui: Renderer Backend for SDL_Renderer for SDL2 +// (Requires: SDL 2.0.17+) + +// Note how SDL_Renderer is an _optional_ component of SDL2. +// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. +// If your application will want to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and +// it might be difficult to step out of those boundaries. + +// Implemented features: +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#ifndef IMGUI_DISABLE +#include "imgui.h" // IMGUI_IMPL_API + +struct SDL_Renderer; + +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data); + +// Called by Init/NewFrame/Shutdown +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture(); +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdlrenderer3.cpp b/third_party/imgui/backends/imgui_impl_sdlrenderer3.cpp new file mode 100644 index 00000000000..01cd1a30861 --- /dev/null +++ b/third_party/imgui/backends/imgui_impl_sdlrenderer3.cpp @@ -0,0 +1,260 @@ +// dear imgui: Renderer Backend for SDL_Renderer for SDL3 +// (Requires: SDL 3.0.0+) + +// Note how SDL_Renderer is an _optional_ component of SDL3. +// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. +// If your application will want to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and +// it might be difficult to step out of those boundaries. + +// Implemented features: +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// 2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly. +// 2023-05-30: Initial version. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_sdlrenderer3.h" +#include // intptr_t + +// Clang warnings with -Weverything +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness +#endif + +// SDL +#include +#if !SDL_VERSION_ATLEAST(3,0,0) +#error This backend requires SDL 3.0.0+ +#endif + +// SDL_Renderer data +struct ImGui_ImplSDLRenderer3_Data +{ + SDL_Renderer* SDLRenderer; + SDL_Texture* FontTexture; + ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +static ImGui_ImplSDLRenderer3_Data* ImGui_ImplSDLRenderer3_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + +// Functions +bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer) +{ + ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); + + // Setup backend capabilities flags + ImGui_ImplSDLRenderer3_Data* bd = IM_NEW(ImGui_ImplSDLRenderer3_Data)(); + io.BackendRendererUserData = (void*)bd; + io.BackendRendererName = "imgui_impl_sdlrenderer3"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + + bd->SDLRenderer = renderer; + + return true; +} + +void ImGui_ImplSDLRenderer3_Shutdown() +{ + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + + ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); + + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + IM_DELETE(bd); +} + +static void ImGui_ImplSDLRenderer3_SetupRenderState() +{ + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + + // Clear out any viewports and cliprect set by the user + // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. + SDL_SetRenderViewport(bd->SDLRenderer, nullptr); + SDL_SetRenderClipRect(bd->SDLRenderer, nullptr); +} + +void ImGui_ImplSDLRenderer3_NewFrame() +{ + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDLRenderer3_Init()?"); + + if (!bd->FontTexture) + ImGui_ImplSDLRenderer3_CreateDeviceObjects(); +} + +void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data) +{ + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + + // If there's a scale factor set by the user, use that instead + // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass + // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. + float rsx = 1.0f; + float rsy = 1.0f; + SDL_GetRenderScale(bd->SDLRenderer, &rsx, &rsy); + ImVec2 render_scale; + render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; + render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; + + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); + int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); + if (fb_width == 0 || fb_height == 0) + return; + + // Backup SDL_Renderer state that will be modified to restore it afterwards + struct BackupSDLRendererState + { + SDL_Rect Viewport; + bool ViewportEnabled; + bool ClipEnabled; + SDL_Rect ClipRect; + }; + BackupSDLRendererState old = {}; + old.ViewportEnabled = SDL_RenderViewportSet(bd->SDLRenderer) == SDL_TRUE; + old.ClipEnabled = SDL_RenderClipEnabled(bd->SDLRenderer) == SDL_TRUE; + SDL_GetRenderViewport(bd->SDLRenderer, &old.Viewport); + SDL_GetRenderClipRect(bd->SDLRenderer, &old.ClipRect); + + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = render_scale; + + // Render command lists + ImGui_ImplSDLRenderer3_SetupRenderState(); + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; + const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + // User callback, registered via ImDrawList::AddCallback() + // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplSDLRenderer3_SetupRenderState(); + else + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } + if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } + if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; } + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + + SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) }; + SDL_SetRenderClipRect(bd->SDLRenderer, &r); + + const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos)); + const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv)); + const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+ + + // Bind texture, Draw + SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); + SDL_RenderGeometryRaw(bd->SDLRenderer, tex, + xy, (int)sizeof(ImDrawVert), + color, (int)sizeof(ImDrawVert), + uv, (int)sizeof(ImDrawVert), + cmd_list->VtxBuffer.Size - pcmd->VtxOffset, + idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx)); + } + } + } + + // Restore modified SDL_Renderer state + SDL_SetRenderViewport(bd->SDLRenderer, old.ViewportEnabled ? &old.Viewport : nullptr); + SDL_SetRenderClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : nullptr); +} + +// Called by Init/NewFrame/Shutdown +bool ImGui_ImplSDLRenderer3_CreateFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + + // Build texture atlas + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. + + // Upload texture to graphics system + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) + bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); + if (bd->FontTexture == nullptr) + { + SDL_Log("error creating texture"); + return false; + } + SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); + SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); + SDL_SetTextureScaleMode(bd->FontTexture, SDL_SCALEMODE_LINEAR); + + // Store our identifier + io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); + + return true; +} + +void ImGui_ImplSDLRenderer3_DestroyFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); + if (bd->FontTexture) + { + io.Fonts->SetTexID(0); + SDL_DestroyTexture(bd->FontTexture); + bd->FontTexture = nullptr; + } +} + +bool ImGui_ImplSDLRenderer3_CreateDeviceObjects() +{ + return ImGui_ImplSDLRenderer3_CreateFontsTexture(); +} + +void ImGui_ImplSDLRenderer3_DestroyDeviceObjects() +{ + ImGui_ImplSDLRenderer3_DestroyFontsTexture(); +} + +//----------------------------------------------------------------------------- + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_sdlrenderer3.h b/third_party/imgui/backends/imgui_impl_sdlrenderer3.h new file mode 100644 index 00000000000..dd05adfd421 --- /dev/null +++ b/third_party/imgui/backends/imgui_impl_sdlrenderer3.h @@ -0,0 +1,39 @@ +// dear imgui: Renderer Backend for SDL_Renderer for SDL3 +// (Requires: SDL 3.0.0+) + +// Note how SDL_Renderer is an _optional_ component of SDL3. +// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. +// If your application will want to render any non trivial amount of graphics other than UI, +// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and +// it might be difficult to step out of those boundaries. + +// Implemented features: +// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. + +// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +struct SDL_Renderer; + +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data); + +// Called by Init/NewFrame/Shutdown +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyFontsTexture(); +IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateDeviceObjects(); +IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_vulkan.cpp b/third_party/imgui/backends/imgui_impl_vulkan.cpp index aa6a3ddb956..a8962ecd252 100644 --- a/third_party/imgui/backends/imgui_impl_vulkan.cpp +++ b/third_party/imgui/backends/imgui_impl_vulkan.cpp @@ -2,18 +2,28 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// Missing features: -// [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914 +// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// 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. -// 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 +// Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. +// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. +// To build this on 32-bit systems and support texture changes: +// - [Solution 1] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'ImTextureID=ImU64' (this is what we do in our .vcxproj files) +// - [Solution 2] IDE/msbuild: in "Properties/C++/Preprocessor Definitions" add 'IMGUI_USER_CONFIG="my_imgui_config.h"' and inside 'my_imgui_config.h' add '#define ImTextureID ImU64' and as many other options as you like. +// - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) +// - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in our batch files) // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering backend in your engine/app. @@ -23,6 +33,23 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering. +// 2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure. +// 2024-01-19: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236) +// 2024-01-11: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size (#3957). Fixed MinAllocationSize handing (#7189). +// 2024-01-03: Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous "best practice" validation layer. (#7189, #4238) +// 2024-01-03: Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as we don't reset them. +// 2023-11-29: Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs vkDestroyCommandPool(). (#7075) +// 2023-11-10: *BREAKING CHANGE*: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own command-buffer to upload fonts. +// *BREAKING CHANGE*: Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unecessary as we create and destroy those objects in the backend. +// ImGui_ImplVulkan_CreateFontsTexture() is automatically called by NewFrame() the first time. +// You can call ImGui_ImplVulkan_CreateFontsTexture() again to recreate the font atlas texture. +// Added ImGui_ImplVulkan_DestroyFontsTexture() but you probably never need to call this. +// 2023-07-04: Vulkan: Added optional support for VK_KHR_dynamic_rendering. User needs to set init_info->UseDynamicRendering = true and init_info->ColorAttachmentFormat. +// 2023-01-02: Vulkan: Fixed sampler passed to ImGui_ImplVulkan_AddTexture() not being honored + removed a bunch of duplicate code. +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. +// 2022-10-04: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symetry. (#914, #5738). +// 2022-01-20: Vulkan: Added support for ImTextureID as VkDescriptorSet. User need to call ImGui_ImplVulkan_AddTexture(). Building for 32-bit targets requires '#define ImTextureID ImU64'. (#914). // 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame. // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2021-03-22: Vulkan: Fix mapped memory validation error when buffer sizes are not multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize. @@ -54,70 +81,28 @@ // 2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources. // 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active. +#include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_vulkan.h" #include +#ifndef IM_MAX +#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B)) +#endif -// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() -// [Please zero-clear before use!] -struct ImGui_ImplVulkanH_FrameRenderBuffers -{ - VkDeviceMemory VertexBufferMemory; - VkDeviceMemory IndexBufferMemory; - VkDeviceSize VertexBufferSize; - VkDeviceSize IndexBufferSize; - VkBuffer VertexBuffer; - VkBuffer IndexBuffer; -}; - -// Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers -// [Please zero-clear before use!] -struct ImGui_ImplVulkanH_WindowRenderBuffers -{ - uint32_t Index; - uint32_t Count; - ImGui_ImplVulkanH_FrameRenderBuffers* FrameRenderBuffers; -}; - -// Vulkan data -struct ImGui_ImplVulkan_Data -{ - ImGui_ImplVulkan_InitInfo VulkanInitInfo; - VkRenderPass RenderPass; - VkDeviceSize BufferMemoryAlignment; - VkPipelineCreateFlags PipelineCreateFlags; - VkDescriptorSetLayout DescriptorSetLayout; - VkPipelineLayout PipelineLayout; - VkDescriptorSet DescriptorSet; - VkPipeline Pipeline; - uint32_t Subpass; - VkShaderModule ShaderModuleVert; - VkShaderModule ShaderModuleFrag; - - // Font data - VkSampler FontSampler; - VkDeviceMemory FontMemory; - VkImage FontImage; - VkImageView FontView; - VkDeviceMemory UploadBufferMemory; - VkBuffer UploadBuffer; - - // Render buffers - ImGui_ImplVulkanH_WindowRenderBuffers MainWindowRenderBuffers; - - ImGui_ImplVulkan_Data() - { - memset(this, 0, sizeof(*this)); - BufferMemoryAlignment = 256; - } -}; +// Visual Studio warnings +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#endif // Forward Declarations +struct ImGui_ImplVulkan_FrameRenderBuffers; +struct ImGui_ImplVulkan_WindowRenderBuffers; bool ImGui_ImplVulkan_CreateDeviceObjects(); void ImGui_ImplVulkan_DestroyDeviceObjects(); +void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); +void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator); -void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); @@ -133,6 +118,7 @@ static bool g_FunctionsLoaded = true; IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateCommandBuffers) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkBeginCommandBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindBufferMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindImageMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindDescriptorSets) \ @@ -175,8 +161,10 @@ static bool g_FunctionsLoaded = true; IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySurfaceKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySwapchainKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDeviceWaitIdle) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkEndCommandBuffer) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFlushMappedMemoryRanges) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeCommandBuffers) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetBufferMemoryRequirements) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetImageMemoryRequirements) \ @@ -186,6 +174,9 @@ static bool g_FunctionsLoaded = true; IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfacePresentModesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetSwapchainImagesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkMapMemory) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueSubmit) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueWaitIdle) \ + IMGUI_VULKAN_FUNC_MAP_MACRO(vkResetCommandPool) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkUnmapMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets) @@ -195,11 +186,68 @@ IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_DEF) #undef IMGUI_VULKAN_FUNC_DEF #endif // VK_NO_PROTOTYPES +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +static PFN_vkCmdBeginRenderingKHR ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR; +static PFN_vkCmdEndRenderingKHR ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR; +#endif + +// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData() +// [Please zero-clear before use!] +struct ImGui_ImplVulkan_FrameRenderBuffers +{ + VkDeviceMemory VertexBufferMemory; + VkDeviceMemory IndexBufferMemory; + VkDeviceSize VertexBufferSize; + VkDeviceSize IndexBufferSize; + VkBuffer VertexBuffer; + VkBuffer IndexBuffer; +}; + +// Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers +// [Please zero-clear before use!] +struct ImGui_ImplVulkan_WindowRenderBuffers +{ + uint32_t Index; + uint32_t Count; + ImGui_ImplVulkan_FrameRenderBuffers* FrameRenderBuffers; +}; + +// Vulkan data +struct ImGui_ImplVulkan_Data +{ + ImGui_ImplVulkan_InitInfo VulkanInitInfo; + VkDeviceSize BufferMemoryAlignment; + VkPipelineCreateFlags PipelineCreateFlags; + VkDescriptorSetLayout DescriptorSetLayout; + VkPipelineLayout PipelineLayout; + VkPipeline Pipeline; + VkShaderModule ShaderModuleVert; + VkShaderModule ShaderModuleFrag; + + // Font data + VkSampler FontSampler; + VkDeviceMemory FontMemory; + VkImage FontImage; + VkImageView FontView; + VkDescriptorSet FontDescriptorSet; + VkCommandPool FontCommandPool; + VkCommandBuffer FontCommandBuffer; + + // Render buffers for main window + ImGui_ImplVulkan_WindowRenderBuffers MainWindowRenderBuffers; + + ImGui_ImplVulkan_Data() + { + memset((void*)this, 0, sizeof(*this)); + BufferMemoryAlignment = 256; + } +}; + //----------------------------------------------------------------------------- // SHADERS //----------------------------------------------------------------------------- -// glsl_shader.vert, compiled with: +// backends/vulkan/glsl_shader.vert, compiled with: // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert /* #version 450 core @@ -263,7 +311,7 @@ static uint32_t __glsl_shader_vert_spv[] = 0x0000002d,0x0000002c,0x000100fd,0x00010038 }; -// glsl_shader.frag, compiled with: +// backends/vulkan/glsl_shader.frag, compiled with: // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag /* #version 450 core @@ -313,7 +361,7 @@ static uint32_t __glsl_shader_frag_spv[] = // FIXME: multi-context support is not tested and probably dysfunctional in this backend. static ImGui_ImplVulkan_Data* ImGui_ImplVulkan_GetBackendData() { - return ImGui::GetCurrentContext() ? (ImGui_ImplVulkan_Data*)ImGui::GetIO().BackendRendererUserData : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplVulkan_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } static uint32_t ImGui_ImplVulkan_MemoryType(VkMemoryPropertyFlags properties, uint32_t type_bits) @@ -338,7 +386,13 @@ static void check_vk_result(VkResult err) v->CheckVkResultFn(err); } -static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& p_buffer_size, size_t new_size, VkBufferUsageFlagBits usage) +// Same as IM_MEMALIGN(). 'alignment' must be a power of two. +static inline VkDeviceSize AlignBufferSize(VkDeviceSize size, VkDeviceSize alignment) +{ + return (size + alignment - 1) & ~(alignment - 1); +} + +static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& buffer_size, size_t new_size, VkBufferUsageFlagBits usage) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; @@ -348,10 +402,10 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory if (buffer_memory != VK_NULL_HANDLE) vkFreeMemory(v->Device, buffer_memory, v->Allocator); - VkDeviceSize vertex_buffer_size_aligned = ((new_size - 1) / bd->BufferMemoryAlignment + 1) * bd->BufferMemoryAlignment; + VkDeviceSize buffer_size_aligned = AlignBufferSize(IM_MAX(v->MinAllocationSize, new_size), bd->BufferMemoryAlignment); VkBufferCreateInfo buffer_info = {}; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - buffer_info.size = vertex_buffer_size_aligned; + buffer_info.size = buffer_size_aligned; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer); @@ -369,18 +423,16 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0); check_vk_result(err); - p_buffer_size = req.size; + buffer_size = buffer_size_aligned; } -static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkanH_FrameRenderBuffers* rb, int fb_width, int fb_height) +static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* rb, int fb_width, int fb_height) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - // Bind pipeline and descriptor sets: + // Bind pipeline: { vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - VkDescriptorSet desc_set[1] = { bd->DescriptorSet }; - vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, desc_set, 0, NULL); } // Bind Vertex And Index Buffer: @@ -433,34 +485,34 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm pipeline = bd->Pipeline; // Allocate array to store enough vertex/index buffers - ImGui_ImplVulkanH_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers; - if (wrb->FrameRenderBuffers == NULL) + ImGui_ImplVulkan_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers; + if (wrb->FrameRenderBuffers == nullptr) { wrb->Index = 0; wrb->Count = v->ImageCount; - wrb->FrameRenderBuffers = (ImGui_ImplVulkanH_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count); - memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count); + wrb->FrameRenderBuffers = (ImGui_ImplVulkan_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); + memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count); } IM_ASSERT(wrb->Count == v->ImageCount); wrb->Index = (wrb->Index + 1) % wrb->Count; - ImGui_ImplVulkanH_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; + ImGui_ImplVulkan_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; if (draw_data->TotalVtxCount > 0) { // Create or resize the vertex/index buffers - size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); - size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); + size_t vertex_size = AlignBufferSize(draw_data->TotalVtxCount * sizeof(ImDrawVert), bd->BufferMemoryAlignment); + size_t index_size = AlignBufferSize(draw_data->TotalIdxCount * sizeof(ImDrawIdx), bd->BufferMemoryAlignment); if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size) CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size) CreateOrResizeBuffer(rb->IndexBuffer, rb->IndexBufferMemory, rb->IndexBufferSize, index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); // Upload vertex/index data into a single contiguous GPU buffer - ImDrawVert* vtx_dst = NULL; - ImDrawIdx* idx_dst = NULL; - VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, rb->VertexBufferSize, 0, (void**)(&vtx_dst)); + ImDrawVert* vtx_dst = nullptr; + ImDrawIdx* idx_dst = nullptr; + VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)&vtx_dst); check_vk_result(err); - err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, rb->IndexBufferSize, 0, (void**)(&idx_dst)); + err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)&idx_dst); check_vk_result(err); for (int n = 0; n < draw_data->CmdListsCount; n++) { @@ -500,7 +552,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != NULL) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) @@ -531,6 +583,16 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm scissor.extent.height = (uint32_t)(clip_max.y - clip_min.y); vkCmdSetScissor(command_buffer, 0, 1, &scissor); + // Bind DescriptorSet with font or user texture + VkDescriptorSet desc_set[1] = { (VkDescriptorSet)pcmd->TextureId }; + if (sizeof(ImTextureID) < sizeof(ImU64)) + { + // We don't support texture switches if ImTextureID hasn't been redefined to be 64-bit. Do a flaky check that other textures haven't been used. + IM_ASSERT(pcmd->TextureId == (ImTextureID)bd->FontDescriptorSet); + desc_set[0] = bd->FontDescriptorSet; + } + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, bd->PipelineLayout, 0, 1, desc_set, 0, nullptr); + // Draw vkCmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0); } @@ -542,7 +604,7 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm // Note: at this point both vkCmdSetViewport() and vkCmdSetScissor() have been called. // Our last values will leak into user/application rendering IF: // - Your app uses a pipeline with VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR dynamic state - // - And you forgot to call vkCmdSetViewport() and vkCmdSetScissor() yourself to explicitely set that state. + // - And you forgot to call vkCmdSetViewport() and vkCmdSetScissor() yourself to explicitly set that state. // If you use VK_DYNAMIC_STATE_VIEWPORT or VK_DYNAMIC_STATE_SCISSOR you are responsible for setting the values before rendering. // In theory we should aim to backup/restore those values but I am not sure this is possible. // We perform a call to vkCmdSetScissor() to set back a full viewport which is likely to fix things for 99% users but technically this is not perfect. (See github #4644) @@ -550,19 +612,55 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm vkCmdSetScissor(command_buffer, 0, 1, &scissor); } -bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) +bool ImGui_ImplVulkan_CreateFontsTexture() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + VkResult err; + + // Destroy existing texture (if any) + if (bd->FontView || bd->FontImage || bd->FontMemory || bd->FontDescriptorSet) + { + vkQueueWaitIdle(v->Queue); + ImGui_ImplVulkan_DestroyFontsTexture(); + } + + // Create command pool/buffer + if (bd->FontCommandPool == VK_NULL_HANDLE) + { + VkCommandPoolCreateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + info.flags = 0; + info.queueFamilyIndex = v->QueueFamily; + vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->FontCommandPool); + } + if (bd->FontCommandBuffer == VK_NULL_HANDLE) + { + VkCommandBufferAllocateInfo info = {}; + info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + info.commandPool = bd->FontCommandPool; + info.commandBufferCount = 1; + err = vkAllocateCommandBuffers(v->Device, &info, &bd->FontCommandBuffer); + check_vk_result(err); + } + + // Start command buffer + { + err = vkResetCommandPool(v->Device, bd->FontCommandPool, 0); + check_vk_result(err); + VkCommandBufferBeginInfo begin_info = {}; + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + err = vkBeginCommandBuffer(bd->FontCommandBuffer, &begin_info); + check_vk_result(err); + } unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); size_t upload_size = width * height * 4 * sizeof(char); - VkResult err; - // Create the Image: { VkImageCreateInfo info = {}; @@ -585,7 +683,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) vkGetImageMemoryRequirements(v->Device, bd->FontImage, &req); VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alloc_info.allocationSize = req.size; + alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits); err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->FontMemory); check_vk_result(err); @@ -607,56 +705,46 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) check_vk_result(err); } - // Update the Descriptor Set: - { - VkDescriptorImageInfo desc_image[1] = {}; - desc_image[0].sampler = bd->FontSampler; - desc_image[0].imageView = bd->FontView; - desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - VkWriteDescriptorSet write_desc[1] = {}; - write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - write_desc[0].dstSet = bd->DescriptorSet; - write_desc[0].descriptorCount = 1; - write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - write_desc[0].pImageInfo = desc_image; - vkUpdateDescriptorSets(v->Device, 1, write_desc, 0, NULL); - } + // Create the Descriptor Set: + bd->FontDescriptorSet = (VkDescriptorSet)ImGui_ImplVulkan_AddTexture(bd->FontSampler, bd->FontView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // Create the Upload Buffer: + VkDeviceMemory upload_buffer_memory; + VkBuffer upload_buffer; { VkBufferCreateInfo buffer_info = {}; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.size = upload_size; buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &bd->UploadBuffer); + err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &upload_buffer); check_vk_result(err); VkMemoryRequirements req; - vkGetBufferMemoryRequirements(v->Device, bd->UploadBuffer, &req); + vkGetBufferMemoryRequirements(v->Device, upload_buffer, &req); bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alloc_info.allocationSize = req.size; + alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size); alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); - err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->UploadBufferMemory); + err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &upload_buffer_memory); check_vk_result(err); - err = vkBindBufferMemory(v->Device, bd->UploadBuffer, bd->UploadBufferMemory, 0); + err = vkBindBufferMemory(v->Device, upload_buffer, upload_buffer_memory, 0); check_vk_result(err); } // Upload to Buffer: { - char* map = NULL; - err = vkMapMemory(v->Device, bd->UploadBufferMemory, 0, upload_size, 0, (void**)(&map)); + char* map = nullptr; + err = vkMapMemory(v->Device, upload_buffer_memory, 0, upload_size, 0, (void**)(&map)); check_vk_result(err); memcpy(map, pixels, upload_size); VkMappedMemoryRange range[1] = {}; range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; - range[0].memory = bd->UploadBufferMemory; + range[0].memory = upload_buffer_memory; range[0].size = upload_size; err = vkFlushMappedMemoryRanges(v->Device, 1, range); check_vk_result(err); - vkUnmapMemory(v->Device, bd->UploadBufferMemory); + vkUnmapMemory(v->Device, upload_buffer_memory); } // Copy to Image: @@ -672,7 +760,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_barrier[0].subresourceRange.levelCount = 1; copy_barrier[0].subresourceRange.layerCount = 1; - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, copy_barrier); + vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; @@ -680,7 +768,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) region.imageExtent.width = width; region.imageExtent.height = height; region.imageExtent.depth = 1; - vkCmdCopyBufferToImage(command_buffer, bd->UploadBuffer, bd->FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + vkCmdCopyBufferToImage(bd->FontCommandBuffer, upload_buffer, bd->FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); VkImageMemoryBarrier use_barrier[1] = {}; use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; @@ -694,15 +782,50 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; use_barrier[0].subresourceRange.levelCount = 1; use_barrier[0].subresourceRange.layerCount = 1; - vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, use_barrier); + vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier); } // Store our identifier - io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontImage); + io.Fonts->SetTexID((ImTextureID)bd->FontDescriptorSet); + + // End command buffer + VkSubmitInfo end_info = {}; + end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + end_info.commandBufferCount = 1; + end_info.pCommandBuffers = &bd->FontCommandBuffer; + err = vkEndCommandBuffer(bd->FontCommandBuffer); + check_vk_result(err); + err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE); + check_vk_result(err); + + err = vkQueueWaitIdle(v->Queue); + check_vk_result(err); + + vkDestroyBuffer(v->Device, upload_buffer, v->Allocator); + vkFreeMemory(v->Device, upload_buffer_memory, v->Allocator); return true; } +// You probably never need to call this, as it is called by ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_Shutdown(). +void ImGui_ImplVulkan_DestroyFontsTexture() +{ + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + + if (bd->FontDescriptorSet) + { + ImGui_ImplVulkan_RemoveTexture(bd->FontDescriptorSet); + bd->FontDescriptorSet = VK_NULL_HANDLE; + io.Fonts->SetTexID(0); + } + + if (bd->FontView) { vkDestroyImageView(v->Device, bd->FontView, v->Allocator); bd->FontView = VK_NULL_HANDLE; } + if (bd->FontImage) { vkDestroyImage(v->Device, bd->FontImage, v->Allocator); bd->FontImage = VK_NULL_HANDLE; } + if (bd->FontMemory) { vkFreeMemory(v->Device, bd->FontMemory, v->Allocator); bd->FontMemory = VK_NULL_HANDLE; } +} + static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator) { // Create the shader modules @@ -727,71 +850,6 @@ static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAlloca } } -static void ImGui_ImplVulkan_CreateFontSampler(VkDevice device, const VkAllocationCallbacks* allocator) -{ - ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - if (bd->FontSampler) - return; - - VkSamplerCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - info.magFilter = VK_FILTER_LINEAR; - info.minFilter = VK_FILTER_LINEAR; - info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; - info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; - info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; - info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; - info.minLod = -1000; - info.maxLod = 1000; - info.maxAnisotropy = 1.0f; - VkResult err = vkCreateSampler(device, &info, allocator, &bd->FontSampler); - check_vk_result(err); -} - -static void ImGui_ImplVulkan_CreateDescriptorSetLayout(VkDevice device, const VkAllocationCallbacks* allocator) -{ - ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - if (bd->DescriptorSetLayout) - return; - - ImGui_ImplVulkan_CreateFontSampler(device, allocator); - VkSampler sampler[1] = { bd->FontSampler }; - VkDescriptorSetLayoutBinding binding[1] = {}; - binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - binding[0].descriptorCount = 1; - binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - binding[0].pImmutableSamplers = sampler; - VkDescriptorSetLayoutCreateInfo info = {}; - info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - info.bindingCount = 1; - info.pBindings = binding; - VkResult err = vkCreateDescriptorSetLayout(device, &info, allocator, &bd->DescriptorSetLayout); - check_vk_result(err); -} - -static void ImGui_ImplVulkan_CreatePipelineLayout(VkDevice device, const VkAllocationCallbacks* allocator) -{ - ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - if (bd->PipelineLayout) - return; - - // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix - ImGui_ImplVulkan_CreateDescriptorSetLayout(device, allocator); - VkPushConstantRange push_constants[1] = {}; - push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; - push_constants[0].offset = sizeof(float) * 0; - push_constants[0].size = sizeof(float) * 4; - VkDescriptorSetLayout set_layout[1] = { bd->DescriptorSetLayout }; - VkPipelineLayoutCreateInfo layout_info = {}; - layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - layout_info.setLayoutCount = 1; - layout_info.pSetLayouts = set_layout; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = push_constants; - VkResult err = vkCreatePipelineLayout(device, &layout_info, allocator, &bd->PipelineLayout); - check_vk_result(err); -} - static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationCallbacks* allocator, VkPipelineCache pipelineCache, VkRenderPass renderPass, VkSampleCountFlagBits MSAASamples, VkPipeline* pipeline, uint32_t subpass) { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); @@ -815,15 +873,15 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC attribute_desc[0].location = 0; attribute_desc[0].binding = binding_desc[0].binding; attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT; - attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos); + attribute_desc[0].offset = offsetof(ImDrawVert, pos); attribute_desc[1].location = 1; attribute_desc[1].binding = binding_desc[0].binding; attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT; - attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv); + attribute_desc[1].offset = offsetof(ImDrawVert, uv); attribute_desc[2].location = 2; attribute_desc[2].binding = binding_desc[0].binding; attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM; - attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col); + attribute_desc[2].offset = offsetof(ImDrawVert, col); VkPipelineVertexInputStateCreateInfo vertex_info = {}; vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; @@ -876,8 +934,6 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states); dynamic_state.pDynamicStates = dynamic_states; - ImGui_ImplVulkan_CreatePipelineLayout(device, allocator); - VkGraphicsPipelineCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; info.flags = bd->PipelineCreateFlags; @@ -894,6 +950,17 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC info.layout = bd->PipelineLayout; info.renderPass = renderPass; info.subpass = subpass; + +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + if (bd->VulkanInitInfo.UseDynamicRendering) + { + IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR"); + IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be NULL"); + info.pNext = &bd->VulkanInitInfo.PipelineRenderingCreateInfo; + info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. + } +#endif + VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &info, allocator, pipeline); check_vk_result(err); } @@ -906,6 +973,7 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() if (!bd->FontSampler) { + // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. VkSamplerCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; info.magFilter = VK_FILTER_LINEAR; @@ -923,12 +991,10 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() if (!bd->DescriptorSetLayout) { - VkSampler sampler[1] = {bd->FontSampler}; VkDescriptorSetLayoutBinding binding[1] = {}; binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; binding[0].descriptorCount = 1; binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - binding[0].pImmutableSamplers = sampler; VkDescriptorSetLayoutCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; info.bindingCount = 1; @@ -937,17 +1003,6 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() check_vk_result(err); } - // Create Descriptor Set: - { - VkDescriptorSetAllocateInfo alloc_info = {}; - alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - alloc_info.descriptorPool = v->DescriptorPool; - alloc_info.descriptorSetCount = 1; - alloc_info.pSetLayouts = &bd->DescriptorSetLayout; - err = vkAllocateDescriptorSets(v->Device, &alloc_info, &bd->DescriptorSet); - check_vk_result(err); - } - if (!bd->PipelineLayout) { // Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full 3d projection matrix @@ -966,39 +1021,22 @@ bool ImGui_ImplVulkan_CreateDeviceObjects() check_vk_result(err); } - ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, bd->RenderPass, v->MSAASamples, &bd->Pipeline, bd->Subpass); + ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, &bd->Pipeline, v->Subpass); return true; } -void ImGui_ImplVulkan_DestroyFontUploadObjects() -{ - ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; - if (bd->UploadBuffer) - { - vkDestroyBuffer(v->Device, bd->UploadBuffer, v->Allocator); - bd->UploadBuffer = VK_NULL_HANDLE; - } - if (bd->UploadBufferMemory) - { - vkFreeMemory(v->Device, bd->UploadBufferMemory, v->Allocator); - bd->UploadBufferMemory = VK_NULL_HANDLE; - } -} - void ImGui_ImplVulkan_DestroyDeviceObjects() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; - ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); - ImGui_ImplVulkan_DestroyFontUploadObjects(); + ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); + ImGui_ImplVulkan_DestroyFontsTexture(); + if (bd->FontCommandBuffer) { vkFreeCommandBuffers(v->Device, bd->FontCommandPool, 1, &bd->FontCommandBuffer); bd->FontCommandBuffer = VK_NULL_HANDLE; } + if (bd->FontCommandPool) { vkDestroyCommandPool(v->Device, bd->FontCommandPool, v->Allocator); bd->FontCommandPool = VK_NULL_HANDLE; } if (bd->ShaderModuleVert) { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; } if (bd->ShaderModuleFrag) { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; } - if (bd->FontView) { vkDestroyImageView(v->Device, bd->FontView, v->Allocator); bd->FontView = VK_NULL_HANDLE; } - if (bd->FontImage) { vkDestroyImage(v->Device, bd->FontImage, v->Allocator); bd->FontImage = VK_NULL_HANDLE; } - if (bd->FontMemory) { vkFreeMemory(v->Device, bd->FontMemory, v->Allocator); bd->FontMemory = VK_NULL_HANDLE; } if (bd->FontSampler) { vkDestroySampler(v->Device, bd->FontSampler, v->Allocator); bd->FontSampler = VK_NULL_HANDLE; } if (bd->DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; } if (bd->PipelineLayout) { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; } @@ -1014,24 +1052,45 @@ bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const ch #ifdef VK_NO_PROTOTYPES #define IMGUI_VULKAN_FUNC_LOAD(func) \ func = reinterpret_cast(loader_func(#func, user_data)); \ - if (func == NULL) \ + if (func == nullptr) \ return false; IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_LOAD) #undef IMGUI_VULKAN_FUNC_LOAD + +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + // Manually load those two (see #5446) + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(loader_func("vkCmdBeginRenderingKHR", user_data)); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(loader_func("vkCmdEndRenderingKHR", user_data)); +#endif #else IM_UNUSED(loader_func); IM_UNUSED(user_data); #endif + g_FunctionsLoaded = true; return true; } -bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) +bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); + if (info->UseDynamicRendering) + { +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +#ifndef VK_NO_PROTOTYPES + ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast(vkGetInstanceProcAddr(info->Instance, "vkCmdBeginRenderingKHR")); + ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast(vkGetInstanceProcAddr(info->Instance, "vkCmdEndRenderingKHR")); +#endif + IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR != nullptr); + IM_ASSERT(ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR != nullptr); +#else + IM_ASSERT(0 && "Can't use dynamic rendering when neither VK_VERSION_1_3 or VK_KHR_dynamic_rendering is defined."); +#endif + } + ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!"); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); // Setup backend capabilities flags ImGui_ImplVulkan_Data* bd = IM_NEW(ImGui_ImplVulkan_Data)(); @@ -1046,11 +1105,10 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend IM_ASSERT(info->DescriptorPool != VK_NULL_HANDLE); IM_ASSERT(info->MinImageCount >= 2); IM_ASSERT(info->ImageCount >= info->MinImageCount); - IM_ASSERT(render_pass != VK_NULL_HANDLE); + if (info->UseDynamicRendering == false) + IM_ASSERT(info->RenderPass != VK_NULL_HANDLE); bd->VulkanInitInfo = *info; - bd->RenderPass = render_pass; - bd->Subpass = info->Subpass; ImGui_ImplVulkan_CreateDeviceObjects(); @@ -1060,20 +1118,23 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend void ImGui_ImplVulkan_Shutdown() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - IM_ASSERT(bd != NULL && "No renderer backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); ImGui_ImplVulkan_DestroyDeviceObjects(); - io.BackendRendererName = NULL; - io.BackendRendererUserData = NULL; + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; IM_DELETE(bd); } void ImGui_ImplVulkan_NewFrame() { ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplVulkan_Init()?"); - IM_UNUSED(bd); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplVulkan_Init()?"); + + if (!bd->FontDescriptorSet) + ImGui_ImplVulkan_CreateFontsTexture(); } void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) @@ -1086,10 +1147,72 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; VkResult err = vkDeviceWaitIdle(v->Device); check_vk_result(err); - ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); + ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); bd->VulkanInitInfo.MinImageCount = min_image_count; } +// Register a texture +// FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem, please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. +VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + + // Create Descriptor Set: + VkDescriptorSet descriptor_set; + { + VkDescriptorSetAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc_info.descriptorPool = v->DescriptorPool; + alloc_info.descriptorSetCount = 1; + alloc_info.pSetLayouts = &bd->DescriptorSetLayout; + VkResult err = vkAllocateDescriptorSets(v->Device, &alloc_info, &descriptor_set); + check_vk_result(err); + } + + // Update the Descriptor Set: + { + VkDescriptorImageInfo desc_image[1] = {}; + desc_image[0].sampler = sampler; + desc_image[0].imageView = image_view; + desc_image[0].imageLayout = image_layout; + VkWriteDescriptorSet write_desc[1] = {}; + write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write_desc[0].dstSet = descriptor_set; + write_desc[0].descriptorCount = 1; + write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + write_desc[0].pImageInfo = desc_image; + vkUpdateDescriptorSets(v->Device, 1, write_desc, 0, nullptr); + } + return descriptor_set; +} + +void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set) +{ + ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); + ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; + vkFreeDescriptorSets(v->Device, v->DescriptorPool, 1, &descriptor_set); +} + +void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +{ + if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } + if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } + if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } + if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; } + buffers->VertexBufferSize = 0; + buffers->IndexBufferSize = 0; +} + +void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) +{ + for (uint32_t n = 0; n < buffers->Count; n++) + ImGui_ImplVulkan_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator); + IM_FREE(buffers->FrameRenderBuffers); + buffers->FrameRenderBuffers = nullptr; + buffers->Index = 0; + buffers->Count = 0; +} //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers @@ -1110,7 +1233,7 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); - IM_ASSERT(request_formats != NULL); + IM_ASSERT(request_formats != nullptr); IM_ASSERT(request_formats_count > 0); // Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation @@ -1118,7 +1241,7 @@ VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physic // Additionally several new color spaces were introduced with Vulkan Spec v1.0.40, // hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used. uint32_t avail_count; - vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, NULL); + vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, nullptr); ImVector avail_format; avail_format.resize((int)avail_count); vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data); @@ -1155,12 +1278,12 @@ VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physic VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); - IM_ASSERT(request_modes != NULL); + IM_ASSERT(request_modes != nullptr); IM_ASSERT(request_modes_count > 0); // Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory uint32_t avail_count = 0; - vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, NULL); + vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, nullptr); ImVector avail_modes; avail_modes.resize((int)avail_count); vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &avail_count, avail_modes.Data); @@ -1178,19 +1301,17 @@ VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_d void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) { IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); - (void)physical_device; - (void)allocator; + IM_UNUSED(physical_device); // Create Command Buffers VkResult err; for (uint32_t i = 0; i < wd->ImageCount; i++) { ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; - ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i]; { VkCommandPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; - info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + info.flags = 0; info.queueFamilyIndex = queue_family; err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool); check_vk_result(err); @@ -1211,6 +1332,11 @@ void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_devi err = vkCreateFence(device, &info, allocator, &fd->Fence); check_vk_result(err); } + } + + for (uint32_t i = 0; i < wd->SemaphoreCount; i++) + { + ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i]; { VkSemaphoreCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; @@ -1246,14 +1372,13 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. // Destroy old Framebuffer for (uint32_t i = 0; i < wd->ImageCount; i++) - { ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); + for (uint32_t i = 0; i < wd->SemaphoreCount; i++) ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); - } IM_FREE(wd->Frames); IM_FREE(wd->FrameSemaphores); - wd->Frames = NULL; - wd->FrameSemaphores = NULL; + wd->Frames = nullptr; + wd->FrameSemaphores = nullptr; wd->ImageCount = 0; if (wd->RenderPass) vkDestroyRenderPass(device, wd->RenderPass, allocator); @@ -1300,7 +1425,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V } err = vkCreateSwapchainKHR(device, &info, allocator, &wd->Swapchain); check_vk_result(err); - err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, NULL); + err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, nullptr); check_vk_result(err); VkImage backbuffers[16] = {}; IM_ASSERT(wd->ImageCount >= min_image_count); @@ -1308,11 +1433,12 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers); check_vk_result(err); - IM_ASSERT(wd->Frames == NULL); + IM_ASSERT(wd->Frames == nullptr && wd->FrameSemaphores == nullptr); + wd->SemaphoreCount = wd->ImageCount + 1; wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount); - wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->ImageCount); + wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->SemaphoreCount); memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount); - memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->ImageCount); + memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount); for (uint32_t i = 0; i < wd->ImageCount; i++) wd->Frames[i].Backbuffer = backbuffers[i]; } @@ -1320,6 +1446,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V vkDestroySwapchainKHR(device, old_swapchain, allocator); // Create the Render Pass + if (wd->UseDynamicRendering == false) { VkAttachmentDescription attachment = {}; attachment.format = wd->SurfaceFormat.format; @@ -1357,7 +1484,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V // We do not create a pipeline by default as this is also used by examples' main.cpp, // but secondary viewport in multi-viewport mode may want to create one with: - //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, bd->Subpass); + //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, v->Subpass); } // Create The Image Views @@ -1382,6 +1509,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V } // Create Framebuffer + if (wd->UseDynamicRendering == false) { VkImageView attachment[1]; VkFramebufferCreateInfo info = {}; @@ -1417,14 +1545,13 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui //vkQueueWaitIdle(bd->Queue); for (uint32_t i = 0; i < wd->ImageCount; i++) - { ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); + for (uint32_t i = 0; i < wd->SemaphoreCount; i++) ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); - } IM_FREE(wd->Frames); IM_FREE(wd->FrameSemaphores); - wd->Frames = NULL; - wd->FrameSemaphores = NULL; + wd->Frames = nullptr; + wd->FrameSemaphores = nullptr; vkDestroyPipeline(device, wd->Pipeline, allocator); vkDestroyRenderPass(device, wd->RenderPass, allocator); vkDestroySwapchainKHR(device, wd->Swapchain, allocator); @@ -1453,22 +1580,6 @@ void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; } -void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) -{ - if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; } - if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; } - if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; } - if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; } - buffers->VertexBufferSize = 0; - buffers->IndexBufferSize = 0; -} +//----------------------------------------------------------------------------- -void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) -{ - for (uint32_t n = 0; n < buffers->Count; n++) - ImGui_ImplVulkanH_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator); - IM_FREE(buffers->FrameRenderBuffers); - buffers->FrameRenderBuffers = NULL; - buffers->Index = 0; - buffers->Count = 0; -} +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_vulkan.h b/third_party/imgui/backends/imgui_impl_vulkan.h index c770d0c1e4e..f77fc235ba6 100644 --- a/third_party/imgui/backends/imgui_impl_vulkan.h +++ b/third_party/imgui/backends/imgui_impl_vulkan.h @@ -2,18 +2,23 @@ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) // Implemented features: -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. -// Missing features: -// [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914 +// [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// 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. -// 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 +// Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. +// See imgui_impl_vulkan.cpp file for details. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ +// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // You will use those if you want to use this rendering backend in your engine/app. @@ -22,6 +27,7 @@ // Read comments in imgui_impl_vulkan.h. #pragma once +#ifndef IMGUI_DISABLE #include "imgui.h" // IMGUI_IMPL_API // [Configuration] in order to use a custom Vulkan function loader: @@ -40,9 +46,20 @@ #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) #define VK_NO_PROTOTYPES #endif +#if defined(VK_USE_PLATFORM_WIN32_KHR) && !defined(NOMINMAX) +#define NOMINMAX #include +#else +#include +#endif +#if defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering) +#define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING +#endif // Initialization data, for ImGui_ImplVulkan_Init() +// - VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, +// and must contain a pool size large enough to hold an ImGui VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptor. +// - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure. // [Please zero-clear before use!] struct ImGui_ImplVulkan_InitInfo { @@ -51,28 +68,47 @@ struct ImGui_ImplVulkan_InitInfo VkDevice Device; uint32_t QueueFamily; VkQueue Queue; + VkDescriptorPool DescriptorPool; // See requirements in note above + VkRenderPass RenderPass; // Ignored if using dynamic rendering + uint32_t MinImageCount; // >= 2 + uint32_t ImageCount; // >= MinImageCount + VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT + + // (Optional) VkPipelineCache PipelineCache; - VkDescriptorPool DescriptorPool; uint32_t Subpass; - uint32_t MinImageCount; // >= 2 - uint32_t ImageCount; // >= MinImageCount - VkSampleCountFlagBits MSAASamples; // >= VK_SAMPLE_COUNT_1_BIT + + // (Optional) Dynamic Rendering + // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. + bool UseDynamicRendering; +#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING + VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo; +#endif + + // (Optional) Allocation, Debugging const VkAllocationCallbacks* Allocator; void (*CheckVkResultFn)(VkResult err); + VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory. }; // Called by user code -IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); -IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); -IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); -IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); -IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); -IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); -IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) +IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info); +IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); +IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); +IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontsTexture(); +IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) + +// Register a texture (VkDescriptorSet == ImTextureID) +// FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem +// Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. +IMGUI_IMPL_API VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout); +IMGUI_IMPL_API void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set); // Optional: load Vulkan functions with a custom function loader // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES -IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = NULL); +IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr); //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers @@ -81,8 +117,8 @@ IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loade // You probably do NOT need to use or care about those functions. // Those functions only exist because: // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. -// 2) the upcoming multi-viewport feature will need them internally. -// Generally we avoid exposing any kind of superfluous high-level helpers in the backends, +// 2) the multi-viewport / platform window implementation needs them internally. +// Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, // but it is too much code to duplicate everywhere so we exceptionally expose them. // // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). @@ -131,19 +167,22 @@ struct ImGui_ImplVulkanH_Window VkPresentModeKHR PresentMode; VkRenderPass RenderPass; VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo + bool UseDynamicRendering; bool ClearEnable; VkClearValue ClearValue; uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) + uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) ImGui_ImplVulkanH_Frame* Frames; ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; ImGui_ImplVulkanH_Window() { - memset(this, 0, sizeof(*this)); - PresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR; + memset((void*)this, 0, sizeof(*this)); + PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this. ClearEnable = true; } }; +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_wgpu.cpp b/third_party/imgui/backends/imgui_impl_wgpu.cpp index 072f2549734..618dbb4ccb8 100644 --- a/third_party/imgui/backends/imgui_impl_wgpu.cpp +++ b/third_party/imgui/backends/imgui_impl_wgpu.cpp @@ -4,17 +4,31 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240) +// 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes. +// 2024-01-22: Fixed pipeline layout leak. (#7245) +// 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults. +// 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602) +// 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V. +// 2023-04-11: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). +// 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470) +// 2022-11-24: Fixed validation error with default depth buffer settings. +// 2022-11-10: Fixed rendering when a depth buffer is enabled. Added 'WGPUTextureFormat depth_format' parameter to ImGui_ImplWGPU_Init(). +// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer(). -// 2021-08-24: Fix for latest specs. +// 2021-08-24: Fixed for latest specs. // 2021-05-24: Add support for draw_data->FramebufferScale. // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92). @@ -22,37 +36,27 @@ // 2021-01-28: Initial version. #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_wgpu.h" #include #include -#define HAS_EMSCRIPTEN_VERSION(major, minor, tiny) (__EMSCRIPTEN_major__ > (major) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ > (minor)) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ == (minor) && __EMSCRIPTEN_tiny__ >= (tiny))) - -#if defined(__EMSCRIPTEN__) && !HAS_EMSCRIPTEN_VERSION(2, 0, 20) -#error "Requires at least emscripten 2.0.20" -#endif - // Dear ImGui prototypes from imgui_internal.h extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0); +#define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro). // WebGPU data -static WGPUDevice g_wgpuDevice = NULL; -static WGPUQueue g_defaultQueue = NULL; -static WGPUTextureFormat g_renderTargetFormat = WGPUTextureFormat_Undefined; -static WGPURenderPipeline g_pipelineState = NULL; - struct RenderResources { - WGPUTexture FontTexture; // Font texture - WGPUTextureView FontTextureView; // Texture view for font texture - WGPUSampler Sampler; // Sampler for the font texture - WGPUBuffer Uniforms; // Shader uniforms - WGPUBindGroup CommonBindGroup; // Resources bind-group to bind the common resources to pipeline - ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map) - WGPUBindGroup ImageBindGroup; // Default font-resource of Dear ImGui - WGPUBindGroupLayout ImageBindGroupLayout; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM + WGPUTexture FontTexture = nullptr; // Font texture + WGPUTextureView FontTextureView = nullptr; // Texture view for font texture + WGPUSampler Sampler = nullptr; // Sampler for the font texture + WGPUBuffer Uniforms = nullptr; // Shader uniforms + WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline + ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map) + WGPUBindGroup ImageBindGroup = nullptr; // Default font-resource of Dear ImGui + WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM }; -static RenderResources g_resources; struct FrameResources { @@ -63,186 +67,158 @@ struct FrameResources int IndexBufferSize; int VertexBufferSize; }; -static FrameResources* g_pFrameResources = NULL; -static unsigned int g_numFramesInFlight = 0; -static unsigned int g_frameIndex = UINT_MAX; struct Uniforms { float MVP[4][4]; + float Gamma; +}; + +struct ImGui_ImplWGPU_Data +{ + ImGui_ImplWGPU_InitInfo initInfo; + WGPUDevice wgpuDevice = nullptr; + WGPUQueue defaultQueue = nullptr; + WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined; + WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined; + WGPURenderPipeline pipelineState = nullptr; + + RenderResources renderResources; + FrameResources* pFrameResources = nullptr; + unsigned int numFramesInFlight = 0; + unsigned int frameIndex = UINT_MAX; }; +// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts +// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. +static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData() +{ + return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; +} + //----------------------------------------------------------------------------- // SHADERS //----------------------------------------------------------------------------- -// glsl_shader.vert, compiled with: -// # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert -/* -#version 450 core -layout(location = 0) in vec2 aPos; -layout(location = 1) in vec2 aUV; -layout(location = 2) in vec4 aColor; -layout(set=0, binding = 0) uniform transform { mat4 mvp; }; +static const char __shader_vert_wgsl[] = R"( +struct VertexInput { + @location(0) position: vec2, + @location(1) uv: vec2, + @location(2) color: vec4, +}; + +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) color: vec4, + @location(1) uv: vec2, +}; -out gl_PerVertex { vec4 gl_Position; }; -layout(location = 0) out struct { vec4 Color; vec2 UV; } Out; +struct Uniforms { + mvp: mat4x4, + gamma: f32, +}; -void main() -{ - Out.Color = aColor; - Out.UV = aUV; - gl_Position = mvp * vec4(aPos, 0, 1); +@group(0) @binding(0) var uniforms: Uniforms; + +@vertex +fn main(in: VertexInput) -> VertexOutput { + var out: VertexOutput; + out.position = uniforms.mvp * vec4(in.position, 0.0, 1.0); + out.color = in.color; + out.uv = in.uv; + return out; } -*/ -static uint32_t __glsl_shader_vert_spv[] = -{ - 0x07230203,0x00010000,0x00080007,0x0000002c,0x00000000,0x00020011,0x00000001,0x0006000b, - 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015, - 0x0000001b,0x00000023,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, - 0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43, - 0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f, - 0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005, - 0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000, - 0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00050005,0x0000001d, - 0x6e617274,0x726f6673,0x0000006d,0x00040006,0x0000001d,0x00000000,0x0070766d,0x00030005, - 0x0000001f,0x00000000,0x00040005,0x00000023,0x736f5061,0x00000000,0x00040047,0x0000000b, - 0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015, - 0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047, - 0x00000019,0x00000002,0x00040048,0x0000001d,0x00000000,0x00000005,0x00050048,0x0000001d, - 0x00000000,0x00000023,0x00000000,0x00050048,0x0000001d,0x00000000,0x00000007,0x00000010, - 0x00030047,0x0000001d,0x00000002,0x00040047,0x0000001f,0x00000022,0x00000000,0x00040047, - 0x0000001f,0x00000021,0x00000000,0x00040047,0x00000023,0x0000001e,0x00000000,0x00020013, - 0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017, - 0x00000007,0x00000006,0x00000004,0x00040017,0x00000008,0x00000006,0x00000002,0x0004001e, - 0x00000009,0x00000007,0x00000008,0x00040020,0x0000000a,0x00000003,0x00000009,0x0004003b, - 0x0000000a,0x0000000b,0x00000003,0x00040015,0x0000000c,0x00000020,0x00000001,0x0004002b, - 0x0000000c,0x0000000d,0x00000000,0x00040020,0x0000000e,0x00000001,0x00000007,0x0004003b, - 0x0000000e,0x0000000f,0x00000001,0x00040020,0x00000011,0x00000003,0x00000007,0x0004002b, - 0x0000000c,0x00000013,0x00000001,0x00040020,0x00000014,0x00000001,0x00000008,0x0004003b, - 0x00000014,0x00000015,0x00000001,0x00040020,0x00000017,0x00000003,0x00000008,0x0003001e, - 0x00000019,0x00000007,0x00040020,0x0000001a,0x00000003,0x00000019,0x0004003b,0x0000001a, - 0x0000001b,0x00000003,0x00040018,0x0000001c,0x00000007,0x00000004,0x0003001e,0x0000001d, - 0x0000001c,0x00040020,0x0000001e,0x00000002,0x0000001d,0x0004003b,0x0000001e,0x0000001f, - 0x00000002,0x00040020,0x00000020,0x00000002,0x0000001c,0x0004003b,0x00000014,0x00000023, - 0x00000001,0x0004002b,0x00000006,0x00000025,0x00000000,0x0004002b,0x00000006,0x00000026, - 0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005, - 0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,0x0000000b, - 0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,0x00000015, - 0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,0x00000016, - 0x00050041,0x00000020,0x00000021,0x0000001f,0x0000000d,0x0004003d,0x0000001c,0x00000022, - 0x00000021,0x0004003d,0x00000008,0x00000024,0x00000023,0x00050051,0x00000006,0x00000027, - 0x00000024,0x00000000,0x00050051,0x00000006,0x00000028,0x00000024,0x00000001,0x00070050, - 0x00000007,0x00000029,0x00000027,0x00000028,0x00000025,0x00000026,0x00050091,0x00000007, - 0x0000002a,0x00000022,0x00000029,0x00050041,0x00000011,0x0000002b,0x0000001b,0x0000000d, - 0x0003003e,0x0000002b,0x0000002a,0x000100fd,0x00010038 +)"; + +static const char __shader_frag_wgsl[] = R"( +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) color: vec4, + @location(1) uv: vec2, }; -// glsl_shader.frag, compiled with: -// # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag -/* -#version 450 core -layout(location = 0) out vec4 fColor; -layout(set=0, binding=1) uniform sampler s; -layout(set=1, binding=0) uniform texture2D t; -layout(location = 0) in struct { vec4 Color; vec2 UV; } In; -void main() -{ - fColor = In.Color * texture(sampler2D(t, s), In.UV.st); -} -*/ -static uint32_t __glsl_shader_frag_spv[] = -{ - 0x07230203,0x00010000,0x00080007,0x00000023,0x00000000,0x00020011,0x00000001,0x0006000b, - 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, - 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010, - 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, - 0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000, - 0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001, - 0x00005655,0x00030005,0x0000000d,0x00006e49,0x00030005,0x00000015,0x00000074,0x00030005, - 0x00000019,0x00000073,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d, - 0x0000001e,0x00000000,0x00040047,0x00000015,0x00000022,0x00000001,0x00040047,0x00000015, - 0x00000021,0x00000000,0x00040047,0x00000019,0x00000022,0x00000000,0x00040047,0x00000019, - 0x00000021,0x00000001,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016, - 0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008, - 0x00000003,0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a, - 0x00000006,0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c, - 0x00000001,0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e, - 0x00000020,0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010, - 0x00000001,0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000, - 0x00000000,0x00000001,0x00000000,0x00040020,0x00000014,0x00000000,0x00000013,0x0004003b, - 0x00000014,0x00000015,0x00000000,0x0002001a,0x00000017,0x00040020,0x00000018,0x00000000, - 0x00000017,0x0004003b,0x00000018,0x00000019,0x00000000,0x0003001b,0x0000001b,0x00000013, - 0x0004002b,0x0000000e,0x0000001d,0x00000001,0x00040020,0x0000001e,0x00000001,0x0000000a, - 0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041, - 0x00000010,0x00000011,0x0000000d,0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011, - 0x0004003d,0x00000013,0x00000016,0x00000015,0x0004003d,0x00000017,0x0000001a,0x00000019, - 0x00050056,0x0000001b,0x0000001c,0x00000016,0x0000001a,0x00050041,0x0000001e,0x0000001f, - 0x0000000d,0x0000001d,0x0004003d,0x0000000a,0x00000020,0x0000001f,0x00050057,0x00000007, - 0x00000021,0x0000001c,0x00000020,0x00050085,0x00000007,0x00000022,0x00000012,0x00000021, - 0x0003003e,0x00000009,0x00000022,0x000100fd,0x00010038 +struct Uniforms { + mvp: mat4x4, + gamma: f32, }; +@group(0) @binding(0) var uniforms: Uniforms; +@group(0) @binding(1) var s: sampler; +@group(1) @binding(0) var t: texture_2d; + +@fragment +fn main(in: VertexOutput) -> @location(0) vec4 { + let color = in.color * textureSample(t, s, in.uv); + let corrected_color = pow(color.rgb, vec3(uniforms.gamma)); + return vec4(corrected_color, color.a); +} +)"; + static void SafeRelease(ImDrawIdx*& res) { if (res) delete[] res; - res = NULL; + res = nullptr; } static void SafeRelease(ImDrawVert*& res) { if (res) delete[] res; - res = NULL; + res = nullptr; } static void SafeRelease(WGPUBindGroupLayout& res) { if (res) wgpuBindGroupLayoutRelease(res); - res = NULL; + res = nullptr; } static void SafeRelease(WGPUBindGroup& res) { if (res) wgpuBindGroupRelease(res); - res = NULL; + res = nullptr; } static void SafeRelease(WGPUBuffer& res) { if (res) wgpuBufferRelease(res); - res = NULL; + res = nullptr; +} +static void SafeRelease(WGPUPipelineLayout& res) +{ + if (res) + wgpuPipelineLayoutRelease(res); + res = nullptr; } static void SafeRelease(WGPURenderPipeline& res) { if (res) wgpuRenderPipelineRelease(res); - res = NULL; + res = nullptr; } static void SafeRelease(WGPUSampler& res) { if (res) wgpuSamplerRelease(res); - res = NULL; + res = nullptr; } static void SafeRelease(WGPUShaderModule& res) { if (res) wgpuShaderModuleRelease(res); - res = NULL; + res = nullptr; } static void SafeRelease(WGPUTextureView& res) { if (res) wgpuTextureViewRelease(res); - res = NULL; + res = nullptr; } static void SafeRelease(WGPUTexture& res) { if (res) wgpuTextureRelease(res); - res = NULL; + res = nullptr; } static void SafeRelease(RenderResources& res) @@ -264,35 +240,39 @@ static void SafeRelease(FrameResources& res) SafeRelease(res.VertexBufferHost); } -static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(uint32_t* binary_data, uint32_t binary_data_size) +static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const char* wgsl_source) { - WGPUShaderModuleSPIRVDescriptor spirv_desc = {}; - spirv_desc.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor; - spirv_desc.codeSize = binary_data_size; - spirv_desc.code = binary_data; + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + + WGPUShaderModuleWGSLDescriptor wgsl_desc = {}; + wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor; + wgsl_desc.code = wgsl_source; WGPUShaderModuleDescriptor desc = {}; - desc.nextInChain = reinterpret_cast(&spirv_desc); + desc.nextInChain = reinterpret_cast(&wgsl_desc); WGPUProgrammableStageDescriptor stage_desc = {}; - stage_desc.module = wgpuDeviceCreateShaderModule(g_wgpuDevice, &desc); + stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc); stage_desc.entryPoint = "main"; return stage_desc; } static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture) { + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } }; WGPUBindGroupDescriptor image_bg_descriptor = {}; image_bg_descriptor.layout = layout; image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry); image_bg_descriptor.entries = image_bg_entries; - return wgpuDeviceCreateBindGroup(g_wgpuDevice, &image_bg_descriptor); + return wgpuDeviceCreateBindGroup(bd->wgpuDevice, &image_bg_descriptor); } static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr) { + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + // Setup orthographic projection matrix into our constant buffer // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). { @@ -307,17 +287,48 @@ static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPas { 0.0f, 0.0f, 0.5f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; - wgpuQueueWriteBuffer(g_defaultQueue, g_resources.Uniforms, 0, mvp, sizeof(mvp)); + wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, MVP), mvp, sizeof(Uniforms::MVP)); + float gamma; + switch (bd->renderTargetFormat) + { + case WGPUTextureFormat_ASTC10x10UnormSrgb: + case WGPUTextureFormat_ASTC10x5UnormSrgb: + case WGPUTextureFormat_ASTC10x6UnormSrgb: + case WGPUTextureFormat_ASTC10x8UnormSrgb: + case WGPUTextureFormat_ASTC12x10UnormSrgb: + case WGPUTextureFormat_ASTC12x12UnormSrgb: + case WGPUTextureFormat_ASTC4x4UnormSrgb: + case WGPUTextureFormat_ASTC5x5UnormSrgb: + case WGPUTextureFormat_ASTC6x5UnormSrgb: + case WGPUTextureFormat_ASTC6x6UnormSrgb: + case WGPUTextureFormat_ASTC8x5UnormSrgb: + case WGPUTextureFormat_ASTC8x6UnormSrgb: + case WGPUTextureFormat_ASTC8x8UnormSrgb: + case WGPUTextureFormat_BC1RGBAUnormSrgb: + case WGPUTextureFormat_BC2RGBAUnormSrgb: + case WGPUTextureFormat_BC3RGBAUnormSrgb: + case WGPUTextureFormat_BC7RGBAUnormSrgb: + case WGPUTextureFormat_BGRA8UnormSrgb: + case WGPUTextureFormat_ETC2RGB8A1UnormSrgb: + case WGPUTextureFormat_ETC2RGB8UnormSrgb: + case WGPUTextureFormat_ETC2RGBA8UnormSrgb: + case WGPUTextureFormat_RGBA8UnormSrgb: + gamma = 2.2f; + break; + default: + gamma = 1.0f; + } + wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, Gamma), &gamma, sizeof(Uniforms::Gamma)); } // Setup viewport wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1); // Bind shader and vertex buffers - wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize); - wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize); - wgpuRenderPassEncoderSetPipeline(ctx, g_pipelineState); - wgpuRenderPassEncoderSetBindGroup(ctx, 0, g_resources.CommonBindGroup, 0, NULL); + wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert)); + wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx)); + wgpuRenderPassEncoderSetPipeline(ctx, bd->pipelineState); + wgpuRenderPassEncoderSetBindGroup(ctx, 0, bd->renderResources.CommonBindGroup, 0, nullptr); // Setup blend factor WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f }; @@ -329,16 +340,19 @@ static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPas void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder) { // Avoid rendering when minimized - if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) + int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0) return; // FIXME: Assuming that this only gets called once per frame! // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator. - g_frameIndex = g_frameIndex + 1; - FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight]; + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + bd->frameIndex = bd->frameIndex + 1; + FrameResources* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight]; // Create and grow vertex/index buffers if needed - if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount) + if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount) { if (fr->VertexBuffer) { @@ -350,19 +364,19 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder WGPUBufferDescriptor vb_desc = { - NULL, + nullptr, "Dear ImGui Vertex buffer", WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex, - fr->VertexBufferSize * sizeof(ImDrawVert), + MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4), false }; - fr->VertexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &vb_desc); + fr->VertexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &vb_desc); if (!fr->VertexBuffer) return; fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize]; } - if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount) + if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount) { if (fr->IndexBuffer) { @@ -374,13 +388,13 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder WGPUBufferDescriptor ib_desc = { - NULL, + nullptr, "Dear ImGui Index buffer", WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index, - fr->IndexBufferSize * sizeof(ImDrawIdx), + MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4), false }; - fr->IndexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &ib_desc); + fr->IndexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ib_desc); if (!fr->IndexBuffer) return; @@ -398,10 +412,10 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } - int64_t vb_write_size = ((char*)vtx_dst - (char*)fr->VertexBufferHost + 3) & ~3; - int64_t ib_write_size = ((char*)idx_dst - (char*)fr->IndexBufferHost + 3) & ~3; - wgpuQueueWriteBuffer(g_defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size); - wgpuQueueWriteBuffer(g_defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size); + int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4); + int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4); + wgpuQueueWriteBuffer(bd->defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size); + wgpuQueueWriteBuffer(bd->defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size); // Setup desired render state ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr); @@ -418,7 +432,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - if (pcmd->UserCallback != NULL) + if (pcmd->UserCallback != nullptr) { // User callback, registered via ImDrawList::AddCallback() // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) @@ -432,21 +446,27 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder // Bind custom texture ImTextureID tex_id = pcmd->GetTexID(); ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id)); - auto bind_group = g_resources.ImageBindGroups.GetVoidPtr(tex_id_hash); + auto bind_group = bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash); if (bind_group) { - wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, NULL); + wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr); } else { - WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(g_resources.ImageBindGroupLayout, (WGPUTextureView)tex_id); - g_resources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group); - wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, NULL); + WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id); + bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group); + wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, nullptr); } // Project scissor/clipping rectangles into framebuffer space ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + + // Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds + if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } + if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } + if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; } if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) continue; @@ -463,6 +483,7 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder static void ImGui_ImplWGPU_CreateFontsTexture() { // Build texture atlas + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height, size_pp; @@ -480,7 +501,7 @@ static void ImGui_ImplWGPU_CreateFontsTexture() tex_desc.format = WGPUTextureFormat_RGBA8Unorm; tex_desc.mipLevelCount = 1; tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding; - g_resources.FontTexture = wgpuDeviceCreateTexture(g_wgpuDevice, &tex_desc); + bd->renderResources.FontTexture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc); WGPUTextureViewDescriptor tex_view_desc = {}; tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm; @@ -490,13 +511,13 @@ static void ImGui_ImplWGPU_CreateFontsTexture() tex_view_desc.baseArrayLayer = 0; tex_view_desc.arrayLayerCount = 1; tex_view_desc.aspect = WGPUTextureAspect_All; - g_resources.FontTextureView = wgpuTextureCreateView(g_resources.FontTexture, &tex_view_desc); + bd->renderResources.FontTextureView = wgpuTextureCreateView(bd->renderResources.FontTexture, &tex_view_desc); } // Upload texture data { WGPUImageCopyTexture dst_view = {}; - dst_view.texture = g_resources.FontTexture; + dst_view.texture = bd->renderResources.FontTexture; dst_view.mipLevel = 0; dst_view.origin = { 0, 0, 0 }; dst_view.aspect = WGPUTextureAspect_All; @@ -505,45 +526,48 @@ static void ImGui_ImplWGPU_CreateFontsTexture() layout.bytesPerRow = width * size_pp; layout.rowsPerImage = height; WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 }; - wgpuQueueWriteTexture(g_defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size); + wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size); } // Create the associated sampler + // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) { WGPUSamplerDescriptor sampler_desc = {}; sampler_desc.minFilter = WGPUFilterMode_Linear; sampler_desc.magFilter = WGPUFilterMode_Linear; - sampler_desc.mipmapFilter = WGPUFilterMode_Linear; + sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear; sampler_desc.addressModeU = WGPUAddressMode_Repeat; sampler_desc.addressModeV = WGPUAddressMode_Repeat; sampler_desc.addressModeW = WGPUAddressMode_Repeat; sampler_desc.maxAnisotropy = 1; - g_resources.Sampler = wgpuDeviceCreateSampler(g_wgpuDevice, &sampler_desc); + bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc); } // Store our identifier - static_assert(sizeof(ImTextureID) >= sizeof(g_resources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); - io.Fonts->SetTexID((ImTextureID)g_resources.FontTextureView); + static_assert(sizeof(ImTextureID) >= sizeof(bd->renderResources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet."); + io.Fonts->SetTexID((ImTextureID)bd->renderResources.FontTextureView); } static void ImGui_ImplWGPU_CreateUniformBuffer() { + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); WGPUBufferDescriptor ub_desc = { - NULL, + nullptr, "Dear ImGui Uniform buffer", WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform, - sizeof(Uniforms), + MEMALIGN(sizeof(Uniforms), 16), false }; - g_resources.Uniforms = wgpuDeviceCreateBuffer(g_wgpuDevice, &ub_desc); + bd->renderResources.Uniforms = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ub_desc); } bool ImGui_ImplWGPU_CreateDeviceObjects() { - if (!g_wgpuDevice) + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + if (!bd->wgpuDevice) return false; - if (g_pipelineState) + if (bd->pipelineState) ImGui_ImplWGPU_InvalidateDeviceObjects(); // Create render pipeline @@ -552,22 +576,51 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined; graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW; graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None; - graphics_pipeline_desc.multisample.count = 1; - graphics_pipeline_desc.multisample.mask = UINT_MAX; - graphics_pipeline_desc.multisample.alphaToCoverageEnabled = false; - graphics_pipeline_desc.layout = nullptr; // Use automatic layout generation + graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState; + + // Bind group layouts + WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {}; + common_bg_layout_entries[0].binding = 0; + common_bg_layout_entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment; + common_bg_layout_entries[0].buffer.type = WGPUBufferBindingType_Uniform; + common_bg_layout_entries[1].binding = 1; + common_bg_layout_entries[1].visibility = WGPUShaderStage_Fragment; + common_bg_layout_entries[1].sampler.type = WGPUSamplerBindingType_Filtering; + + WGPUBindGroupLayoutEntry image_bg_layout_entries[1] = {}; + image_bg_layout_entries[0].binding = 0; + image_bg_layout_entries[0].visibility = WGPUShaderStage_Fragment; + image_bg_layout_entries[0].texture.sampleType = WGPUTextureSampleType_Float; + image_bg_layout_entries[0].texture.viewDimension = WGPUTextureViewDimension_2D; + + WGPUBindGroupLayoutDescriptor common_bg_layout_desc = {}; + common_bg_layout_desc.entryCount = 2; + common_bg_layout_desc.entries = common_bg_layout_entries; + + WGPUBindGroupLayoutDescriptor image_bg_layout_desc = {}; + image_bg_layout_desc.entryCount = 1; + image_bg_layout_desc.entries = image_bg_layout_entries; + + WGPUBindGroupLayout bg_layouts[2]; + bg_layouts[0] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &common_bg_layout_desc); + bg_layouts[1] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &image_bg_layout_desc); + + WGPUPipelineLayoutDescriptor layout_desc = {}; + layout_desc.bindGroupLayoutCount = 2; + layout_desc.bindGroupLayouts = bg_layouts; + graphics_pipeline_desc.layout = wgpuDeviceCreatePipelineLayout(bd->wgpuDevice, &layout_desc); // Create the vertex shader - WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_vert_spv, sizeof(__glsl_shader_vert_spv) / sizeof(uint32_t)); + WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_vert_wgsl); graphics_pipeline_desc.vertex.module = vertex_shader_desc.module; graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint; // Vertex input configuration WGPUVertexAttribute attribute_desc[] = { - { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, pos), 0 }, - { WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, uv), 1 }, - { WGPUVertexFormat_Unorm8x4, (uint64_t)IM_OFFSETOF(ImDrawVert, col), 2 }, + { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 }, + { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 }, + { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 }, }; WGPUVertexBufferLayout buffer_layouts[1]; @@ -580,7 +633,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() graphics_pipeline_desc.vertex.buffers = buffer_layouts; // Create the pixel shader - WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_frag_spv, sizeof(__glsl_shader_frag_spv) / sizeof(uint32_t)); + WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_frag_wgsl); // Create the blending setup WGPUBlendState blend_state = {}; @@ -592,7 +645,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha; WGPUColorTargetState color_state = {}; - color_state.format = g_renderTargetFormat; + color_state.format = bd->renderTargetFormat; color_state.blend = &blend_state; color_state.writeMask = WGPUColorWriteMask_All; @@ -606,42 +659,47 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() // Create depth-stencil State WGPUDepthStencilState depth_stencil_state = {}; - depth_stencil_state.depthBias = 0; - depth_stencil_state.depthBiasClamp = 0; - depth_stencil_state.depthBiasSlopeScale = 0; + depth_stencil_state.format = bd->depthStencilFormat; + depth_stencil_state.depthWriteEnabled = false; + depth_stencil_state.depthCompare = WGPUCompareFunction_Always; + depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always; + depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep; + depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep; + depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep; + depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always; + depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep; + depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep; + depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep; // Configure disabled depth-stencil state - graphics_pipeline_desc.depthStencil = nullptr; + graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state; - g_pipelineState = wgpuDeviceCreateRenderPipeline(g_wgpuDevice, &graphics_pipeline_desc); + bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc); ImGui_ImplWGPU_CreateFontsTexture(); ImGui_ImplWGPU_CreateUniformBuffer(); // Create resource bind group - WGPUBindGroupLayout bg_layouts[2]; - bg_layouts[0] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 0); - bg_layouts[1] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 1); - WGPUBindGroupEntry common_bg_entries[] = { - { nullptr, 0, g_resources.Uniforms, 0, sizeof(Uniforms), 0, 0 }, - { nullptr, 1, 0, 0, 0, g_resources.Sampler, 0 }, + { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 }, + { nullptr, 1, 0, 0, 0, bd->renderResources.Sampler, 0 }, }; WGPUBindGroupDescriptor common_bg_descriptor = {}; common_bg_descriptor.layout = bg_layouts[0]; common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry); common_bg_descriptor.entries = common_bg_entries; - g_resources.CommonBindGroup = wgpuDeviceCreateBindGroup(g_wgpuDevice, &common_bg_descriptor); + bd->renderResources.CommonBindGroup = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor); - WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], g_resources.FontTextureView); - g_resources.ImageBindGroup = image_bind_group; - g_resources.ImageBindGroupLayout = bg_layouts[1]; - g_resources.ImageBindGroups.SetVoidPtr(ImHashData(&g_resources.FontTextureView, sizeof(ImTextureID)), image_bind_group); + WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], bd->renderResources.FontTextureView); + bd->renderResources.ImageBindGroup = image_bind_group; + bd->renderResources.ImageBindGroupLayout = bg_layouts[1]; + bd->renderResources.ImageBindGroups.SetVoidPtr(ImHashData(&bd->renderResources.FontTextureView, sizeof(ImTextureID)), image_bind_group); SafeRelease(vertex_shader_desc.module); SafeRelease(pixel_shader_desc.module); + SafeRelease(graphics_pipeline_desc.layout); SafeRelease(bg_layouts[0]); return true; @@ -649,50 +707,57 @@ bool ImGui_ImplWGPU_CreateDeviceObjects() void ImGui_ImplWGPU_InvalidateDeviceObjects() { - if (!g_wgpuDevice) + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + if (!bd->wgpuDevice) return; - SafeRelease(g_pipelineState); - SafeRelease(g_resources); + SafeRelease(bd->pipelineState); + SafeRelease(bd->renderResources); ImGuiIO& io = ImGui::GetIO(); - io.Fonts->SetTexID(NULL); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. + io.Fonts->SetTexID(0); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. - for (unsigned int i = 0; i < g_numFramesInFlight; i++) - SafeRelease(g_pFrameResources[i]); + for (unsigned int i = 0; i < bd->numFramesInFlight; i++) + SafeRelease(bd->pFrameResources[i]); } -bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format) +bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info) { - // Setup backend capabilities flags ImGuiIO& io = ImGui::GetIO(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + // Setup backend capabilities flags + ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)(); + io.BackendRendererUserData = (void*)bd; io.BackendRendererName = "imgui_impl_webgpu"; io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. - g_wgpuDevice = device; - g_defaultQueue = wgpuDeviceGetQueue(g_wgpuDevice); - g_renderTargetFormat = rt_format; - g_pFrameResources = new FrameResources[num_frames_in_flight]; - g_numFramesInFlight = num_frames_in_flight; - g_frameIndex = UINT_MAX; - - g_resources.FontTexture = NULL; - g_resources.FontTextureView = NULL; - g_resources.Sampler = NULL; - g_resources.Uniforms = NULL; - g_resources.CommonBindGroup = NULL; - g_resources.ImageBindGroups.Data.reserve(100); - g_resources.ImageBindGroup = NULL; - g_resources.ImageBindGroupLayout = NULL; + bd->initInfo = *init_info; + bd->wgpuDevice = init_info->Device; + bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice); + bd->renderTargetFormat = init_info->RenderTargetFormat; + bd->depthStencilFormat = init_info->DepthStencilFormat; + bd->numFramesInFlight = init_info->NumFramesInFlight; + bd->frameIndex = UINT_MAX; + + bd->renderResources.FontTexture = nullptr; + bd->renderResources.FontTextureView = nullptr; + bd->renderResources.Sampler = nullptr; + bd->renderResources.Uniforms = nullptr; + bd->renderResources.CommonBindGroup = nullptr; + bd->renderResources.ImageBindGroups.Data.reserve(100); + bd->renderResources.ImageBindGroup = nullptr; + bd->renderResources.ImageBindGroupLayout = nullptr; // Create buffers with a default size (they will later be grown as needed) - for (int i = 0; i < num_frames_in_flight; i++) + bd->pFrameResources = new FrameResources[bd->numFramesInFlight]; + for (int i = 0; i < bd->numFramesInFlight; i++) { - FrameResources* fr = &g_pFrameResources[i]; - fr->IndexBuffer = NULL; - fr->VertexBuffer = NULL; - fr->IndexBufferHost = NULL; - fr->VertexBufferHost = NULL; + FrameResources* fr = &bd->pFrameResources[i]; + fr->IndexBuffer = nullptr; + fr->VertexBuffer = nullptr; + fr->IndexBufferHost = nullptr; + fr->VertexBufferHost = nullptr; fr->IndexBufferSize = 10000; fr->VertexBufferSize = 5000; } @@ -702,17 +767,31 @@ bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextur void ImGui_ImplWGPU_Shutdown() { + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ImGui_ImplWGPU_InvalidateDeviceObjects(); - delete[] g_pFrameResources; - g_pFrameResources = NULL; - wgpuQueueRelease(g_defaultQueue); - g_wgpuDevice = NULL; - g_numFramesInFlight = 0; - g_frameIndex = UINT_MAX; + delete[] bd->pFrameResources; + bd->pFrameResources = nullptr; + wgpuQueueRelease(bd->defaultQueue); + bd->wgpuDevice = nullptr; + bd->numFramesInFlight = 0; + bd->frameIndex = UINT_MAX; + + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; + IM_DELETE(bd); } void ImGui_ImplWGPU_NewFrame() { - if (!g_pipelineState) + ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData(); + if (!bd->pipelineState) ImGui_ImplWGPU_CreateDeviceObjects(); } + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_wgpu.h b/third_party/imgui/backends/imgui_impl_wgpu.h index ec10768e99e..9dc3ff290be 100644 --- a/third_party/imgui/backends/imgui_impl_wgpu.h +++ b/third_party/imgui/backends/imgui_impl_wgpu.h @@ -4,18 +4,40 @@ // Implemented features: // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! -// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. +// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + #include -IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format); +// Initialization data, for ImGui_ImplWGPU_Init() +struct ImGui_ImplWGPU_InitInfo +{ + WGPUDevice Device; + int NumFramesInFlight = 3; + WGPUTextureFormat RenderTargetFormat = WGPUTextureFormat_Undefined; + WGPUTextureFormat DepthStencilFormat = WGPUTextureFormat_Undefined; + WGPUMultisampleState PipelineMultisampleState = {}; + + ImGui_ImplWGPU_InitInfo() + { + PipelineMultisampleState.count = 1; + PipelineMultisampleState.mask = -1u; + PipelineMultisampleState.alphaToCoverageEnabled = false; + } +}; + +IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info); IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame(); IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder); @@ -23,3 +45,5 @@ IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURen // Use if you want to reset your rendering device without losing Dear ImGui state. IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects(); + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_win32.cpp b/third_party/imgui/backends/imgui_impl_win32.cpp index ce8f9d55c8e..73ed700c48f 100644 --- a/third_party/imgui/backends/imgui_impl_win32.cpp +++ b/third_party/imgui/backends/imgui_impl_win32.cpp @@ -1,23 +1,29 @@ -// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) -// [X] Platform: Mouse 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: Mouse support. Can discriminate Mouse/TouchScreen/Pen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" +#ifndef IMGUI_DISABLE #include "imgui_impl_win32.h" #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include +#include // GET_X_LPARAM(), GET_Y_LPARAM() #include #include @@ -33,6 +39,23 @@ typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*); // CHANGELOG // (minor and older changes stripped away, please see git history for details) +// 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. @@ -66,26 +89,28 @@ typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*); // 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(NULL) when io.MouseDrawCursor is set. +// 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set. struct ImGui_ImplWin32_Data { HWND hWnd; HWND MouseHwnd; - bool MouseTracked; + int MouseTrackedArea; // 0: not tracked, 1: client are, 2: non-client area + int MouseButtonsDown; INT64 Time; INT64 TicksPerSecond; ImGuiMouseCursor LastMouseCursor; - bool HasGamepad; - bool WantUpdateHasGamepad; + UINT32 KeyboardCodePage; #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + bool HasGamepad; + bool WantUpdateHasGamepad; HMODULE XInputDLL; PFN_XInputGetCapabilities XInputGetCapabilities; PFN_XInputGetState XInputGetState; #endif - ImGui_ImplWin32_Data() { memset(this, 0, sizeof(*this)); } + ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } }; // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts @@ -94,14 +119,24 @@ struct ImGui_ImplWin32_Data // 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 : NULL; + return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; } // Functions -bool ImGui_ImplWin32_Init(void* hwnd) +static void ImGui_ImplWin32_UpdateKeyboardCodePage() +{ + // Retrieve keyboard code page, required for handling of non-Unicode Windows. + ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); + HKL keyboard_layout = ::GetKeyboardLayout(0); + LCID keyboard_lcid = MAKELCID(HIWORD(keyboard_layout), SORT_DEFAULT); + if (::GetLocaleInfoA(keyboard_lcid, (LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE), (LPSTR)&bd->KeyboardCodePage, sizeof(bd->KeyboardCodePage)) == 0) + bd->KeyboardCodePage = CP_ACP; // Fallback to default ANSI code page when fails. +} + +static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) { ImGuiIO& io = ImGui::GetIO(); - IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!"); + IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); INT64 perf_frequency, perf_counter; if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency)) @@ -117,39 +152,18 @@ bool ImGui_ImplWin32_Init(void* hwnd) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) bd->hWnd = (HWND)hwnd; - bd->WantUpdateHasGamepad = true; bd->TicksPerSecond = perf_frequency; bd->Time = perf_counter; bd->LastMouseCursor = ImGuiMouseCursor_COUNT; + ImGui_ImplWin32_UpdateKeyboardCodePage(); - io.ImeWindowHandle = hwnd; - - // Keyboard mapping. Dear 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_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'; + // Set platform dependent data in viewport + ImGui::GetMainViewport()->PlatformHandleRaw = (void*)hwnd; + IM_UNUSED(platform_has_own_dc); // Used in 'docking' branch // Dynamically load XInput library #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD + bd->WantUpdateHasGamepad = true; const char* xinput_dll_names[] = { "xinput1_4.dll", // Windows 8+ @@ -171,10 +185,21 @@ bool ImGui_ImplWin32_Init(void* hwnd) 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 != NULL && "No platform backend to shutdown, or already shutdown?"); + IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); ImGuiIO& io = ImGui::GetIO(); // Unload XInput library @@ -183,8 +208,9 @@ void ImGui_ImplWin32_Shutdown() ::FreeLibrary(bd->XInputDLL); #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD - io.BackendPlatformName = NULL; - io.BackendPlatformUserData = NULL; + io.BackendPlatformName = nullptr; + io.BackendPlatformUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); IM_DELETE(bd); } @@ -198,7 +224,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(NULL); + ::SetCursor(nullptr); } else { @@ -216,43 +242,75 @@ static bool ImGui_ImplWin32_UpdateMouseCursor() case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; } - ::SetCursor(::LoadCursor(NULL, win32_cursor)); + ::SetCursor(::LoadCursor(nullptr, win32_cursor)); } return true; } -static void ImGui_ImplWin32_UpdateMousePos() +static bool IsVkDown(int vk) +{ + return (::GetKeyState(vk) & 0x8000) != 0; +} + +static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1) +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(key, down); + io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code) + IM_UNUSED(native_scancode); +} + +static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds() +{ + // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one. + if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT); + if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT); + + // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW). + if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN); + if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN)) + ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN); +} + +static void ImGui_ImplWin32_UpdateKeyModifiers() +{ + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL)); + io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT)); + io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU)); + io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_APPS)); +} + +static void ImGui_ImplWin32_UpdateMouseData() { ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(bd->hWnd != 0); - const ImVec2 mouse_pos_prev = io.MousePos; - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - - // Obtain focused and hovered window. We forward mouse input when focused or when hovered (and no other window is capturing) HWND focused_window = ::GetForegroundWindow(); - HWND hovered_window = bd->MouseHwnd; - HWND mouse_window = NULL; - if (hovered_window && (hovered_window == bd->hWnd || ::IsChild(hovered_window, bd->hWnd))) - mouse_window = hovered_window; - else if (focused_window && (focused_window == bd->hWnd || ::IsChild(focused_window, bd->hWnd))) - mouse_window = focused_window; - if (mouse_window == NULL) - return; - - // Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) - if (io.WantSetMousePos) + const bool is_app_focused = (focused_window == bd->hWnd); + if (is_app_focused) { - POINT pos = { (int)mouse_pos_prev.x, (int)mouse_pos_prev.y }; - if (::ClientToScreen(bd->hWnd, &pos)) - ::SetCursorPos(pos.x, pos.y); - } + // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) + if (io.WantSetMousePos) + { + POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y }; + if (::ClientToScreen(bd->hWnd, &pos)) + ::SetCursorPos(pos.x, pos.y); + } - // Set Dear ImGui mouse position from OS position - POINT pos; - if (::GetCursorPos(&pos) && ::ScreenToClient(mouse_window, &pos)) - io.MousePos = ImVec2((float)pos.x, (float)pos.y); + // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured) + // This also fills a short gap when clicking non-client area: WM_NCMOUSELEAVE -> modal OS move -> gap -> WM_NCMOUSEMOVE + if (!io.WantSetMousePos && bd->MouseTrackedArea == 0) + { + POINT pos; + if (::GetCursorPos(&pos) && ::ScreenToClient(bd->hWnd, &pos)) + io.AddMousePosEvent((float)pos.x, (float)pos.y); + } + } } // Gamepad navigation mapping @@ -261,47 +319,54 @@ static void ImGui_ImplWin32_UpdateGamepads() #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD ImGuiIO& io = ImGui::GetIO(); ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - memset(io.NavInputs, 0, sizeof(io.NavInputs)); - if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) - return; + //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; + 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; - if (bd->HasGamepad && bd->XInputGetState && bd->XInputGetState(0, &xinput_state) == ERROR_SUCCESS) - { - const XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad; - io.BackendFlags |= ImGuiBackendFlags_HasGamepad; - - #define MAP_BUTTON(NAV_NO, BUTTON_ENUM) { io.NavInputs[NAV_NO] = (gamepad.wButtons & BUTTON_ENUM) ? 1.0f : 0.0f; } - #define MAP_ANALOG(NAV_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; } - MAP_BUTTON(ImGuiNavInput_Activate, XINPUT_GAMEPAD_A); // Cross / A - MAP_BUTTON(ImGuiNavInput_Cancel, XINPUT_GAMEPAD_B); // Circle / B - MAP_BUTTON(ImGuiNavInput_Menu, XINPUT_GAMEPAD_X); // Square / X - MAP_BUTTON(ImGuiNavInput_Input, XINPUT_GAMEPAD_Y); // Triangle / Y - MAP_BUTTON(ImGuiNavInput_DpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); // D-Pad Left - MAP_BUTTON(ImGuiNavInput_DpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); // D-Pad Right - MAP_BUTTON(ImGuiNavInput_DpadUp, XINPUT_GAMEPAD_DPAD_UP); // D-Pad Up - MAP_BUTTON(ImGuiNavInput_DpadDown, XINPUT_GAMEPAD_DPAD_DOWN); // D-Pad Down - MAP_BUTTON(ImGuiNavInput_FocusPrev, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB - MAP_BUTTON(ImGuiNavInput_FocusNext, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB - MAP_BUTTON(ImGuiNavInput_TweakSlow, XINPUT_GAMEPAD_LEFT_SHOULDER); // L1 / LB - MAP_BUTTON(ImGuiNavInput_TweakFast, XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB - MAP_ANALOG(ImGuiNavInput_LStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); - MAP_ANALOG(ImGuiNavInput_LStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); - MAP_ANALOG(ImGuiNavInput_LStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); - MAP_ANALOG(ImGuiNavInput_LStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32767); - #undef MAP_BUTTON - #undef MAP_ANALOG - } + 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 } @@ -309,7 +374,7 @@ void ImGui_ImplWin32_NewFrame() { ImGuiIO& io = ImGui::GetIO(); ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); - IM_ASSERT(bd != NULL && "Did you call ImGui_ImplWin32_Init()?"); + IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplWin32_Init()?"); // Setup display size (every frame to accommodate for window resizing) RECT rect = { 0, 0, 0, 0 }; @@ -323,7 +388,10 @@ void ImGui_ImplWin32_NewFrame() bd->Time = current_time; // Update OS mouse position - ImGui_ImplWin32_UpdateMousePos(); + ImGui_ImplWin32_UpdateMouseData(); + + // Process workarounds for known Windows key handling issues + ImGui_ImplWin32_ProcessKeyEventsWorkarounds(); // Update OS mouse cursor with the cursor requested by imgui ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); @@ -337,6 +405,136 @@ void ImGui_ImplWin32_NewFrame() 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 @@ -346,10 +544,10 @@ void ImGui_ImplWin32_NewFrame() #endif // Win32 message handler (process Win32 mouse/keyboard inputs, etc.) -// Call from your application's message handler. +// 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. -// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag. @@ -357,9 +555,22 @@ void ImGui_ImplWin32_NewFrame() // 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) { - if (ImGui::GetCurrentContext() == NULL) + if (ImGui::GetCurrentContext() == nullptr) return 0; ImGuiIO& io = ImGui::GetIO(); @@ -368,33 +579,57 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA 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->MouseTracked) + if (bd->MouseTrackedArea != area) { - TRACKMOUSEEVENT tme = { sizeof(tme), TME_LEAVE, hwnd, 0 }; - ::TrackMouseEvent(&tme); - bd->MouseTracked = true; + TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 }; + TRACKMOUSEEVENT tme_track = { sizeof(tme_track), (DWORD)((area == 2) ? (TME_LEAVE | TME_NONCLIENT) : TME_LEAVE), hwnd, 0 }; + if (bd->MouseTrackedArea != 0) + ::TrackMouseEvent(&tme_cancel); + ::TrackMouseEvent(&tme_track); + bd->MouseTrackedArea = area; } + POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) }; + if (msg == WM_NCMOUSEMOVE && ::ScreenToClient(hwnd, &mouse_pos) == FALSE) // WM_NCMOUSEMOVE are provided in absolute coordinates. + break; + io.AddMouseSourceEvent(mouse_source); + io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); break; + } case WM_MOUSELEAVE: - if (bd->MouseHwnd == hwnd) - bd->MouseHwnd = NULL; - bd->MouseTracked = false; + case WM_NCMOUSELEAVE: + { + const int area = (msg == WM_MOUSELEAVE) ? 1 : 2; + if (bd->MouseTrackedArea == area) + { + if (bd->MouseHwnd == hwnd) + bd->MouseHwnd = nullptr; + bd->MouseTrackedArea = 0; + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); + } break; + } case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: { + ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); int button = 0; if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; } if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; } if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; } if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } - if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL) + if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr) ::SetCapture(hwnd); - io.MouseDown[button] = true; + bd->MouseButtonsDown |= 1 << button; + io.AddMouseSourceEvent(mouse_source); + io.AddMouseButtonEvent(button, true); return 0; } case WM_LBUTTONUP: @@ -402,47 +637,69 @@ 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) { button = 0; } if (msg == WM_RBUTTONUP) { button = 1; } if (msg == WM_MBUTTONUP) { button = 2; } if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } - io.MouseDown[button] = false; - if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd) + bd->MouseButtonsDown &= ~(1 << button); + if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd) ::ReleaseCapture(); + io.AddMouseSourceEvent(mouse_source); + io.AddMouseButtonEvent(button, false); return 0; } case WM_MOUSEWHEEL: - io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA; + io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA); return 0; case WM_MOUSEHWHEEL: - io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA; + io.AddMouseWheelEvent(-(float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f); return 0; case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: { - bool down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); + const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); if (wParam < 256) - io.KeysDown[wParam] = down; - if (wParam == VK_CONTROL) - { - io.KeysDown[VK_LCONTROL] = ((::GetKeyState(VK_LCONTROL) & 0x8000) != 0); - io.KeysDown[VK_RCONTROL] = ((::GetKeyState(VK_RCONTROL) & 0x8000) != 0); - io.KeyCtrl = io.KeysDown[VK_LCONTROL] || io.KeysDown[VK_RCONTROL]; - } - if (wParam == VK_SHIFT) - { - io.KeysDown[VK_LSHIFT] = ((::GetKeyState(VK_LSHIFT) & 0x8000) != 0); - io.KeysDown[VK_RSHIFT] = ((::GetKeyState(VK_RSHIFT) & 0x8000) != 0); - io.KeyShift = io.KeysDown[VK_LSHIFT] || io.KeysDown[VK_RSHIFT]; - } - if (wParam == VK_MENU) { - io.KeysDown[VK_LMENU] = ((::GetKeyState(VK_LMENU) & 0x8000) != 0); - io.KeysDown[VK_RMENU] = ((::GetKeyState(VK_RMENU) & 0x8000) != 0); - io.KeyAlt = io.KeysDown[VK_LMENU] || io.KeysDown[VK_RMENU]; + // Submit modifiers + ImGui_ImplWin32_UpdateKeyModifiers(); + + // Obtain virtual key code + // (keypad enter doesn't have its own... VK_RETURN with KF_EXTENDED flag means keypad enter, see IM_VK_KEYPAD_ENTER definition for details, it is mapped to ImGuiKey_KeyPadEnter.) + int vk = (int)wParam; + if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) + vk = IM_VK_KEYPAD_ENTER; + const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk); + const int scancode = (int)LOBYTE(HIWORD(lParam)); + + // Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event. + if (key == ImGuiKey_PrintScreen && !is_key_down) + ImGui_ImplWin32_AddKeyEvent(key, true, vk, scancode); + + // Submit key event + if (key != ImGuiKey_None) + ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode); + + // Submit individual left/right modifier events + if (vk == VK_SHIFT) + { + // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds() + if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); } + if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); } + } + else if (vk == VK_CONTROL) + { + if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); } + if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); } + } + else if (vk == VK_MENU) + { + if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); } + if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); } + } } return 0; } @@ -450,18 +707,33 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA case WM_KILLFOCUS: io.AddFocusEvent(msg == WM_SETFOCUS); return 0; + case WM_INPUTLANGCHANGE: + ImGui_ImplWin32_UpdateKeyboardCodePage(); + return 0; case WM_CHAR: - // You can also use ToAscii()+GetKeyboardState() to retrieve characters. - if (wParam > 0 && wParam < 0x10000) - io.AddInputCharacterUTF16((unsigned short)wParam); + if (::IsWindowUnicode(hwnd)) + { + // You can also use ToAscii()+GetKeyboardState() to retrieve characters. + if (wParam > 0 && wParam < 0x10000) + io.AddInputCharacterUTF16((unsigned short)wParam); + } + else + { + wchar_t wch = 0; + ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1); + io.AddInputCharacter(wch); + } return 0; case WM_SETCURSOR: + // This is required to restore cursor when transitioning from e.g resize borders to client area. if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) return 1; return 0; case WM_DEVICECHANGE: +#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD if ((UINT)wParam == DBT_DEVNODES_CHANGED) bd->WantUpdateHasGamepad = true; +#endif return 0; } return 0; @@ -487,11 +759,11 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) { typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG); - static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = NULL; - if (RtlVerifyVersionInfoFn == NULL) + static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr; + if (RtlVerifyVersionInfoFn == nullptr) if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll")) RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); - if (RtlVerifyVersionInfoFn == NULL) + if (RtlVerifyVersionInfoFn == nullptr) return FALSE; RTL_OSVERSIONINFOEXW versionInfo = { }; @@ -560,10 +832,10 @@ float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) if (_IsWindows8Point1OrGreater()) { static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process - static PFN_GetDpiForMonitor GetDpiForMonitorFn = NULL; - if (GetDpiForMonitorFn == NULL && shcore_dll != NULL) + static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr; + if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr) GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"); - if (GetDpiForMonitorFn != NULL) + if (GetDpiForMonitorFn != nullptr) { GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! @@ -571,11 +843,11 @@ float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) } } #ifndef NOGDI - const HDC dc = ::GetDC(NULL); + 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(NULL, dc); + ::ReleaseDC(nullptr, dc); #endif return xdpi / 96.0f; } @@ -627,3 +899,5 @@ void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) } //--------------------------------------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/third_party/imgui/backends/imgui_impl_win32.h b/third_party/imgui/backends/imgui_impl_win32.h index 768fe16947f..be562714242 100644 --- a/third_party/imgui/backends/imgui_impl_win32.h +++ b/third_party/imgui/backends/imgui_impl_win32.h @@ -1,27 +1,35 @@ -// dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications) +// dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) // Implemented features: // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) -// [X] Platform: Mouse 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: Mouse support. Can discriminate Mouse/TouchScreen/Pen. +// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. +// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. -// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. +// 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. -// 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 +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #pragma once #include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); +IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(); // Win32 message handler your application need to call. // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on from this helper. // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. +// - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. + #if 0 extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); #endif @@ -40,3 +48,5 @@ IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // // - 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 diff --git a/third_party/imgui/docs/BACKENDS.md b/third_party/imgui/docs/BACKENDS.md index 5bd2e836457..e5aa79be163 100644 --- a/third_party/imgui/docs/BACKENDS.md +++ b/third_party/imgui/docs/BACKENDS.md @@ -5,22 +5,22 @@ _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKE **The backends/ folder contains backends for popular platforms/graphics API, which you can use in your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h. -- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing.
- e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl.cpp)), etc. +- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, and windowing.
+ e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl2.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl2.cpp)), etc. -- The 'Renderer' backends are in charge of: creating atlas texture, rendering imgui draw data.
- e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp), Vulkan ([imgui_impl_vulkan.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp), etc. +- The 'Renderer' backends are in charge of: creating atlas texture, and rendering imgui draw data.
+ e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp)), Vulkan ([imgui_impl_vulkan.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp)), etc. -- For some high-level frameworks, a single backend usually handle both 'Platform' and 'Renderer' parts.
+- For some high-level frameworks, a single backend usually handles both 'Platform' and 'Renderer' parts.
e.g. Allegro 5 ([imgui_impl_allegro5.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_allegro5.cpp)). If you end up creating a custom backend for your engine, you may want to do the same. -An application usually combines 1 Platform backend + 1 Renderer backend + main Dear ImGui sources. +An application usually combines one Platform backend + one Renderer backend + main Dear ImGui sources. For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx11) application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. There are 20+ examples in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder. See [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for details. **Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** -### What are backends +### What are backends? Dear ImGui is highly portable and only requires a few things to run and render, typically: @@ -38,10 +38,10 @@ Dear ImGui is highly portable and only requires a few things to run and render, - Optional: multi-viewports support. etc. -This is essentially what each backends are doing + obligatory portability cruft. Using default backends ensure you can get all those features including the ones that would be harder to implement on your side (e.g. multi-viewports support). +This is essentially what each backend is doing + obligatory portability cruft. Using default backends ensure you can get all those features including the ones that would be harder to implement on your side (e.g. multi-viewports support). It is important to understand the difference between the core Dear ImGui library (files in the root folder) -and backends which we are describing here (backends/ folder). +and the backends which we are describing here (backends/ folder). - Some issues may only be backend or platform specific. - You should be able to write backends for pretty much any platform and any 3D graphics API. @@ -62,7 +62,8 @@ List of Platforms Backends: imgui_impl_android.cpp ; Android native app API imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) - imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org + imgui_impl_sdl2.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org + imgui_impl_sdl3.cpp ; SDL3 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org (*EXPERIMENTAL UNTIL SDL3 IS RELEASED*) imgui_impl_win32.cpp ; Win32 native API (Windows) imgui_impl_glut.cpp ; GLUT/FreeGLUT (this is prehistoric software and absolutely not recommended today!) @@ -75,7 +76,8 @@ List of Renderer Backends: imgui_impl_metal.mm ; Metal (with ObjC) imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context) imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) - imgui_impl_sdlrenderer.cpp; SDL_Renderer (optional component of SDL2 available from SDL 2.0.18+) + imgui_impl_sdlrenderer2.cpp ; SDL_Renderer (optional component of SDL2 available from SDL 2.0.18+) + imgui_impl_sdlrenderer3.cpp ; SDL_Renderer (optional component of SDL3 available from SDL 3.0.0+) imgui_impl_vulkan.cpp ; Vulkan imgui_impl_wgpu.cpp ; WebGPU @@ -83,12 +85,12 @@ List of high-level Frameworks Backends (combining Platform + Renderer): imgui_impl_allegro5.cpp -Emscripten is also supported. -The [example_emscripten_opengl3](https://github.com/ocornut/imgui/tree/master/examples/example_emscripten_opengl3) app uses imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp, but other combos are possible. +Emscripten is also supported! +The SDL+GL, GLFW+GL and SDL+WebGPU examples are all ready to build and run with Emscripten. ### Backends for third-party frameworks, graphics API or other languages -See https://github.com/ocornut/imgui/wiki/Bindings for the full list (e.g. Adventure Game Studio, Cinder, Cocos2d-x, Game Maker Studio2, Godot, LÖVE+LUA, Magnum, Monogame, Ogre, openFrameworks, OpenSceneGraph, SFML, Sokol, Unity, Unreal Engine and many others). +See https://github.com/ocornut/imgui/wiki/Bindings for the full list (e.g. Adventure Game Studio, Cinder, Cocos2d-x, Game Maker Studio2, Godot, LÖVE+LUA, Magnum, Monogame, Ogre, openFrameworks, OpenSceneGraph, SFML, Sokol, Unity, Unreal Engine and many others). ### Recommended Backends @@ -97,7 +99,7 @@ If you are not sure which backend to use, the recommended platform/frameworks fo |Library |Website |Backend |Note | |--------|--------|--------|-----| | GLFW | https://github.com/glfw/glfw | imgui_impl_glfw.cpp | | -| SDL2 | https://www.libsdl.org | imgui_impl_sdl.cpp | | +| SDL2 | https://www.libsdl.org | imgui_impl_sdl2.cpp | | | Sokol | https://github.com/floooh/sokol | [util/sokol_imgui.h](https://github.com/floooh/sokol/blob/master/util/sokol_imgui.h) | Lower-level than GLFW/SDL | @@ -109,19 +111,19 @@ Think twice! If you are new to Dear ImGui, first try using the existing backends as-is. You will save lots of time integrating the library. You can LATER decide to rewrite yourself a custom backend if you really need to. -In most situations, custom backends have less features and more bugs than the standard backends we provide. +In most situations, custom backends have fewer features and more bugs than the standard backends we provide. If you want portability, you can use multiple backends and choose between them either at compile time or at runtime. **Example A**: your engine is built over Windows + DirectX11 but you have your own high-level rendering system layered over DirectX11.
Suggestion: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. -Once it works, if you really need it you can replace the imgui_impl_dx11.cpp code with a +Once it works, if you really need it, you can replace the imgui_impl_dx11.cpp code with a custom renderer using your own rendering functions, and keep using the standard Win32 code etc. -**Example B**: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, Vulkan respectively.
+**Example B**: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, and Vulkan respectively.
Suggestion: use multiple generic backends! -Once it works, if you really need it you can replace parts of backends with your own abstractions. +Once it works, if you really need it, you can replace parts of backends with your own abstractions. **Example C**: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch), and you have high-level systems everywhere.
diff --git a/third_party/imgui/docs/CHANGELOG.txt b/third_party/imgui/docs/CHANGELOG.txt index c8ad7bed455..1266dde5979 100644 --- a/third_party/imgui/docs/CHANGELOG.txt +++ b/third_party/imgui/docs/CHANGELOG.txt @@ -5,35 +5,1556 @@ This document holds the user-facing changelog that we also use in release notes. We generally fold multiple commits pertaining to the same topic as a single entry. Changes to backends are also included within the individual .cpp files of each backend. +FAQ https://www.dearimgui.com/faq/ RELEASE NOTES: https://github.com/ocornut/imgui/releases -REPORT ISSUES: https://github.com/ocornut/imgui/issues -DISCUSS, ASK QUESTIONS: https://github.com/ocornut/imgui/discussions -FAQ https://www.dearimgui.org/faq/ WIKI https://github.com/ocornut/imgui/wiki +GETTING STARTED https://github.com/ocornut/imgui/wiki/Getting-Started +GLOSSARY https://github.com/ocornut/imgui/wiki/Glossary +ISSUES & SUPPORT https://github.com/ocornut/imgui/issues WHEN TO UPDATE? - Keeping your copy of Dear ImGui updated regularly is recommended. -- It is generally safe to sync to the latest commit in master or docking branches - The library is fairly stable and regressions tends to be fixed fast when reported. +- It is generally safe and recommended to sync to the latest commit in 'master' or 'docking' + branches. The library is fairly stable and regressions tends to be fixed fast when reported. HOW TO UPDATE? -- Overwrite every file except imconfig.h (if you have modified it). -- You may also locally branch to modify imconfig.h and merge latest into your branch. +- Update submodule or copy/overwrite every file. +- About imconfig.h: + - You may modify your copy of imconfig.h, in this case don't overwrite it. + - or you may locally branch to modify imconfig.h and merge/rebase latest. + - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to + specify a custom path for your imconfig.h file and instead not have to modify the default one. - Read the `Breaking Changes` section (in imgui.cpp or here in the Changelog). - If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. -- If you are dropping this repository in your codebase, please leave the demo and text files in there, they will be useful. +- If you are copying this repository in your codebase, please leave the demo and documentations files in there, they will be useful. - You may diff your previous Changelog with the one you just copied and read that diff. - You may enable `IMGUI_DISABLE_OBSOLETE_FUNCTIONS` in imconfig.h to forcefully disable legacy names and symbols. Doing it every once in a while is a good way to make sure you are not using obsolete symbols. Dear ImGui is in active development, and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. - Please report any issue! +----------------------------------------------------------------------- + VERSION 1.90.4 (Released 2024-02-22) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.4 + +Other changes: + +- Nav: Fixed SetKeyboardFocusHere() or programmatic tabbing API from not working on + windows with the ImGuiWindowFlags_NoNavInputs flag (regression in 1.90.2, which + among other things broke imgui_memory_editor). +- Menus, Popups: Fixed an issue where hovering a parent-menu upward would + erroneously close the window. (#7325, #7287, #7063) +- Popups: Fixed resizable popup minimum size being too small. Standardized minimum + size logic. (#7329). +- Modals: Temporary changes of ImGuiCol_ModalWindowDimBg are properly handled by + BeginPopupModal(). (#7340) +- Tables: Angled headers: fixed support for multi-line labels. (#6917) +- Tables: Angled headers: various fixes to accurately handle CellPadding changes. (#6917) +- Tables: Angled headers: properly registers horizontal component of angled headers + for auto-resizing of columns. (#6917) +- Tables: Angled headers: fixed TableAngledHeadersRow() incorrect background fill + drawn too low, particularly visible with tables that have no scrolling. (#6917) +- ProgressBar: Fixed a minor tesselation issue when rendering rounded progress bars, + where in some situations the rounded section wouldn't follow regular tesselation rules. +- Debug Tools: Item Picker: Promoted ImGui::DebugStartItemPicker() to public API. (#2673) +- Debug Tools: Item Picker: Menu entry visible in Demo->Tools but greyed out unless + io.ConfigDebugIsDebuggerPresent is set. (#2673) +- Misc: Added optional alpha multiplier parameter to GetColorU32(ImU32) variant. +- Demo: Custom Rendering: better demonstrate PathArcTo(), PathBezierQuadraticCurveTo(), + PathBezierCubicCurveTo(), PathStroke(), PathFillConvex() functions. + + +----------------------------------------------------------------------- + VERSION 1.90.3 (Released 2024-02-14) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.3 + +Breaking changes: + +- Backends: SDL2: Removed obsolete ImGui_ImplSDL2_NewFrame(SDL_Window*) signature which + was obsoleted in 1.84. Calling ImGui_ImplSDL2_NewFrame() is fine. +- Backends: Vulkan: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to + ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering. (#7308) [@shawnhatori] +- Backends: Vulkan: Using dynamic rendering now require filling the PipelineRenderingCreateInfo + structure in ImGui_ImplVulkan_InitInfo, allowing to configure color/depth/stencil formats. + Removed ColorAttachmentFormat field previously provided for dynamic rendering. + (#7166, #6855, #5446, #5037) [@shawnhatori] + +Other changes: + +- Menus, Popups: Fixed menus and popups with ChildWindow flag erroneously not displaying + a scrollbar when contents is over parent viewport size. (#7287, #7063) [@ZingBallyhoo] +- Backends: SDL2, SDL3: Handle gamepad disconnection + fixed increasing gamepad reference + counter continuously. Added support for multiple simultaneous gamepads. + Added ImGui_ImplSDL2_SetGamepadMode()) function to select whether to automatically pick + first available gamepad, all gamepads, or specific gamepads. + (#3884, #6559, #6890, #7180) [@ocornut, @lethal-guitar, @wn2000, @bog-dan-ro] +- Backends: SDL3: Fixed gamepad handling. (#7180) [@bog-dan-ro] +- Backends: SDLRenderer3: query newly added SDL_RenderViewportSet() to not restore + a wrong viewport if none was initially set. +- Backends: DirectX9: Using RGBA format when allowed by the driver to avoid CPU side + conversion. (#6575) [@Demonese] +- Internals: Fixed ImFileOpen not working before context is created, preventing creation + of a font atlas before main context creation. (#7314, #7315) [@PathogenDavid, @ocornut] + + +----------------------------------------------------------------------- + VERSION 1.90.2 (Released 2024-02-09) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.2 + +Breaking changes: + +- Commented out ImGuiIO::ImeWindowHandle obsoleted in 1.87 in favor of writing + to 'void* ImGuiViewport::PlatformHandleRaw'. +- Backends: WebGPU: ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure + instead of variety of parameters, allowing for easier further changes. (#7240) + +Other changes: + +- Nav: keyboard/gamepad activation mark widgets as held to give better visual feedback. +- Nav: tweak to logic marking navigated item as hovered when using keyboard, allowing + the hover highlight to stay even while another item is activated. +- Nav: Fixed SetKeyboardFocusHere() not working when current nav focus is in different scope, + regression from 1.90.1 related to code scoping Tab presses to local scope. (#7226) [@bratpilz] +- Nav: Fixed pressing Escape while in a child window with _NavFlattened flag. (#7237) +- Nav: Improve handling of Alt key to toggle menu so that key ownership may be claimed on + individual left/right alt key without interfering with the other. +- Nav, Menus: Fixed click on a BeginMenu() followed by right-arrow from making the child menu + reopen and flicker (using ImGuiPopupFlags_NoReopen). +- Nav: ImGuiWindowFlags_NoNavInputs is tested during scoring so NavFlattened windows can use it. +- Popups: OpenPopup(): added ImGuiPopupFlags_NoReopen flag to specifically not close and reopen + a popup when it is already open. (#1497, #1533) + (Note that this differs from specific handling we already have in place for the case of calling + OpenPopup() repeatedly every frame: we already didn't reopen in that specific situation, otherwise + the effect would be very disastrous in term of confusion, as reopening would steal focus). +- Popups: Slight change to popup closing logic (e.g. after focusing another window) which skipped + over popups that are also child windows. +- Combo: Fixed not reusing windows optimally when used inside a popup stack. +- Debug Tools: Metrics: Fixed debug break in SetShortcutRouting() not handling ImGuiMod_Shortcut redirect. +- Debug Tools: Metrics: Improved Monitors and Viewports minimap display. Highlight on hover. +- Debug Tools: Debug Log: Added "Input Routing" logging. +- Debug Tools: Added "nop" to IM_DEBUG_BREAK macro on GCC to work around GDB bug (#7266) [@Peter0x44] +- Backends: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by + allocating one extra semaphore than in-flight frames. (#7236) [@mklefrancois] +- Backends: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size. (#3957) +- Backends: Vulkan: Fixed handling of ImGui_ImplVulkan_InitInfo::MinAllocationSize field. (#7189, #4238) +- Backends: WebGPU: Added ImGui_ImplWGPU_InitInfo::PipelineMultisampleState. (#7240) +- Backends: WebGPU: Filling all WGPUDepthStencilState fields explicitly as a recent Dawn + update stopped setting default values. (#7232) [@GrigoryGraborenko] +- Backends: WebGPU: Fixed pipeline layout leak. (#7245) [@rajveermalviya] +- Backends: OpenGL3: Backup and restore GL_PIXEL_UNPACK_BUFFER. (#7253) +- Internals: Many improvements related to yet unpublicized shortcut routing and input ownership systems. +- Internals: InputText: Added internal helpers to force reload of user-buf when active. (#2890) [@kudaba, @ocornut] + Often requested in some form (#6962, #5219, #3290, #4627, #5054, #3878, #2881, #1506, #1216, #968), + and useful for interactive completion/suggestions popups (#2057, #718) + + +----------------------------------------------------------------------- + VERSION 1.90.1 (Released 2024-01-10) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.1 + +Breaking changes: + +- imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. + Prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls. +- Removed CalcListClipping() marked obsolete in 1.86. (#3841) + Prefer using ImGuiListClipper which can return non-contiguous ranges. +- Internals, Columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting + to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80. +- Commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter. (#2625, #7143) + +Other changes: + +- Windows: + - BeginChild(): Fixed auto-resizing erroneously limiting size to host viewport + minus padding. There are no limit to a child width/height. (#7063) [@Devyre] + - BeginChild(): Resize borders rendered even when ImGuiWindowFlags_NoBackground + is specified. (#1710, #7194) + - Fixed some auto-resizing path using style.WindowMinSize.x (instead of x/y) + for both axises since 1.90. (#7106) [@n0bodysec] + - Scrolling: internal scrolling value is rounded instead of truncated, as a way to reduce + speed asymmetry when (incorrectly) attempting to scroll by non-integer amount. (#6677) +- Navigation (Keyboard/gamepad): + - Nav, IO: SetNextFrameWantCaptureKeyboard(false) calls are not overridden back to true when + navigation is enabled. SetNextFrameWantCaptureKeyboard() is always higher priority. (#6997) + - Nav: Activation can also be performed with Keypad Enter. (#5606) +- Drag and Drop: + - Fixed drop target highlight on items temporarily pushing a widened clip rect + (namely Selectables and Treenodes using SpanAllColumn flag) so the highlight properly covers + all columns. (#7049, #4281, #3272) +- InputText: + - InputTextMultiline: Fixed Tab character input not repeating (1.89.4 regression). + - InputTextMultiline: Tabbing through a multi-line text editor which allows Tab character inputs + (using the ImGuiInputTextFlags_AllowTabInput flag) doesn't automatically activate it, in order + to allow passing through multiple widgets easily. (#3092, #5759, #787) +- Drags, Sliders, Inputs: + - DragScalarN, SliderScalarN, InputScalarN: Fixed incorrect pushes into ItemWidth + stack when number of components is 1. [#7095] [@Nahor] + - Drags, Sliders, Inputs: removed all attempts to filter non-numerical characters during text + editing. Invalid inputs not applied to value, visibly reverted after validation. (#6810, #7096) + - Drags, Sliders, Inputs: removal of filter means that "nan" and "inf" values may be input. (#7096) + - DragScalarN, SliderScalarN, InputScalarN, PushMultiItemsWidths: improve multi-components + width computation to better distribute the error. (#7120, #7121) [@Nahor] +- Menus: + - Tweaked hover slack logic, adding an extra timeout to avoid situations where a slow vertical + movements toward another parent BeginMenu() can keep the wrong child menu open. (#6671, #6926) +- Color Editors: + - ColorEdit: Layout tweaks for very small sizes. (#7120, #7121) + - ColorPicker: Fixed saturation/value cursor radius not scaling properly. +- Tabs: Added ImGuiTabItemFlags_NoAssumedClosure to enable app to react on closure attempt, + without having to draw an unsaved document marker (ImGuiTabItemFlags_UnsavedDocument sets + _NoAssumedClosure automatically). (#7084) +- Debug Tools: + - Added io.ConfigDebugIsDebuggerPresent option. When enabled, this adds buttons in various + locations of Metrics/Debugger to manually request a debugger break: + - Request a debug break in a Begin() call. + - Request a debug break in a ItemAdd() call via debug log and hovering 0xXXXXXX identifiers. + - Request a debug break in a BeginTable() call. + - Request a debug break in a SetShortcutRouting()/Shortcut() call. [Internal] + - Metrics: Reorganize Tools menu. + - Added DebugFlashStyleColor() to identify a style color. Added to Style Editor. + - Debug Log: Hide its own clipper log to reduce noise in the output. (#5855) + - Debug Log: Clicking any filter with SHIFT held enables it for 2 frames only, + making it easier when dealing with spammy logs. (#5855) +- Settings: Fixed an issue marking settings as dirty when merely clicking on a border or resize + grip without moving it. +- Misc: Added IMGUI_USER_H_FILENAME to change the path included when using + IMGUI_INCLUDE_IMGUI_USER_H. (#7039) [@bryceberger] +- Misc: Rework debug display of texture id in Metrics window to avoid compile-error when + ImTextureID is defined to be larger than 64-bits. (#7090) +- Misc: Added extra courtesy ==/!= operators when IMGUI_DEFINE_MATH_OPERATORS is defined. +- Misc: Fixed text functions fast-path for handling "%s" and "%.*s" to handle null pointers gracefully, + like most printf implementations. (#7016, #3466, #6846) [@codefrog2002] +- Misc: Renamed some defines in imstb_textedit.h to avoid conflicts when using unity/jumbo builds + on a codebase where another copy of the library is used. +- Misc: During shutdown, check that io.BackendPlatformUserData and io.BackendRendererUserData are NULL + in order to catch cases where backend was not shut down. (#7175) +- Misc: Reworked Issue Template to a shinier and better form. (#5927) [@Panquesito7, @PathogenDavid, @ocornut] +- Backends: + - GLFW, Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to + register canvas selector and auto-resize GLFW window. (#6751) [@Traveller23, @ypujante] + - GLFW: Fixed Windows specific hooks to use Unicode version of WndProc even when + compiling in MBCS mode. (#7174) [@kimidaisuki22] + - OpenGL3: Update GL3W based imgui_impl_opengl3_loader.h to load libGL.so variants in + case of missing symlink. Fix 1.90 regression for some distros. (#6983) + - Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs + vkDestroyCommandPool(). (#7075) [@FoonTheRaccoon] + - Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous + "best practice" validation layer. (#7189, #4238) [@philae-ael] + - Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT + as we don't reset them. + - WebGPU: Fixed wgpuRenderPassEncoderSetScissorRect() crash when rendering modal window's + dimming layer, which has an unclipped value in ImDrawCmd::ClipRect. (#7191) [@aparis69] +- Examples: + - Examples: GLFW+Emscripten: Fixed examples not consistently resizing according to host canvas. + (#6751) [@Traveller23, @ypujante] + - Examples: SDL3: Minor fixes following recent SDL3 in-progress development. + + +----------------------------------------------------------------------- + VERSION 1.90.0 (Released 2023-11-15) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90 + +Breaking changes: + + - BeginChild(): Upgraded 'bool border = false' parameter to 'ImGuiChildFlags flags = 0'. + Added ImGuiChildFlags_Border value. As with our prior "bool-to-flags" API updates, + the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a + smoother transition, meaning all existing calls will still work. + If you want to neatly transition your call sites: + Before: BeginChild("Name", size, true) + After: BeginChild("Name", size, ImGuiChildFlags_Border) + Before: BeginChild("Name", size, false) + After: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None) + Existing code will still work as 'ImGuiChildFlags_Border == true', but you are encouraged to update call sites. + - BeginChild(): Added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for + the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense + for use with BeginChild() anyhow, passing it to Begin() had no effect. Now that we accept + child-flags we are moving it there. (#462) + Before: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding); + After: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0); + Kept inline redirection enum (will obsolete later) so existing code will work. + - BeginChildFrame()/EndChildFrame(): removed functions in favor of using BeginChild() with + the ImGuiChildFlags_FrameStyle flag. Kept inline redirection function (will obsolete). + Those functions were merely PushStyle/PopStyle helpers and custom versions are easy to create. + (The removal isn't so much motivated by needing to add the feature in BeginChild(), but by the + necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.) + - Debug Tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), + as earlier name was misleading. Kept inline redirection function. (#4631) + - IO: Removed io.MetricsActiveAllocations introduced in 1.63, was displayed in Metrics and unlikely to + be accessed by end-user. Value still visible in the UI and easily to recompute from a delta. + - Defining IMGUI_DISABLE_OBSOLETE_FUNCTIONS now automatically defines IMGUI_DISABLE_OBSOLETE_KEYIO. (#4921) + - Removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define. (#4537) + - ListBox, Combo: Changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. + Before: + getter type: bool (*getter)(void* user_data, int idx, const char** out_text) + function: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...); + function: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...); + After: + getter type: const char* (*getter)(void* user_data, int idx) + function: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...); + function: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...); + Old type was unnecessarily complex and harder to wrap in e.g. a lambda. Kept inline redirection function (will obsolete). + - Commented out obsolete redirecting enums/functions that were marked obsolete two years ago: + - GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. + Consider that generally 'GetContentRegionAvail().x' is often more correct and more useful. + - ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX names. + Read 1.82 changelog for details + grep commented names in sources. + - Commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for + AddRect()/AddRectFilled()/PathRect()/AddImageRounded(). -> Use ImDrawFlags_RoundCornersXXX flags. + Read 1.82 changelog for details. + - Backends: Vulkan: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own + command-buffer to upload fonts. Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary. + No need to call ImGui_ImplVulkan_CreateFontsTexture() as it is done automatically in ImGui_ImplVulkan_NewFrame(). + You can call ImGui_ImplVulkan_CreateFontsTexture() manually if you need to reload the font atlas texture. + (#6943, #6715, #6327, #3743, #4618) + +Other changes: + +- Windows: + - BeginChild(): Added ImGuiChildFlags_ResizeX and ImGuiChildFlags_ResizeY to allow resizing + child windows from the bottom/right border (toward layout direction). Resized child windows + settings are saved and persistent in .ini file. (#1710) + - BeginChild(): Added ImGuiChildFlags_Border as a replacement for 'bool border = true' parameter. + - BeginChild(): Added ImGuiChildFlags_AutoResizeX and ImGuiChildFlags_AutoResizeY to auto-resize + on one axis, while generally providing a size on the other axis. (#1666, #1395, #1496, #1710) + e.g. BeginChild("name", {-FLT_MIN, 0.0f}, ImGuiChildFlags_AutoResizeY); + - Size is only reevaluated if the child window is within visible boundaries or just appearing. + This allows coarse clipping to be performed and auto-resizing childs to return false when + hidden because of being scrolled out. + - Combining this with also specifying ImGuiChildFlags_AlwaysAutoResize disables + this optimization, meaning child contents will never be clipped (not recommended). + - Please be considerate that child are full windows and carry significant overhead: + combining auto-resizing for both axises to create a non-scrolling child to merely draw + a border would be better more optimally using BeginGroup(). (see #1496) + (until we come up with new helpers for framed groups and work-rect adjustments). + - BeginChild(): made it possible to use SetNextWindowSizeConstraints() rectangle, often + useful when ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY. (#1666, #1395, #1496) + Custom constraint callback are not supported with child window. + - BeginChild(): Added ImGuiChildFlags_FrameStyle as a replacement for BeginChildFrame(), + use it to make child window use FrameBg, FrameRounding, FrameBorderSize, FramePadding + instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. + - Popups: clarified meaning of 'p_open != NULL' in BeginPopupModal() + set back user value + to false when popup is closed in ways other than clicking the close button. (#6900) + - Double-clicking lower-left resize grip auto-resize (like lower-right one). + - Double-clicking bottom or right window border auto-resize on a singles axis. + - Use relative mouse movement for border resize when the border geometry has moved + (e.g. resizing a child window triggering parent scroll) in order to avoid resizing + feedback loops. Unless manually mouse-wheeling while border resizing. (#1710) +- Separators: + - Altered end-points to use more standard boundaries. (#205, #4787, #1643) + Left position is always current cursor X position, right position is always work-rect + rightmost edge. It effectively means that: + - A separator in the root of a window will end up a little more distant from edges + than previously (essentially following WindowPadding instead of clipping edges). + - A separator inside a table cell end up a little distance from edges instead of + touching them (essentially following CellPadding instead of clipping edges). + - Matches tree indentation (was not the case before). + - Matches SeparatorText(). (#1643) + - Makes things correct inside groups without specific/hard-coded handling. (#205) + - Support legacy behavior when used inside old Columns(), as we favored that idiom back then, + only different is left position follows indentation level, to match calling a Separator() + inside or outside Columns(). +- Tooltips: + - Made using SetItemTooltip()/IsItemHovered(ImGuiHoveredFlags_ForTooltip) defaults to + activate tooltips on disabled items. This is done by adding ImGuiHoveredFlags_AllowWhenDisabled + to the default value of style.HoverFlagsForTooltipMouse/HoverFlagsForTooltipNav. (#1485) + - Made is possible to combine ImGuiHoveredFlags_ForTooltip with a ImGuiHoveredFlags_DelayXXX + override. (#1485) +- Drag and Drop: + - Reworked drop target highlight: reduce rectangle to its visible portion, and then expand + slightly. A full rectangle is always visible and it may protrude slightly. (#4281, #3272) + - Fixed submitting a tooltip from drop target location when using AcceptDragDropPayload() + with ImGuiDragDropFlags_AcceptNoPreviewTooltip and submitting a tooltip manually. +- Tables: + - Added angled headers support. You need to set ImGuiTableColumnFlags_AngledHeader on selected + columns and call TableAngledHeadersRow(). Added style.TableAngledHeadersAngle style option. (#6917) + - Added ImGuiTableFlags_HighlightHoveredColumn flag, currently highlighting column header. + - Fixed an edge-case when no columns are visible + table scrollbar is visible + user + code is always testing return value of TableSetColumnIndex() to coarse clip. With an active + clipper it would have asserted. Without a clipper, the scrollbar range would be wrong. + - Request user to submit contents when outer host-window is requesting auto-resize, + so a scrolling table can contribute to initial window size. (#6510) + - Fixed subtle drawing overlap between borders in some situations. + - Fixed bottom-most and right-most outer border offset by one. (#6765, #3752) [@v-ein] + - Fixed top-most and left-most outer border overlapping inner clip-rect when scrolling. (#6765) + - Fixed top-most outer border being drawn with both TableBorderLight and TableBorderStrong + in some situations, causing the earlier to be visible underneath when alpha is not 1.0f. + - Fixed right-clicking right-most section (past right-most column) from highlighting a column. + - Fixed an issue with ScrollX enabled where an extraneous draw command would be created. +- Menus: + - Menus: Fixed a bug where activating an item in a child-menu and dragging mouse over the + parent-menu would erroneously close the child-menu. (Regression from 1.88). (#6869) + - MenuBar: Fixed an issue where layouting an item in the menu-bar would erroneously + register contents size in a way that would affect the scrolling layer. + Was most often noticeable when using an horizontal scrollbar. (#6789) +- InputText: + - InputTextMultiline: Fixed a crash pressing Down on last empty line of a multi-line buffer. + (regression from 1.89.2, only happened in some states). (#6783, #6000) + - InputTextMultiline: Fixed Tabbing cycle leading to a situation where Enter key wouldn't + be accepted by the widget when navigation highlight is visible. (#6802, #3092, #5759, #787) +- Nav: Tabbing always enable nav highlight when ImGuiConfigFlags_NavEnableKeyboard is set. + Previously was inconsistent and only enabled when stepping through a non-input item. + (#6802, #3092, #5759, #787) +- TreeNode: Added ImGuiTreeNodeFlags_SpanAllColumns for use in tables. (#3151, #3565, #2451, #2438) +- TabBar: Fixed position of unsaved document marker (ImGuiTabItemFlags_UnsavedDocument) which was + accidentally offset in 1.89.9. (#6862) [@alektron] +- ColorPicker4(): Fixed ImGuiColorEditFlags_NoTooltip not being forwarded to individual DragFloat3 + sub-widgets which have a visible color preview when ImGuiColorEditFlags_NoSidePreview is also set. (#6957) +- BeginGroup(): Fixed a bug pushing line lower extent too far down when called after a call + to SameLine() followed by manual cursor manipulation. +- BeginCombo(): Added ImGuiComboFlags_WidthFitPreview flag. (#6881) [@mpv-enjoyer] +- BeginListBox(): Fixed not consuming SetNextWindowXXX() data when returning false. +- Fonts: + - Argument 'float size_pixels' passed to AddFontXXX() functions is now rounded to lowest integer. + This is because our layout/font system currently doesn't fully support non-integer sizes. Until + it does, this has been a common pitfall leading to more or less subtle issues. (#3164, #3309, #6800) + - Better assert during load when passing truncated font data or wrong data size. (#6822) + - Ensure calling AddFontXXX function doesn't invalidates ImFont's ConfigData pointers + prior to building again. (#6825) + - Added ImFontConfig::RasterizerDensity field to increase texture size of rendered glyphs + without altering other metrics. Among other things, this makes it easier to have zooming code + swapping between 2 fonts (e.g. a 100% and a 400% fonts) depending on current scale. (#6925) [@thedmd] + Important: if you increase this it is expected that you would render the font with a scale of + similar value or magnitude. Merely increasing this without increasing scale may lower quality. + - imgui_freetype: Added support for RasterizerDensity. (#6925) [@thedmd] + - imgui_freetype: Fixed a warning and leak in IMGUI_ENABLE_FREETYPE_LUNASVG support. (#6842, #6591) +- Inputs: Added IsKeyChordPressed() helper function e.g. IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_S). + (note that ImGuiMod_Shortcut may be used as an alias for Cmd on OSX and Ctrl on other systems). +- Misc: Most text functions also treat "%.*s" (along with "%s") specially to bypass formatting. (#3466, #6846) +- IO: Add extra keys to ImGuiKey enum: ImGuiKey_F13 to ImGuiKey_F24. (#6891, #4921) +- IO: Add extra keys to ImGuiKey enum: ImGuiKey_AppBack, ImGuiKey_AppForward. (#4921) +- IO: Setting io.WantSetMousePos ignores incoming MousePos events. (#6837, #228) [@bertaye] +- Debug Tools: Metrics: Added log of recent alloc/free calls. +- Debug Tools: Metrics: Added "Show groups rectangles" in tools. +- ImDrawList: Added AddEllipse(), AddEllipseFilled(), PathEllipticalArcTo(). (#2743) [@Doohl] +- ImVector: Added find_index() helper. +- Demo: Added "Drag and Drop -> Tooltip at target location" demo. +- Demo: Added "Layout -> Child Windows -> Manual-resize" demo. (#1710) +- Demo: Added "Layout -> Child Windows -> Auto-resize with constraints" demo. (#1666, #1395, #1496, #1710) +- Demo: Partly fixed "Examples -> Constrained-resizing window" custom constrains demo. (#6210) [@cfillion] +- Backends: Vulkan: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own + command-buffer to upload fonts. Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary. + No need to call ImGui_ImplVulkan_CreateFontsTexture() as it is done automatically in ImGui_ImplVulkan_NewFrame(). + You can call ImGui_ImplVulkan_CreateFontsTexture() manually if you need to reload font atlas texture. + Fixed leaks, and added ImGui_ImplVulkan_DestroyFontsTexture() (probably no need to call this directly). + (#6943, #6715, #6327, #3743, #4618) + [@helynranta, @thomasherzog, @guybrush77, @albin-johansson, @MiroKaku, @benbatya-fb, @ocornut] +- Backends: GLFW: Clear emscripten's MouseWheel callback before shutdown. (#6790, #6096, #4019) [@halx99] +- Backends: GLFW: Added support for F13 to F24 function keys. (#6891) +- Backends: SDL2, SDL3: Added support for F13 to F24 function keys, AppBack, AppForward. (#6891) +- Backends: SDL3: Updates for recent API changes. (#7000, #6974) +- Backends: Win32: Added support for F13 to F24 function keys, AppBack, AppForward. (#6891) +- Backends: Win32: Added support for keyboard codepage conversion for when application + is compiled in MBCS mode and using a non-Unicode window. (#6785, #6782, #5725, #5961) [@sneakyevil] +- Backends: Win32: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows + doesn't emit it (same behavior as GLFW/SDL). (#6859) [@thedmd, @SuperWangKai] +- Backends: OpenGL3: rename symbols in our internal loader so that LTO compilation with another + copy of gl3w becomes possible. (#6875, #6668, #4445) [@nicolasnoble] +- Backends: OpenGL3: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead + of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983) +- Backends: OSX: Added support for F13 to F20 function keys. Support mapping F13 to PrintScreen. (#6891) +- Examples: GLFW+Vulkan, SDL+Vulkan: Simplified and removed code due to backend improvements. +- Internals: Renamed ImFloor() to ImTrunc(). Renamed ImFloorSigned() to ImFloor(). (#6861) + + +----------------------------------------------------------------------- + VERSION 1.89.9 (Released 2023-09-04) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.9 + +Breaking changes: + +- Clipper: Renamed IncludeRangeByIndices(), also called ForceDisplayRangeByIndices() + before 1.89.6, to IncludeItemsByIndex(). Kept inline redirection function. (#6424, #3841) + +Other changes: + +- Tables: Made it possible to use SameLine(0,0) after TableNextColumn() or + TableSetColumnIndex() in order to reuse line pos/height from previous cell. (#3740) +- Tables: Made it possible to change style.CellPadding.y between rows. (#3740) +- Nav, TreeNode: Pressing Left with ImGuiTreeNodeFlags_NavLeftJumpsBackHere now goes + through proper navigation logic: honor scrolling and selection. (#1079, #1131) +- Sliders: Fixed an integer overflow and div-by-zero in SliderInt() when + v_max=INT_MAX (#6675, #6679) [@jbarthelmes] +- Windows: Layout of Close/Collapse buttons uses style.ItemInnerSpacing.x between items, + stopped incorrectly using FramePadding in a way where hit-boxes could overlap when + setting large values. (#6749) +- TabBar, Style: added style.TabBarBorderSize and associated ImGuiStyleVar_TabBarBorderSize. + Tweaked rendering of that separator to allow thicker values. (#6820, #4859, #5022, #5239) +- InputFloat, SliderFloat, DragFloat: always turn both '.' and ',' into the current decimal + point character when using Decimal/Scientific character filter. (#6719, #2278) [@adamsepp] +- ColorEdit, ColorPicker: Manipulating options popup don't mark item as edited. (#6722) + (Note that they may still be marked as Active/Hovered.) +- Clipper: Added IncludeItemByIndex() helper to include a single item. (#6424, #3841) +- Clipper: Fixed a bug if attempt to force-include a range which matches an already + included range, clipper would end earlier. (#3841) +- ImDrawData: Fixed an issue where TotalVtxCount/TotalIdxCount does not match the sum + of individual ImDrawList's buffer sizes when a dimming/modal background is rendered. (#6716) +- ImDrawList: Automatically calling ChannelsMerge() if not done after a split. +- ImDrawList: Fixed OOB access in _CalcCircleAutoSegmentCount when passing excessively + large radius to AddCircle(). (#6657, #5317) [@EggsyCRO, @jdpatdiscord] +- IO: Exposed io.PlatformLocaleDecimalPoint to configure decimal point ('.' or ',') for + languages needing it. Should ideally be set to the value of '*localeconv()->decimal_point' + but our backends don't do it yet. (#6719, #2278) +- IO: Fixed io.AddMousePosEvent() and io.AddMouseButtonEvent() writing MouseSource to + wrong union section. Was semantically incorrect and accidentally had no side-effects + with default compiler alignment settings. (#6727) [@RickHuang2001] +- Misc: Made multiple calls to Render() during the same frame early out faster. +- Debug Tools: Metrics: Fixed "Drawlists" section and per-viewport equivalent + appearing empty (regression in 1.89.8). +- Demo: Reorganized "Examples" menu. +- Demo: Tables: Demonstrate using SameLine() between cells. (#3740) +- Demo: Tables: Demonstrate altering CellPadding.y between rows. (#3740) +- Demo: Custom Rendering: Demonstrate out-of-order rendering using ImDrawListSplitter. +- Backends: SDL2,SDL3: added ImGui_ImplSDL2_InitForOther()/ImGui_ImplSDL3_InitForOther() + for consistency (matching GLFW backend) and as most initialization paths don't actually + need to care about rendering backend. +- Examples: Emscripten+WebGPU: Fixed WGPUInstance creation process + use preferred + framebuffer format. (#6640, #6748) [@smileorigin] + + +----------------------------------------------------------------------- + VERSION 1.89.8 (Released 2023-08-01) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.8 + +Breaking changes: + +- IO: Obsoleted io.ClearInputCharacters() (added in 1.47) as it now ambiguous + and often incorrect/misleading considering the existence of a higher-level + input queue. This is automatically cleared by io.ClearInputsKeys(). (#4921) +- ImDrawData: CmdLists[] array is now owned, changed from 'ImDrawList**' to + 'ImVector'. Majority of users shouldn't be affected, but you + cannot compare to NULL nor reassign manually anymore. + Instead use AddDrawList(). Allocation count are identical. (#6406, #4879, #1878) + +Other changes: + +- Fonts: ImFontConfig::OversampleH now defaults to 2 instead of 3, since the + quality increase is largely minimal. +- Fonts, imgui_freetype: Added support to render OpenType SVG fonts using lunasvg. + Requires enabling IMGUI_ENABLE_FREETYPE_LUNASVG along with IMGUI_ENABLE_FREETYPE, + and providing headers/libraries for lunasvg. (#6591, #6607) [@sakiodre] +- ImDrawData: CmdLists[] array is now an ImVector<> owned by ImDrawData rather + than a pointer to internal state. + - This makes it easier for user to create their own or append to an existing draw data. + Added a ImDrawData::AddDrawList() helper function to do that. (#6406, #4879, #1878) + - This makes it easier to perform a deep-swap instead of a deep-copy, as array + ownership is now clear. (#6597, #6475, #6167, #5776, #5109, #4763, #3515, #1860) + - Syntax and allocation count are otherwise identical. +- Fixed CTRL+Tab dimming background assert when target window has a callback + in the last ImDrawCmd. (#4857, #5937) +- IsItemHovered: Fixed ImGuiHoveredFlags_ForTooltip for Keyboard/Gamepad navigation, + got broken prior to 1.89.7 due to an unrelated change making flags conflict. (#6622, #1485) +- InputText: Fixed a case where deactivation frame would write to underlying + buffer or call CallbackResize although unnecessary, in a frame where the + return value was false. +- Tables: fixed GetContentRegionAvail().y report not taking account of lower cell + padding or of using ImGuiTableFlags_NoHostExtendY. Not taking it into account + would make the idiom of creating vertically bottom-aligned content (e.g. a child + window) inside a table make the parent window erroneously have a scrollbar. (#6619) +- Tables: fixed calculation of multi-instance shared decoration/scrollbar width of + scrolling tables, to avoid flickering width variation when resizing down a table + hosting a child window. (#5920, #6619) +- Scrollbar: layout needs to take account of window border size, so a border size + will slightly reduce scrollbar size. Generally we tried to make it that window + border size has no incidence on layout but this can't work with thick borders. (#2522) +- IO: Added io.ClearEventsQueue() to clear incoming inputs events. (#4921) + May be useful in conjunction with io.ClearInputsKeys() if you need to clear + both current inputs state and queued events (e.g. when using blocking native + dialogs such as Windows's ::MessageBox() or ::GetOpenFileName()). +- IO: Changed io.ClearInputsKeys() specs to also clear current frame character buffer + (what now obsoleted io.ClearInputCharacters() did), as this is effectively the + desirable behavior. +- Misc: Added IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION config macro to disable + stb_sprintf implementation when using IMGUI_USE_STB_SPRINTF. (#6626) [@septag] +- Misc: Avoid stb_textedit.h reincluding string.h while in a namespace, which + messes up with building with Clang Modules. (#6653, #4791) [@JohelEGP] +- Demo: Better showcase use of SetNextItemAllowOverlap(). (#6574, #6512, #3909, #517) +- Demo: Showcase a few more InputText() flags. +- Backends: Made all backends sources files support global IMGUI_DISABLE. (#6601) +- Backends: GLFW: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used + differently. User may set ImGuiConfigFlags_NoMouse if desired. (#5625, #6609) [@scorpion-26] +- Backends: WebGPU: Update for changes in Dawn. (#6602, #6188) [@williamhCode] +- Examples: Vulkan: Creating minimal descriptor pools to fit only what is needed by + example. (#6642) [@SaschaWillem] + + +----------------------------------------------------------------------- + VERSION 1.89.7 (Released 2023-07-04) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.7 + +Breaking changes: + +- Moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. + As the fields were added in 1.89 and expected to be left unchanged by most users, or only + tweaked once during app initialisation, we are exceptionally accepting the breakage. + Majority of users should not even notice. +- Overlapping items: (#6512, #3909, #517) + - Added 'SetNextItemAllowOverlap()' (called before an item) as a replacement for using + 'SetItemAllowOverlap()' (called after an item). This is roughly equivalent to using the + legacy 'SetItemAllowOverlap()' call (public API) + ImGuiButtonFlags_AllowOverlap (internal). + - Obsoleted 'SetItemAllowOverlap()': it didn't and couldn't work reliably since 1.89 (2022-11-15), + and relied on ambiguously defined design. Use 'SetNextItemAllowOverlap()' before item instead. + - Selectable, TreeNode: When using ImGuiSelectableFlags_AllowOverlap/ImGuiTreeNodeFlags_AllowOverlap + and holding item held, overlapping widgets won't appear as hovered. (#6512, #3909) + While this fixes a common small visual issue, it also means that calling IsItemHovered() + after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't + use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610) + - Renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap'. + - Renamed 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap' + - Kept redirecting enums (will obsolete). + +Other changes: + +- Tooltips/IsItemHovered() related changes: + - Tooltips: Added SetItemTooltip() and BeginItemTooltip() functions. + They are shortcuts for the common idiom of using IsItemHovered(). + - SetItemTooltip("Hello") == if (IsItemHovered(ImGuiHoveredFlags_Tooltip)) { SetTooltip("Hello"); } + - BeginItemTooltip() == IsItemHovered(ImGuiHoveredFlags_Tooltip) && BeginTooltip() + The newly added ImGuiHoveredFlags_Tooltip is meant to facilitate standardizing + mouse hovering delays and rules for a given application. + The previously common idiom of using 'if (IsItemHovered()) { SetTooltip(...); }' + won't use delay or stationary test. + - IsItemHovered: Added ImGuiHoveredFlags_Stationary to require mouse being + stationary when hovering a new item. Added style.HoverStationaryDelay (~0.15 sec). + Once the mouse has been stationary once the state is preserved for same item. (#1485) + - IsItemHovered: Added ImGuiHoveredFlags_ForTooltip as a shortcut for pulling flags + from style.HoverFlagsForTooltipMouse or style.HoverFlagsForTooltipNav depending + on active inputs (#1485) + - style.HoverFlagsForTooltipMouse defaults to 'ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort' + - style.HoverFlagsForTooltipNav defaults to 'ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal'. + - Tooltips: Tweak default offset for non-drag and drop tooltips so underlying items + isn't covered as much. (Match offset for drag and drop tooltips) + - IsItemHovered: Tweaked default value of style.HoverDelayNormal from 0.30 to 0.40, + Tweaked default value of style.HoverDelayShort from 0.10 to 0.15. (#1485) + - IsItemHovered: Added ImGuiHoveredFlags_AllowWhenOverlappedByWindow to ignore window-overlap only. + Option ImGuiHoveredFlags_AllowWhenOverlapped now expand into a combination of both + _AllowWhenOverlappedByWindow + _AllowWhenOverlappedByItem, matching old behavior. +- Overlapping items: (#6512, #3909, #517) + - Most item types should now work with SetNextItemAllowOverlap(). (#6512, #3909, #517) + - Fixed first frame of an overlap highlighting underlying item if previous frame didn't hover anything. + - IsItemHovered: Changed to return false when querying an item using AllowOverlap mode which + is being overlapped. Added ImGuiHoveredFlags_AllowWhenOverlappedByItem to opt-out. (#6512, #3909, #517) +- IsWindowHovered: Added support for ImGuiHoveredFlags_Stationary. +- IsWindowHovered, IsItemHovered: Assert when passed any unsupported flags. +- Tables: Fixed a regression in 1.89.6 leading to the first column of tables with either + ScrollX or ScrollY flags from being impossible to resize. (#6503) +- CollapsingHeader/TreeNode: Fixed text padding when using _Framed+_Leaf flags. (#6549) [@BobbyAnguelov] +- InputText: Fixed not returning true when buffer is cleared while using the + ImGuiInputTextFlags_EscapeClearsAll flag. (#5688, #2620) +- InputText: Fixed a crash on deactivating a ReadOnly buffer. (#6570, #6292, #4714) +- InputText: ImGuiInputTextCallbackData::InsertChars() accept (NULL,NULL) range, in order to conform + to common idioms (e.g. passing .data(), .data() + .size() from a null string). (#6565, #6566, #3615) +- Combo: Made simple/legacy Combo() function not returns true when picking already selected item. + This is consistent with other widgets. If you need something else, you can use BeginCombo(). (#1182) +- Clipper: Rework inner logic to allow functioning with a zero-clear constructor. + This is order to facilitate usage for language bindings (e.g cimgui or dear_binding) + where user may not be calling a constructor manually. (#5856) +- Drag and Drop: Apply default behavior of drag source not reporting itself as hovered + at lower-level, so DragXXX, SliderXXX, InputXXX, Plot widgets are fulfilling it. + (Behavior doesn't apply when ImGuiDragDropFlags_SourceNoDisableHover is set). +- Modals: In the case of nested modal, made sure that focused or appearing windows are + moved below the lowest blocking modal (rather than the highest one). (#4317) +- GetKeyName(): Fixed assert with ImGuiMod_XXX values when IMGUI_DISABLE_OBSOLETE_KEYIO is set. +- Debug Tools: Added 'io.ConfigDebugIniSettings' option to save .ini data with extra + comments. Currently mainly for inspecting Docking .ini data, but makes saving slower. +- Demo: Added more developed "Widgets->Tooltips" section. (#1485) +- Backends: OpenGL3: Fixed support for glBindSampler() backup/restore on ES3. (#6375, #6508) [@jsm174] +- Backends: OpenGL3: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts + lower than 3.2. (#6539, #6333) [@krumelmonster] +- Backends: Vulkan: Added optional support for VK_KHR_dynamic_rendering (Vulkan 1.3+) in the + backend for applications using it. User needs to set 'init_info->UseDynamicRendering = true' + and 'init_info->ColorAttachmentFormat'. RenderPass becomes unused. (#5446, #5037) [@spnda, @cmarcelo] +- Backends: GLFW: Accept glfwGetTime() not returning a monotonically increasing value. + This seems to happens on some Windows setup when peripherals disconnect, and is likely + to also happen on browser+Emscripten. Matches similar 1.89.4 fix in SDL backend. (#6491) +- Examples: Win32+OpenGL3: Changed DefWindowProc() to DefWindowProcW() to match other examples + and support the example app being compiled without UNICODE. (#6516, #5725, #5961, #5975) [@yenixing] + + +----------------------------------------------------------------------- + VERSION 1.89.6 (Released 2023-05-31) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.6 + +Breaking changes: + +- Clipper: Commented out obsolete redirection constructor which was marked obsolete in 1.79: + 'ImGuiListClipper(int items_count, float items_height)' --> Use 'ImGuiListClipper() + clipper.Begin()'. +- Clipper: Renamed ForceDisplayRangeByIndices() to IncludeRangeByIndices(), kept + inline redirection function (introduced in 1.86 and rarely used). (#6424, #3841) +- Commented out obsolete/redirecting functions that were marked obsolete more than two years ago: + - ListBoxHeader() -> use BeginListBox() + - ListBoxFooter() -> use EndListBox() + - Note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for refeence. +- Backends: SDL_Renderer: Renamed 'imgui_impl_sdlrenderer.h/cpp' to 'imgui_impl_sdlrenderer2.h/cpp', + in order to accomodate for upcoming SDL3 and change in its SDL_Renderer API. (#6286) +- Backends: GLUT: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame(). + It needs to be called from the main app loop, like with every other backends. (#6337) [@GereonV] + +Other changes: + +- Window: Fixed resizing from upper border when io.ConfigWindowsMoveFromTitleBarOnly is set. (#6390) +- Tables: Fixed a small miscalculation in TableHeader() leading to an empty tooltip + showing when a sorting column has no visible name. (#6342) [@lukaasm] +- Tables: Fixed command merging when compiling with VS2013 (one array on stack was not + initialized on VS2013. Unsure if due to a bug or UB/standard conformance). (#6377) +- InputText: Avoid setting io.WantTextInputNextFrame during the deactivation frame. + (#6341) [@lukaasm] +- Drag, Sliders: if the format string doesn't contain any %, CTRL+Click to input text will + use the default format specifier for the type. Allow display/input of raw value when using + "enums" patterns (display label instead of value) + allow using when value is hidden. (#6405) +- Nav: Record/restore preferred position on each given axis after a movement on that axis, + then score movement on the other axis using this as a bias. This allows going up and down + between e.g. a large header spanning horizontal space and three-ways-columns, landing + on the same column as before. +- Nav: Fixed navigation within tables/columns where item boundaries goes beyond columns limits, + unclipped bounding boxes would interfere with other columns. (#2221) [@zzzyap, @ocornut] +- Nav: Fixed CTRL+Tab into a root window with only childs with _NavFlattened flags + erroneously initializing default nav layer to menu layer. +- Menus: Fixed an issue when opening a menu hierarchy in a given menu-bar would allow + opening another via simple hovering. (#3496, #4797) +- Fonts: Fixed crash when merging fonts and the first font has no valid glyph. (#6446) [@JaedanC] +- Fonts: Fixed crash when manually specifying an EllipsisChar that doesn't exist. (#6480) +- Misc: Added ImVec2 unary minus operator. (#6368) [@Koostosh] +- Debug Tools: Debug Log: Fixed not parsing 0xXXXXXXXX values for geo-locating on mouse + hover hover when the identifier is at the end of the line. (#5855) +- Debug Tools: Added 'io.ConfigDebugIgnoreFocusLoss' option to disable 'io.AddFocusEvent(false)' + handling. May facilitate interactions with a debugger when focus loss leads to clearing + inputs data. (#4388, #4921) +- Backends: Clear bits sets io.BackendFlags on backend Shutdown(). (#6334, #6335] [@GereonV] + Potentially this would facilitate switching runtime backend mid-session. +- Backends: Win32: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw + Win32/Winapi with OpenGL. (#3218) +- Backends: OpenGL3: Restore front and back polygon mode separately when supported + by context (Desktop 3.0, 3.1, or 3.2+ with compat bit). (#6333) [@GereonV] +- Backends: OpenGL3: Support for glBindSampler() backup/restore on ES3. (#6375) [@jsm174] +- Backends: SDL3: Fixed build on Emscripten/iOS/Android. (#6391) [@jo-codegirl] +- Backends: SDLRenderer3: Added SDL_Renderer for SDL3 backend. (#6286) [@Carcons, @ocornut] +- Examples: Added native Win32+OpenGL3 example. We don't recommend using this setup but we + provide it for completeness. (#3218, #5170, #6086, #2772, #2600, #2359, #2022, #1553) [@learn-more] +- Examples: Vulkan: Use integrated GPU if nothing else is available. (#6359) [@kimidaisuki22] +- Examples: DX9, DX10, DX11: Queue framebuffer resize instead of processing in WM_SIZE, + as some drivers tends to only cleanup after existing the native resize modal loop. (#6374) +- Examples: Added SDL3+SDL_Renderer example. (#6286) +- Examples: Updated all Visual Studio projects and batches to use /utf-8 argument. + + +----------------------------------------------------------------------- + VERSION 1.89.5 (Released 2023-04-13) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.5 + +Other changes: + +- InputText: Reworked prev/next-word behavior to more closely match Visual Studio + text editor. Include '.' as a delimiter and alter varying subtle behavior with how + blanks and separators are treated when skipping words. (#6067) [@ajweeks] +- InputText: Fixed a tricky edge case, ensuring value is always written back on the + frame where IsItemDeactivated() returns true, in order to allow usage without user + retaining underlying data. While we don't really want to encourage user not retaining + underlying data, in the absence of a "late commit" behavior/flag we understand it may + be desirable to take advantage of this trick. (#4714) +- Drag, Sliders: Fixed parsing of text input when '+' or '#' format flags are used + in the format string. (#6259) [@idbrii] +- Nav: Made Ctrl+Tab/Ctrl+Shift+Tab windowing register ownership to held modifier so + it doesn't interfere with other code when remapping those actions. (#4828, #3255, #5641) +- Nav: Made PageUp/PageDown/Home/End navigation also scroll parent windows when + necessary to make the target location fully visible (same as e.g. arrow keys). +- ColorEdit: Fixed shading of S/V triangle in Hue Wheel mode. (#5200, #6254) [@jamesthomasgriffin] +- TabBar: Tab-bars with ImGuiTabBarFlags_FittingPolicyScroll can be scrolled with + horizontal mouse-wheel (or Shift + WheelY). (#2702) +- Rendering: Using adaptive tessellation for RadioButton, ColorEdit preview circles, + Windows Close and Collapse Buttons. +- ButtonBehavior: Fixed an edge case where changing widget type/behavior while active + and using same id could lead to an assert. (#6304) +- Misc: Fixed ImVec2 operator[] violating aliasing rules causing issue with Intel C++ + compiler. (#6272) [@BayesBug] +- IO: Input queue trickling adjustment for touch screens. (#2702, #4921) + This fixes single-tapping to move simulated mouse and immediately click on a widget + that is using the ImGuiButtonFlags_AllowItemOverlap policy. + - This only works if the backend can distinguish TouchScreen vs Mouse. + See 'Demo->Tools->Metrics->Inputs->Mouse Source' to verify. + - Fixed tapping on BeginTabItem() on a touch-screen. (#2702) + - Fixed tapping on CollapsingHeader() with a close button on a touch-screen. + - Fixed tapping on TreeNode() using ImGuiTreeNodeFlags_AllowItemOverlap on a touch-screen. + - Fixed tapping on Selectable() using ImGuiSelectableFlags_AllowItemOverlap on a touch-screen. + - Fixed tapping on TableHeader() on a touch-screen. +- IO: Added io.AddMouseSourceEvent() and ImGuiMouseSource enum. This is to allow backend to + specify actual event source between Mouse/TouchScreen/Pen. (#2702, #2334, #2372, #3453, #5693) +- IO: Fixed support for calling io.AddXXXX functions from inactive context (wrongly + advertised as supported in 1.89.4). (#6199, #6256, #5856) [@cfillion] +- Backends: OpenGL3: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530) +- Backends: OpenGL3: Properly restoring "no shader program bound" if it was the case prior to + running the rendering function. (#6267, #6220, #6224) [@BrunoLevy] +- Backends: Win32: Added support for io.AddMouseSourceEvent() to discriminate Mouse/TouchScreen/Pen. (#2334, #2702) +- Backends: SDL2/SDL3: Added support for io.AddMouseSourceEvent() to discriminate Mouse/TouchScreen. + This is relying on SDL passing SDL_TOUCH_MOUSEID in the event's 'which' field. (#2334, #2702) +- Backends: SDL2/SDL3: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they actually + block text input input and don't only pertain to IME. It's unclear exactly what their relation + is to other IME function such as SDL_SetTextInputRect(). (#6306, #6071, #1953) +- Backends: GLFW: Added support on Win32 only for io.AddMouseSourceEvent() to discriminate + Mouse/TouchScreen/Pen. (#2334, #2702) +- Backends: GLFW: Fixed key modifiers handling on secondary viewports. (#6248, #6034) [@aiekick] +- Backends: Android: Added support for io.AddMouseSourceEvent() to discriminate Mouse/TouchScreen/Pen. + (#6315) [@PathogenDavid] +- Backends: OSX: Added support for io.AddMouseSourceEvent() to discriminate Mouse/Pen. + (#6314) [@PathogenDavid] +- Backends: WebGPU: Align buffers. Use WGSL shaders instead of SPIR-V. Add gamma uniform. (#6188) [@eliemichel] +- Backends: WebGPU: Reorganized to store data in io.BackendRendererUserData like other backends. +- Examples: Vulkan: Fixed validation errors with newer VulkanSDK by explicitly querying and enabling + "VK_KHR_get_physical_device_properties2", "VK_KHR_portability_enumeration", and + VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR. (#6109, #6172, #6101) +- Examples: Windows: Added 'misc/debuggers/imgui.natstepfilter' file to all Visual Studio projects, + now that VS 2022 17.6 Preview 2 support adding Debug Step Filter spec files into projects. +- Examples: SDL3: Updated for latest WIP SDL3 branch. (#6243) +- TestSuite: Added variety of new regression tests and improved/amended existing ones + in imgui_test_engine/ repo. [@PathogenDavid, @ocornut] + + +----------------------------------------------------------------------- + VERSION 1.89.4 (Released 2023-03-14) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.4 + +Breaking Changes: + +- Renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). + Kept inline redirection functions (will obsolete). +- Moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h. + Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA, + it has been frequently requested by people to use our own. We had an opt-in define which was + previously fulfilled by imgui_internal.h. It is now fulfilled by imgui.h. (#6164, #6137, #5966, #2832) + OK: #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h" + Error: #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h" + Added a dedicated compile-time check message to help diagnose this. +- Tooltips: Added 'bool' return value to BeginTooltip() for API consistency. + Please only submit contents and call EndTooltip() if BeginTooltip() returns true. + In reality the function will _currently_ always return true, but further changes down the + line may change this, best to clarify API sooner. Updated demo code accordingly. +- Commented out redirecting enums/functions names that were marked obsolete two years ago: + - ImGuiSliderFlags_ClampOnInput -> use ImGuiSliderFlags_AlwaysClamp + - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite + - ImDrawList::AddBezierCurve() -> use ImDrawList::AddBezierCubic() + - ImDrawList::PathBezierCurveTo() -> use ImDrawList::PathBezierCubicCurveTo() + +Other changes: + +- Nav: Tabbing now cycles through all items when ImGuiConfigFlags_NavEnableKeyboard is set. + (#3092, #5759, #787) + While this was generally desired and requested by many, note that its addition means + that some types of UI may become more fastidious to use TAB key with, if the navigation + cursor cycles through too many items. You can mark items items as not tab-spottable: + - Public API: PushTabStop(false) / PopTabStop() + - Internal: PushItemFlag(ImGuiItemFlags_NoTabStop, true); + - Internal: Directly pass ImGuiItemFlags_NoTabStop to ItemAdd() for custom widgets. +- Nav: Tabbing/Shift-Tabbing can more reliably be used to step out of an item that is not + tab-stoppable. (#3092, #5759, #787) +- Nav: Made Enter key submit the same type of Activation event as Space key, + allowing to press buttons with Enter. (#5606) + (Enter emulates a "prefer text input" activation vs. + Space emulates a "prefer tweak" activation which is to closer to gamepad controls). +- Nav: Fixed an issue with Gamepad navigation when the movement lead to a scroll and + frame time > repeat rate. Triggering a new move request on the same frame as a move + result lead to an incorrect calculation and loss of navigation id. (#6171) +- Nav: Fixed SetItemDefaultFocus() from not scrolling when item is partially visible. + (#2814, #2812) [@DomGries] +- Tables: Fixed an issue where user's Y cursor movement within a hidden column would + have side-effects. +- IO: Lifted constraint to call io.AddEventXXX functions from current context. (#4921, #5856, #6199) +- InputText: Fixed not being able to use CTRL+Tab while an InputText() using Tab + for completion or text data is active (regression from 1.89). +- Drag and Drop: Fixed handling of overlapping targets when smaller one is submitted + before and can accept the same data type. (#6183). +- Drag and Drop: Clear drag and drop state as soon as delivery is accepted in order to + avoid interferences. (#5817, #6183) [@DimaKoltun] +- Debug Tools: Added io.ConfigDebugBeginReturnValueOnce / io.ConfigDebugBeginReturnValueLoop + options to simulate Begin/BeginChild returning false to facilitate debugging user behavior. +- Demo: Updated to test return value of BeginTooltip(). +- Backends: OpenGL3: Fixed restoration of a potentially deleted OpenGL program. If an active + program was pending deletion, attempting to restore it would error. (#6220, #6224) [@Cyphall] +- Backends: Win32: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse positions over + non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162) +- Backends: SDL2, SDL3: Accept SDL_GetPerformanceCounter() not returning a monotonically + increasing value. (#6189, #6114, #3644) [@adamkewley] +- Backends: GLFW: Avoid using glfwGetError() and glfwGetGamepadState() on Emscripten, which + recently updated its GLFW emulation layer to GLFW 3.3 without supporting those. (#6240) +- Examples: Android: Fixed example build for Gradle 8. (#6229, #6227) [@duddel] +- Examples: Updated all examples application to enable ImGuiConfigFlags_NavEnableKeyboard + and ImGuiConfigFlags_NavEnableGamepad by default. (#787) +- Internals: Misc tweaks to facilitate applying an explicit-context patch. (#5856) [@Dragnalith] + + +----------------------------------------------------------------------- + VERSION 1.89.3 (Released 2023-02-14) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.3 + +Breaking Changes: + +- Backends+Examples: SDL2: renamed all unnumbered references to "sdl" to "sdl2". + This is in prevision for the future release of SDL3 and its associated backend. (#6146) + - imgui_impl_sdl.cpp -> imgui_impl_sdl2.cpp + - imgui_impl_sdl.h -> imgui_impl_sdl2.h + - example_sdl_xxxx/ -> example_sdl2_xxxx/ (folders and projects) + +Other changes: + +- SeparatorText(): Added SeparatorText() widget. (#1643) [@phed, @ocornut] + - Added to style: float SeparatorTextBorderSize. + - Added to style: ImVec2 SeparatorTextAlign, SeparatorTextPadding. +- Tables: Raised max Columns count from 64 to 512. (#6094, #5305, #4876, #3572) + The previous limit was due to using 64-bit integers but we moved to bits-array + and tweaked the system enough to ensure no performance loss. +- Tables: Solved an ID conflict issue with multiple-instances of a same table, + due to how unique table instance id was generated. (#6140) [@ocornut, @rodrigorc] +- Inputs, Scrolling: Made horizontal scroll wheel and horizontal scroll direction consistent + across backends/os. (#4019, #6096, #1463) [@PathogenDavid, @ocornut, @rokups] + - Clarified that 'wheel_y > 0.0f' scrolls Up, 'wheel_y > 0.0f' scrolls Down. + Clarified that 'wheel_x > 0.0f' scrolls Left, 'wheel_x > 0.0f' scrolls Right. + - Backends: Fixed horizontal scroll direction for Win32 and SDL backends. (#4019) + - Shift+WheelY support on non-OSX machines was already correct. (#2424, #1463) + (whereas on OSX machines Shift+WheelY turns into WheelX at the OS level). + - If you use a custom backend, you should verify horizontal wheel direction. + - Axises are flipped by OSX for mouse & touch-pad when 'Natural Scrolling' is on. + - Axises are flipped by Windows for touch-pad when 'Settings->Touchpad->Down motion scrolls up' is on. + - You can use 'Demo->Tools->Debug Log->IO" to visualize values submitted to Dear ImGui. + - Known issues remaining with Emscripten: + - The magnitude of wheeling values on Emscripten was improved but isn't perfect. (#6096) + - When running the Emscripten app on a Mac with a mouse, SHIFT+WheelY doesn't turn into WheelX. + This is because we don't know that we are running on Mac and apply our own Shift+swapping + on top of OSX' own swapping, so wheel axises are swapped twice. Emscripten apps may need + to find a way to detect this and set io.ConfigMacOSXBehaviors manually (if you know a way + let us know!), or offer the "OSX-style behavior" option to their user. +- Window: Avoid rendering shapes for hidden resize grips. +- Text: Fixed layouting of wrapped-text block skipping successive empty lines, + regression from the fix in 1.89.2. (#5720, #5919) +- Text: Fixed clipping of single-character "..." ellipsis (U+2026 or U+0085) when font + is scaled. Scaling wasn't taken into account, leading to ellipsis character straying + slightly out of its expected boundaries. (#2775) +- Text: Tweaked rendering of three-dots "..." ellipsis variant. (#2775, #4269) +- InputText: Added support for Ctrl+Delete to delete up to end-of-word. (#6067) [@ajweeks] + (Not adding Super+Delete to delete to up to end-of-line on OSX, as OSX doesn't have it) +- InputText: On OSX, inhibit usage of Alt key to toggle menu when active (used for work skip). +- Menus: Fixed layout of MenuItem()/BeginMenu() when label contains a '\n'. (#6116) [@imkcy9] +- ColorEdit, ColorPicker: Fixed hue/saturation preservation logic from interfering with + the displayed value (but not stored value) of others widgets instances. (#6155) +- PlotHistogram, PlotLines: Passing negative sizes honor alignment like other widgets. +- Combo: Allow SetNextWindowSize() to alter combo popup size. (#6130) +- Fonts: Assert that in each GlyphRanges[] pairs first is <= second. +- ImDrawList: Added missing early-out in AddPolyline() and AddConvexPolyFilled() when + color alpha is zero. +- Misc: Most text functions treat "%s" as a shortcut to no-formatting. (#3466) +- Misc: Tolerate zero delta-time under Emscripten as backends are imprecise in their + values for io.DeltaTime, and browser features such as "privacy.resistFingerprinting=true" + can exacerbate that. (#6114, #3644) +- Backends: OSX: Fixed scroll/wheel scaling for devices emitting events with + hasPreciseScrollingDeltas==false (e.g. non-Apple mices). +- Backends: Win32: flipping WM_MOUSEHWHEEL horizontal value to match other backends and + offer consistent horizontal scrolling direction. (#4019) +- Backends: SDL2: flipping SDL_MOUSEWHEEL horizontal value to match other backends and + offer consistent horizontal scrolling direction. (#4019) +- Backends: SDL2: Removed SDL_MOUSEWHEEL value clamping. (#4019, #6096, #6081) +- Backends: SDL2: Added support for SDL 2.0.18+ preciseX/preciseY mouse wheel data + for smooth scrolling as reported by SDL. (#4019, #6096) +- Backends: SDL2: Avoid calling SDL_SetCursor() when cursor has not changed, as the function + is surprisingly costly on Mac with latest SDL (already fixed in SDL latest trunk). (#6113) +- Backends: SDL2: Implement IME handler to call SDL_SetTextInputRect()/SDL_StartTextInput(). + It will only works with SDL 2.0.18+ if your code calls 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1")' + prior to calling SDL_CreateWindow(). Updated all examples accordingly. (#6071, #1953) +- Backends: SDL3: Added experimental imgui_impl_sdl3.cpp backend. (#6146) [@dovker, @ocornut] + SDL 3.0.0 has not yet been released, so it is possible that its specs/api will change before + release. This backend is provided as a convenience for early adopters etc. We don't recommend + switching to SDL3 before it is released. +- Backends: GLFW: Registering custom low-level mouse wheel handler to get more accurate + scrolling impulses on Emscripten. (#4019, #6096) [@ocornut, @wolfpld, @tolopolarity] +- Backends: GLFW: Added ImGui_ImplGlfw_SetCallbacksChainForAllWindows() to instruct backend + to chain callbacks even for secondary viewports/windows. User callbacks may need to test + the 'window' parameter. (#6142) +- Backends: OpenGL3: Fixed GL loader compatibility with 2.x profiles. (#6154, #4445, #3530) [@grauw] +- Backends: WebGPU: Fixed building for latest WebGPU specs (remove implicit layout generation). + (#6117, #4116, #3632) [@tonygrue, @bfierz] +- Examples: refactored SDL2+GL and GLFW+GL examples to compile with Emscripten. + (#2492, #2494, #3699, #3705) [@ocornut, @nicolasnoble] + The dedicated example_emscripten_opengl3/ has been removed. +- Examples: Added SDL3+GL experimental example. (#6146) +- Examples: Win32: Fixed examples using RegisterClassW() since 1.89 to also call + DefWindowProcW() instead of DefWindowProc() so that title text are correctly converted + when application is compiled without /DUNICODE. (#5725, #5961, #5975) [@markreidvfx] +- Examples: SDL2+SDL_Renderer: Added call to SDL_RenderSetScale() to fix display on a + Retina display (albeit lower-res as our other unmodified examples). (#6121, #6065, #5931). + + +----------------------------------------------------------------------- + VERSION 1.89.2 (Released 2023-01-05) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.2 + +All changes: + +- Tables, Nav, Scrolling: fixed scrolling functions and focus tracking with frozen rows and + frozen columns. Windows now have a better understanding of outer/inner decoration sizes, + which should later lead us toward more flexible uses of menu/status bars. (#5143, #3692) +- Tables, Nav: frozen columns are not part of menu layer and can be crossed over. (#5143, #3692) +- Tables, Columns: fixed cases where empty columns may lead to empty ImDrawCmd. (#4857, #5937) +- Tables: fixed matching width of synchronized tables (multiple tables with same id) when only + some instances have a vertical scrollbar and not all. (#5920) +- Fixed cases where CTRL+Tab or Modal can occasionally lead to the creation of ImDrawCmd with + zero triangles, which would makes the render loop of some backends assert (e.g. Metal with + debugging, Allegro). (#4857, #5937) +- Inputs, IO: reworked ImGuiMod_Shortcut to redirect to Ctrl/Super at runtime instead of + compile-time, being consistent with our support for io.ConfigMacOSXBehaviors and making it + easier for bindings generators to process that value. (#5923, #456) +- Inputs, Scrolling: better selection of scrolling window when hovering nested windows + and when backend/OS is emitting dual-axis wheeling inputs (typically touch pads on macOS). + We now select a primary axis based on recent events, and select a target window based on it. + We expect this behavior to be further improved/tweaked. (#3795, #4559) [@ocornut, @folays] +- InputText: fixed cursor navigation when pressing Up Arrow on the last character of a + multiline buffer which doesn't end with a carriage return. (#6000) +- Text: fixed layouting of wrapped-text block when the last source line is above the + clipping region. Regression added in 1.89. (#5720, #5919) +- Misc: added GetItemID() in public API. It is not often expected that you would use this, + but it is useful for Shortcut() and upcoming owner-aware input functions which wants to + be implemented with public API. +- Fonts: imgui_freetype: fixed a packing issue which in some occurrences would prevent large + amount of glyphs from being packed correctly. (#5788, #5829) +- Fonts: added a 'void* UserData' field in ImFontAtlas, as a convenience for use by + applications using multiple font atlases. +- Demo: simplified "Inputs" section, moved contents to Metrics->Inputs. +- Debug Tools: Metrics: added "Inputs" section, moved from Demo for consistency. +- Misc: fixed parameters to IMGUI_DEBUG_LOG() not being dead-stripped when building + with IMGUI_DISABLE_DEBUG_TOOLS is used. (#5901) [@Teselka] +- Misc: fixed compile-time detection of SSE features on MSVC 32-bits builds. (#5943) [@TheMostDiligent] +- Examples: DirectX10, DirectX11: try WARP software driver if hardware driver is not available. (#5924, #5562) +- Backends: GLFW: Fixed mods state on Linux when using Alt-GR text input (e.g. German keyboard layout), which + could lead to broken text input. Revert a 2022/01/17 change were we resumed using mods provided by GLFW, + turns out they are faulty in this specific situation. (#6034) +- Backends: Allegro5: restoring using al_draw_indexed_prim() when Allegro version is >= 5.2.5. (#5937) [@Espyo] +- Backends: Vulkan: Fixed sampler passed to ImGui_ImplVulkan_AddTexture() not being honored as we were using + an immutable sampler. (#5502, #6001, #914) [@martin-ejdestig, @rytisss] + + +----------------------------------------------------------------------- + VERSION 1.89.1 (Released 2022-11-24) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.1 + +Other changes: + +- Scrolling, Focus: fixed SetKeyboardFocusHere()/SetItemDefaultFocus() during a window-appearing + frame (and associated lower-level functions e.g. ScrollToRectEx()) from not centering item. (#5902) +- Inputs: fixed moving a window or drag and dropping from preventing input-owner-unaware code + from accessing keys. (#5888, #4921, #456) +- Inputs: fixed moving a window or drag and dropping from capturing mods. (#5888, #4921, #456) +- Layout: fixed End()/EndChild() incorrectly asserting if users manipulates cursor position + inside a collapsed/culled window and IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. (#5548, #5911) +- Combo: fixed selected item (marked with SetItemDefaultFocus()) from not being centered when + the combo window initially appears. (#5902). +- ColorEdit: fixed label overlapping when using style.ColorButtonPosition == ImGuiDir_Left to + move the color button on the left side (regression introduced in 1.88 WIP 2022/02/28). (#5912) +- Drag and Drop: fixed GetDragDropPayload() returning a non-NULL value if a drag source is + active but a payload hasn't been submitted yet. This is convenient to detect new payload + from within a drag source handler. (#5910, #143) +- Backends: GLFW: cancel out errors emitted by glfwGetKeyName() when a name is missing. (#5908) +- Backends: WebGPU: fixed validation error with default depth buffer settings. (#5869, #5914) [@kdchambers] + + +----------------------------------------------------------------------- + VERSION 1.89 (Released 2022-11-15) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89 + +Breaking changes: + +- Layout: Obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries. (#5548) + This relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item. + - Previously this would make the window content size ~200x200: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End(); + - Instead, please submit an item: + Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); + - Alternative: + Begin(...) + Dummy(ImVec2(200,200)) + End(); + Content size is now only extended when submitting an item. + With '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert. + Without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it. + (This incorrect pattern has been mentioned or suggested in: #4510, #3355, #1760, #1490, #4152, #150, + threads have been amended to refer to this issue). +- Inputs: ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers. (#4921) + This will require uses of legacy backend-dependent indices to be casted, e.g. + - with imgui_impl_glfw: IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A); + - with imgui_impl_win32: IsKeyPressed('A') -> IsKeyPressed((ImGuiKey)'A') + - etc. however if you are upgrading code you might as well use the backend-agnostic IsKeyPressed(ImGuiKey_A) now. +- Renamed and merged keyboard modifiers key enums and flags into a same set: (#4921, #456) + - ImGuiKey_ModCtrl and ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl + - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift + - ImGuiKey_ModAlt and ImGuiModFlags_Alt -> ImGuiMod_Alt + - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super + Kept inline redirection enums (will obsolete). + This change simplifies a few things, reduces confusion, and will facilitate upcoming + shortcut/input ownership apis. + - The ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends. + - The ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api, + only by third-party extensions. They were however subject to a recent rename + (ImGuiKeyModFlags_XXX -> ImGuiModFlags_XXX) and we are exceptionally commenting out + the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion + and because they were not meant to be used anyway. +- Removed io.NavInputs[] and ImGuiNavInput enum that were used to feed gamepad inputs. + Basically 1.87 already obsoleted them from the backend's point of view, but internally + our navigation code still used this array and enum, so they were still present. + Not anymore! (#4921, #4858, #787, #1599, #323) + Transition guide: + - Official backends from 1.87+ -> no issue. + - Official backends from 1.60 to 1.86 -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating! + - Custom backends not writing to io.NavInputs[] -> no issue. + - Custom backends writing to io.NavInputs[] -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing! + - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[]. + The ImGuiNavInput enum was essentially 1.60's attempt to combine keyboard and gamepad inputs with named + semantic, but the additional indirection and copy added complexity and got in the way of other + incoming work. User's code (other than backends) should not be affected, unless you have custom + widgets intercepting navigation events via the named enums (in which case you can upgrade your code). +- DragInt()/SliderInt(): Removed runtime patching of invalid "%f"/"%.0f" types of format strings. + This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details. +- Changed signature of ImageButton() function: (#5533, #4471, #2464, #1390) + - Added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter. + - Old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1)); + - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values. + - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer. + - New signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1)); + - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier. + - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this. + - As always we are keeping a redirection function available (will obsolete later). +- Removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)'. (#1057) + Must always pass a pointer value explicitly, NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr); + If you used TreePush() replace with TreePush((void*)NULL); +- Removed support for 1.42-era IMGUI_DISABLE_INCLUDE_IMCONFIG_H / IMGUI_INCLUDE_IMCONFIG_H. (#255) + They only made sense before we could use IMGUI_USER_CONFIG. + +Other Changes: + +- Popups & Modals: fixed nested Begin() inside a popup being erroneously input-inhibited. + While it is unusual, you can nest a Begin() inside a popup or modal, it is occasionally + useful to achieve certain things (e.g. to implement suggestion popups #718, #4461). +- Inputs: Standard widgets now claim for key/button ownership and test for them. + - Fixes scenario where e.g. a Popup with a Selectable() reacting on mouse down + (e.g. double click) closes, and behind it is another window with an item reacting + on mouse up. Previously this would lead to both items reacting, now the item in the + window behind won't react on the mouse up since the mouse button ownership has already + been claimed earlier. + - Internals: There are MANY more aspects to this changes. Added experimental/internal APIs + to allow handling input/shorting routing and key ownership. Things will be moved into + public APIs over time. For now this release is a way to test the solidity of underlying + systems while letting early adopters adopters toy with internals. + (#456, #2637, #2620, #2891, #3370, #3724, #4828, #5108, #5242, #5641) +- Scrolling: Tweak mouse-wheel locked window timer so it is shorter but also gets reset + whenever scrolling again. Modulate for small (sub-pixel) amounts. (#2604) +- Scrolling: Mitigated issue where multi-axis mouse-wheel inputs (usually from touch pad + events) are incorrectly locking scrolling in a parent window. (#4559, #3795, #2604) +- Scrolling: Exposed SetNextWindowScroll() in public API. Useful to remove a scrolling + delay in some situations where e.g. windows need to be synched. (#1526) +- InputText: added experimental io.ConfigInputTextEnterKeepActive feature to make pressing + Enter keep the input active and select all text. +- InputText: numerical fields automatically accept full-width characters (U+FF01..U+FF5E) + by converting them to half-width (U+0021..U+007E). +- InputText: added ImGuiInputTextFlags_EscapeClearsAll flag: first press on Escape clears + text if any, second press deactivate the InputText(). (#5688, #2620) +- InputText: added support for shift+click style selection. (#5619) [@procedural] +- InputText: clarified that callbacks cannot modify buffer when using the ReadOnly flag. +- InputText: fixed minor one-frame selection glitch when reverting with Escape. +- ColorEdit3: fixed id collision leading to an assertion. (#5707) +- IsItemHovered: Added ImGuiHoveredFlags_DelayNormal and ImGuiHoveredFlags_DelayShort flags, + allowing to introduce a shared delay for tooltip idioms. The delays are respectively + io.HoverDelayNormal (default to 0.30f) and io.HoverDelayShort (default to 0.10f). (#1485) +- IsItemHovered: Added ImGuiHoveredFlags_NoSharedDelay to disable sharing delays between items, + so moving from one item to a nearby one will requires delay to elapse again. (#1485) +- Tables: activating an ID (e.g. clicking button inside) column doesn't prevent columns + output flags from having ImGuiTableColumnFlags_IsHovered set. (#2957) +- Tables,Columns: fixed a layout issue where SameLine() prior to a row change would set the + next row in such state where subsequent SameLine() would move back to previous row. +- Tabs: Fixed a crash when closing multiple windows (possible with docking only) with an + appended TabItemButton(). (#5515, #3291) [@rokups] +- Tabs: Fixed shrinking policy leading to infinite loops when fed unrounded tab widths. (#5652) +- Tabs: Fixed shrinking policy sometimes erroneously making right-most tabs stray a little out + bar boundaries (bug in 1.88). (#5652). +- Tabs: Enforcing minimum size of 1.0f, fixed asserting on zero-tab widths. (#5572) +- Window: Fixed a potential crash when appending to a child window. (#5515, #3496, #4797) [@rokups] +- Window: Fixed an issue where uncollapsed a window would show a scrollbar for a frame. +- Window: Auto-fit size takes account of work rectangle (menu bars eating from viewport). (#5843) +- Window: Fixed position not being clamped while auto-resizing (fixes appearing windows without + .ini data from moving for a frame when using io.ConfigWindowsMoveFromTitleBarOnly). (#5843) +- IO: Added ImGuiMod_Shortcut which is ImGuiMod_Super on Mac and ImGuiMod_Ctrl otherwise. (#456) +- IO: Added ImGuiKey_MouseXXX aliases for mouse buttons/wheel so all operations done on ImGuiKey + can apply to mouse data as well. (#4921) +- IO: Filter duplicate input events during the AddXXX() calls. (#5599, #4921) +- IO: Fixed AddFocusEvent(false) to also clear MouseDown[] state. (#4921) +- Menus: Fixed incorrect sub-menu parent association when opening a menu by closing another. + Among other things, it would accidentally break part of the closing heuristic logic when moving + towards a sub-menu. (#2517, #5614). [@rokups] +- Menus: Fixed gaps in closing logic which would make child-menu erroneously close when crossing + the gap between a menu item inside a window and a child-menu in a secondary viewport. (#5614) +- Menus: Fixed using IsItemHovered()/IsItemClicked() on BeginMenu(). (#5775) +- Menus, Popups: Experimental fix for issue where clicking on an open BeginMenu() item called from + a window which is neither a popup neither a menu used to incorrectly close and reopen the menu + (the fix may have side-effect and is labelld as experimental as we may need to revert). (#5775) +- Menus, Nav: Fixed keyboard/gamepad navigation occasionally erroneously landing on menu-item + in parent window when the parent is not a popup. (#5730) +- Menus, Nav: Fixed not being able to close a menu with Left arrow when parent is not a popup. (#5730) +- Menus, Nav: Fixed using left/right navigation when appending to an existing menu (multiple + BeginMenu() call with same names). (#1207) +- Menus: Fixed a one-frame issue where SetNextWindowXXX data are not consumed by a BeginMenu() + returning false. +- Nav: Fixed moving/resizing window with gamepad or keyboard when running at very high framerate. +- Nav: Pressing Space/GamepadFaceDown on a repeating button uses the same repeating rate as a mouse hold. +- Nav: Fixed an issue opening a menu with Right key from a non-menu window. +- Text: Fixed wrapped-text not doing a fast-forward on lines above the clipping region, + which would result in an abnormal number of vertices created (was slower and more likely to + asserts with 16-bits ImDrawVtx). (#5720) +- Fonts: Added GetGlyphRangesGreek() helper for Greek & Coptic glyph range. (#5676, #5727) [@azonenberg] +- ImDrawList: Not using alloca() anymore, lift single polygon size limits. (#5704, #1811) + - Note: now using a temporary buffer stored in ImDrawListSharedData. + This change made it more visible than you cannot append to multiple ImDrawList from multiple + threads if they share the same ImDrawListSharedData. Previously it was a little more likely + for this to "accidentally" work, but was already incorrect. (#6167) +- Platform IME: [Windows] Removed call to ImmAssociateContextEx() leading to freeze on some setups. + (#2589, #5535, #5264, #4972) +- Misc: better error reporting for PopStyleColor()/PopStyleVar() + easier to recover. (#1651) +- Misc: io.Framerate moving average now converge in 60 frames instead of 120. (#5236, #4138) +- Debug Tools: Debug Log: Visually locate items when hovering a 0xXXXXXXXX value. (#5855) +- Debug Tools: Debug Log: Added 'IO' and 'Clipper' events logging. (#5855) +- Debug Tools: Metrics: Visually locate items when hovering a 0xXXXXXXXX value (in most places). +- Debug Tools: Item Picker: Mouse button can be changed by holding Ctrl+Shift, making it easier + to use the Item Picker in e.g. menus. (#2673) +- Docs: Fixed various typos in comments and documentations. (#5649, #5675, #5679) [@tocic, @lessigsx] +- Demo: Improved "Constrained-resizing window" example, more clearly showcase aspect-ratio. (#5627) +- Demo: Added more explicit "Center window" mode to "Overlay example". (#5618) +- Demo: Fixed Log & Console from losing scrolling position with Auto-Scroll when child is clipped. (#5721) +- Examples: Added all SDL examples to default VS solution. +- Examples: Win32: Always use RegisterClassW() to ensure windows are Unicode. (#5725) +- Examples: Android: Enable .ini file loading/saving into application internal data folder. (#5836) [@rewtio] +- Backends: GLFW: Honor GLFW_CURSOR_DISABLED by not setting mouse position. (#5625) [@scorpion-26] +- Backends: GLFW: Add glfwGetError() call on GLFW 3.3 to inhibit missing mouse cursor errors. (#5785) [@mitchellh] +- Backends: SDL: Disable SDL 2.0.22 new "auto capture" which prevents drag and drop across windows + (e.g. for multi-viewport support) and don't capture mouse when drag and dropping. (#5710) +- Backends: Win32: Convert WM_CHAR values with MultiByteToWideChar() when window class was + registered as MBCS (not Unicode). (#5725, #1807, #471, #2815, #1060) [@or75, @ocornut] +- Backends: OSX: Fixed mouse inputs on flipped views. (#5756) [@Nemirtingas] +- Backends: OSX: Fixed mouse coordinate before clicking on the host window. (#5842) [@maezawa-akira] +- Backends: OSX: Fixes to support full app creation in C++. (#5403) [@stack] +- Backends: OpenGL3: Reverted use of glBufferSubData(), too many corruptions issues were reported, + and old leaks issues seemingly can't be reproed with Intel drivers nowadays (revert earlier changes). + (#4468, #4504, #3381, #2981, #4825, #4832, #5127). +- Backends: Metal: Use __bridge for ARC based systems. (#5403) [@stack] +- Backends: Metal: Add dispatch synchronization. (#5447) [@luigifcruz] +- Backends: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. (#5603) [@dcvz] +- Backends: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symetry. (#914, #5738). +- Backends: WebGPU: fixed rendering when a depth buffer is enabled. (#5869) [@brainlag] + + +----------------------------------------------------------------------- + VERSION 1.88 (Released 2022-06-21) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.88 + +Breaking changes: + +- Renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. + Kept support for old define (will obsolete). +- Renamed CaptureMouseFromApp() and CaptureKeyboardFromApp() to SetNextFrameWantCaptureMouse() + and SetNextFrameWantCaptureKeyboard() to clarify purpose, old name was too misleading. + Kept inline redirection functions (will obsolete). +- Renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). + (This was never used in public API functions but technically present in imgui.h and ImGuiIO). +- Backends: OSX: Removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend + automatically handling event capture. Examples that are using the OSX backend have removed + all the now-unnecessary calls to ImGui_ImplOSX_HandleEvent(), applications can do as well. + [@stuartcarnie] (#4821) +- Internals: calling ButtonBehavior() without calling ItemAdd() now requires a KeepAliveID() + call. This is because the KeepAliveID() call was moved from GetID() to ItemAdd(). (#5181) + +Other Changes: + +- IO: Fixed backward-compatibility regression introduced in 1.87: (#4921, #4858) + - Direct accesses to io.KeysDown[] with legacy indices didn't work (with new backends). + - Direct accesses to io.KeysDown[GetKeyIndex(XXX)] would access invalid data (with old/new backends). + - Calling IsKeyDown() didn't have those problems, and is recommended as io.KeysDown[] is obsolete. +- IO: Fixed input queue trickling of interleaved keys/chars events (which are frequent especially + when holding down a key as OS submits chars repeat events) delaying key presses and mouse movements. + In particular, using the input system for fast game-like actions (e.g. WASD camera move) would + typically have been impacted, as well as holding a key while dragging mouse. Constraints have + been lifted and are now only happening when e.g. an InputText() widget is active. (#4921, #4858) + Note that even thought you shouldn't need to disable io.ConfigInputTrickleEventQueue, you can + technically dynamically change its setting based on the context (e.g. disable only when hovering + or interacting with a game/3D view). +- IO: Fixed input queue trickling of mouse wheel events: multiple wheel events are merged, while + a mouse pos followed by a mouse wheel are now trickled. (#4921, #4821) +- IO: Added io.SetAppAcceptingEvents() to set a master flag for accepting key/mouse/characters + events (default to true). Useful if you have native dialog boxes that are interrupting your + application loop/refresh, and you want to disable events being queued while your app is frozen. +- Windows: Fixed first-time windows appearing in negative coordinates from being initialized + with a wrong size. This would most often be noticeable in multi-viewport mode (docking branch) + when spawning a window in a monitor with negative coordinates. (#5215, #3414) [@DimaKoltun] +- Clipper: Fixed a regression in 1.86 when not calling clipper.End() and late destructing the + clipper instance. High-level languages (Lua,Rust etc.) would typically be affected. (#4822) +- Layout: Fixed mixing up SameLine() and SetCursorPos() together from creating situations where line + height would be emitted from the wrong location (e.g. 'ItemA+SameLine()+SetCursorPos()+ItemB' would + emit ItemA worth of height from the position of ItemB, which is not necessarily aligned with ItemA). +- Sliders: An initial click within the knob/grab doesn't shift its position. (#1946, #5328) +- Sliders, Drags: Fixed dragging when using hexadecimal display format string. (#5165, #3133) +- Sliders, Drags: Fixed manual input when using hexadecimal display format string. (#5165, #3133) +- InputScalar: Fixed manual input when using %03d style width in display format string. (#5165, #3133) +- InputScalar: Automatically allow hexadecimal input when format is %X (without extra flag). +- InputScalar: Automatically allow scientific input when format is float/double (without extra flag). +- Nav: Fixed nav movement in a scope with only one disabled item from focusing the disabled item. (#5189) +- Nav: Fixed issues with nav request being transferred to another window when calling SetKeyboardFocusHere() + and simultaneous changing window focus. (#4449) +- Nav: Changed SetKeyboardFocusHere() to not behave if a drag or window moving is in progress. +- Nav: Fixed inability to cancel nav in modal popups. (#5400) [@rokups] +- IsItemHovered(): added ImGuiHoveredFlags_NoNavOverride to disable the behavior where the + return value is overridden by focus when gamepad/keyboard navigation is active. +- InputText: Fixed pressing Tab emitting two tabs characters because of dual Keys/Chars events being + trickled with the new input queue (happened on some backends only). (#2467, #1336) +- InputText: Fixed a one-frame display glitch where pressing Escape to revert after a deletion + would lead to small garbage being displayed for one frame. Curiously a rather old bug! (#3008) +- InputText: Fixed an undo-state corruption issue when editing main buffer before reactivating item. (#4947) +- InputText: Fixed an undo-state corruption issue when editing in-flight buffer in user callback. + (#4947, #4949] [@JoshuaWebb] +- Tables: Fixed incorrect border height used for logic when resizing one of several synchronized + instance of a same table ID, when instances have a different height. (#3955). +- Tables: Fixed incorrect auto-fit of parent windows when using non-resizable weighted columns. (#5276) +- Tables: Fixed draw-call merging of last column. Depending on some unrelated settings (e.g. BorderH) + merging draw-call of the last column didn't always work (regression since 1.87). (#4843, #4844) [@rokups] +- Inputs: Fixed IsMouseClicked() repeat mode rate being half of keyboard repeat rate. +- ColorEdit: Fixed text baseline alignment after a SameLine() after a ColorEdit() with visible label. +- Tabs: BeginTabItem() now reacts to SetNextItemWidth(). (#5262) +- Tabs: Tweak shrinking policy so that while resizing tabs that don't need shrinking keep their + initial width more precisely (without the occasional +1 worth of width). +- Menus: Adjusted BeginMenu() closing logic so hovering void or non-MenuItem() in parent window + always lead to menu closure. Fixes using items that are not MenuItem() or BeginItem() at the root + level of a popup with a child menu opened. +- Menus: Menus emitted from the main/scrolling layer are not part of the same menu-set as menus emitted + from the menu-bar, avoiding accidental hovering from one to the other. (#3496, #4797) [@rokups] +- Style: Adjust default value of GrabMinSize from 10.0f to 12.0f. +- Stack Tool: Added option to copy item path to clipboard. (#4631) +- Settings: Fixed out-of-bounds read when .ini file on disk is empty. (#5351) [@quantum5] +- Settings: Fixed some SetNextWindowPos/SetNextWindowSize API calls not marking settings as dirty. +- DrawList: Fixed PathArcTo() emitting terminating vertices too close to arc vertices. (#4993) [@thedmd] +- DrawList: Fixed texture-based anti-aliasing path with RGBA textures (#5132, #3245) [@cfillion] +- DrawList: Fixed divide-by-zero or glitches with Radius/Rounding values close to zero. (#5249, #5293, #3491) +- DrawList: Circle with a radius smaller than 0.5f won't appear, to be consistent with other primitives. [@thedmd] +- Debug Tools: Debug Log: Added ShowDebugLogWindow() showing an opt-in synthetic log of principal events + (focus, popup, active id changes) helping to diagnose issues. +- Debug Tools: Added DebugTextEncoding() function to facilitate diagnosing issues when not sure about + whether you have a UTF-8 text encoding issue or a font loading issue. [@LaMarche05, @ocornut] +- Demo: Add better demo of how to use SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). +- Metrics: Added a "UTF-8 Encoding Viewer" section using the aforementioned DebugTextEncoding() function. +- Metrics: Added "InputText" section to visualize internal state (#4947, #4949). +- Misc: Fixed calling GetID("label") _before_ a widget emitting this item inside a group (such as InputInt()) + from causing an assertion when closing the group. (#5181). +- Misc: Fixed IsAnyItemHovered() returning false when using navigation. +- Misc: Allow redefining IM_COL32_XXX layout macros to facilitate use on big-endian systems. (#5190, #767, #844) +- Misc: Added IMGUI_STB_SPRINTF_FILENAME to support custom path to stb_sprintf. (#5068, #2954) [@jakubtomsu] +- Misc: Added constexpr to ImVec2/ImVec4 inline constructors. (#4995) [@Myriachan] +- Misc: Updated stb_truetype.h from 1.20 to 1.26 (many fixes). (#5075) +- Misc: Updated stb_textedit.h from 1.13 to 1.14 (our changes so this effectively is a no-op). (#5075) +- Misc: Updated stb_rect_pack.h from 1.00 to 1.01 (minor). (#5075) +- Misc: binary_to_compressed_c tool: Added -nostatic option. (#5021) [@podsvirov] +- ImVector: Fixed erase() with empty range. (#5009) [@thedmd] +- Backends: Vulkan: Don't use VK_PRESENT_MODE_MAX_ENUM_KHR as specs state it isn't part of the API. (#5254) +- Backends: GLFW: Fixed a regression in 1.87 which resulted in keyboard modifiers events being + reported incorrectly on Linux/X11, due to a bug in GLFW. [@rokups] +- Backends: GLFW: Fixed untranslated keys when pressing lower case letters on OSX (#5260, #5261) [@cpichard] +- Backends: SDL: Fixed dragging out viewport broken on some SDL setups. (#5012) [@rokups] +- Backends: SDL: Added support for extra mouse buttons (SDL_BUTTON_X1/SDL_BUTTON_X2). (#5125) [@sgiurgiu] +- Backends: SDL, OpenGL3: Fixes to facilitate building on AmigaOS4. (#5190) [@afxgroup] +- Backends: OSX: Monitor NSKeyUp events to catch missing keyUp for key when user press Cmd + key (#5128) [@thedmd] +- Backends: OSX, Metal: Store backend data in a per-context struct, allowing to use these backends with + multiple contexts. (#5203, #5221, #4141) [@noisewuwei] +- Backends: Metal: Fixed null dereference on exit inside command buffer completion handler. (#5363, #5365) [@warrenm] +- Backends: OpenGL3: Partially revert 1.86 change of using glBufferSubData(): now only done on Windows and + Intel GPU, based on querying glGetString(GL_VENDOR). Essentially we got report of accumulating leaks on Intel + with multi-viewports when using simple glBufferData() without orphaning, and report of corruptions on other + GPUs with multi-viewports when using orphaning and glBufferSubData(), so currently switching technique based + on GPU vendor, which unfortunately reinforce the cargo-cult nature of dealing with OpenGL drivers. + Navigating the space of mysterious OpenGL drivers is particularly difficult as they are known to rely on + application specific whitelisting. (#4468, #3381, #2981, #4825, #4832, #5127). +- Backends: OpenGL3: Fix state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING + and vertex attribute states. [@rokups] +- Examples: Emscripten+WebGPU: Fix building for latest WebGPU specs. (#3632) +- Examples: OSX+Metal, OSX+OpenGL: Removed now-unnecessary calls to ImGui_ImplOSX_HandleEvent(). (#4821) + + +----------------------------------------------------------------------- + VERSION 1.87 (Released 2022-02-07) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.87 + +Breaking Changes: + +- Removed support for pre-C++11 compilers. We'll stop supporting VS2010. (#4537) +- Reworked IO mouse input API: (#4921, #4858) [@thedmd, @ocornut] + - Added io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() functions, + obsoleting writing directly to io.MousePos, io.MouseDown[], io.MouseWheel, etc. + - This enable input queue trickling to support low framerates. (#2787, #1992, #3383, #2525, #1320) + - For all calls to IO new functions, the Dear ImGui context should be bound/current. +- Reworked IO keyboard input API: (#4921, #2625, #3724) [@thedmd, @ocornut] + - Added io.AddKeyEvent() function, obsoleting writing directly to io.KeyMap[], io.KeysDown[] arrays. + - For keyboard modifiers, you can call io.AddKeyEvent() with ImGuiKey_ModXXX values, + obsoleting writing directly to io.KeyCtrl, io.KeyShift etc. + - Added io.SetKeyEventNativeData() function (optional) to pass native and old legacy indices. + - Added full range of key enums in ImGuiKey (e.g. ImGuiKey_F1). + - Added GetKeyName() helper function. + - Obsoleted GetKeyIndex(): it is now unnecessary and will now return the same value. + - All keyboard related functions taking 'int user_key_index' now take 'ImGuiKey key': + - IsKeyDown(), IsKeyPressed(), IsKeyReleased(), GetKeyPressedAmount(). + - Added io.ConfigInputTrickleEventQueue (defaulting to true) to disable input queue trickling. + - Backward compatibility: + - All backends updated to use new functions. + - Old backends populating those arrays should still work! + - Calling e.g. IsKeyPressed(MY_NATIVE_KEY_XXX) will still work! (for a while) + - Those legacy arrays will only be disabled if '#define IMGUI_DISABLE_OBSOLETE_KEYIO' is set in your imconfig. + In a few versions, IMGUI_DISABLE_OBSOLETE_FUNCTIONS will automatically enable IMGUI_DISABLE_OBSOLETE_KEYIO, + so this will be moved into the regular obsolescence path. + - BREAKING: If your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") + this is a use case that will now assert and be breaking for your old backend. + - Transition guide: + - IsKeyPressed(MY_NATIVE_KEY_XXX) -> use IsKeyPressed(ImGuiKey_XXX) + - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX) + - Backend writing to io.KeyMap[],KeysDown[] -> backend should call io.AddKeyEvent(), if legacy indexing is desired, call io.SetKeyEventNativeData() + - Basically the trick we took advantage of is that we previously only supported native keycode from 0 to 511, + so ImGuiKey values can still express a legacy native keycode, and new named keys are all >= 512. + - This will enable a few things in the future: + - Access to portable keys allows for backend-agnostic keyboard input code. Until now it was difficult + to share code using keyboard across project because of this gap. (#2625, #3724) + - Access to full key ranges will allow us to develop a proper keyboard shortcut system. (#456) + - io.SetKeyEventNativeData() include native keycode/scancode which may later be exposed. (#3141, #2959) +- Reworked IO nav/gamepad input API and unifying inputs sources: (#4921, #4858, #787) + - Added full range of ImGuiKey_GamepadXXXX enums (e.g. ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadR2) to use with + io.AddKeyEvent(), io.AddKeyAnalogEvent(). + - Added io.AddKeyAnalogEvent() function, obsoleting writing directly to io.NavInputs[] arrays. +- Renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum. (#2625) +- Removed support for legacy arithmetic operators (+,+-,*,/) when inputing text into a slider/drag. (#4917, #3184) + This doesn't break any api/code but a feature that was accessible by end-users (which seemingly no one used). + (Instead you may implement custom expression evaluators to provide a better version of this). +- Backends: GLFW: backend now uses glfwSetCursorPosCallback(). + - If calling ImGui_ImplGlfw_InitXXX with install_callbacks=true: nothing to do. is already done for you. + - If calling ImGui_ImplGlfw_InitXXX with install_callbacks=false: you WILL NEED to register the GLFW callback + using glfwSetCursorPosCallback() and forward it to the backend function ImGui_ImplGlfw_CursorPosCallback(). +- Backends: SDL: Added SDL_Renderer* parameter to ImGui_ImplSDL2_InitForSDLRenderer(), so backend can call + SDL_GetRendererOutputSize() to obtain framebuffer size valid for hi-dpi. (#4927) [@Clownacy] +- Commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019) + - ImGui::SetNextTreeNodeOpen() -> use ImGui::SetNextItemOpen() + - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x + - ImGui::TreeAdvanceToLabelPos() -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing()); + - ImFontAtlas::CustomRect -> use ImFontAtlasCustomRect + - ImGuiColorEditFlags_RGB/HSV/HEX -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex +- Removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn() for IME support. + Because this field was mostly only ever used by Dear ImGui internally, not by backends nor the vast majority + of user code, this should only affect a very small fraction for users who are already very IME-aware. +- Obsoleted 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'. + This removes an incompatibility between 'master' and 'multi-viewports' backends and toward enabling + better support for IME. Updated backends accordingly. Because the old field is set by existing backends, + we are keeping it (marked as obsolete). + +Other Changes: + +- IO: Added event based input queue API, which now trickles events to support low framerates. [@thedmd, @ocornut] + Previously the most common issue case (button presses in low framerates) was handled by backend. This is now + handled by core automatically for all kind of inputs. (#4858, #2787, #1992, #3383, #2525, #1320) + - New IO functions for keyboard/gamepad: AddKeyEvent(), AddKeyAnalogEvent(). + - New IO functions for mouse: AddMousePosEvent(), AddMouseButtonEvent(), AddMouseWheelEvent(). +- IO: Unified key enums allow using key functions on key mods and gamepad values. +- Fixed CTRL+Tab into an empty window causing artifacts on the highlight rectangle due to bad reordering on ImDrawCmd. +- Fixed a situation where CTRL+Tab or Modal can occasionally lead to the creation of ImDrawCmd with zero triangles, + which would makes the draw operation of some backends assert (e.g. Metal with debugging). (#4857) +- Popups: Fixed a regression crash when a new window is created after a modal on the same frame. (#4920) [@rokups] +- Popups: Fixed an issue when reopening a same popup multiple times would offset them by 1 pixel on the right. (#4936) +- Tables, ImDrawListSplitter: Fixed erroneously stripping trailing ImDrawList::AddCallback() when submitted in + last column or last channel and when there are no other drawing operation. (#4843, #4844) [@hoffstadt] +- Tables: Fixed positioning of Sort icon on right-most column with some settings (not resizable + no borders). (#4918). +- Nav: Fixed gamepad navigation in wrapping popups not wrapping all the way. (#4365) +- Sliders, Drags: Fixed text input of values with a leading sign, common when using a format enforcing sign. (#4917) +- Demo: draw a section of keyboard in "Inputs > Keyboard, Gamepad & Navigation state" to visualize keys. [@thedmd] +- Platform IME: changed io.ImeSetInputScreenPosFn() to io.SetPlatformImeDataFn() API, + now taking a ImGuiPlatformImeData structure which we can more easily extend in the future. +- Platform IME: moved io.ImeWindowHandle to GetMainViewport()->PlatformHandleRaw. +- Platform IME: add ImGuiPlatformImeData::WantVisible, hide IME composition window when not used. (#2589) [@actboy168] +- Platform IME: add ImGuiPlatformImeData::InputLineHeight. (#3113) [@liuliu] +- Platform IME: [windows] call ImmSetCandidateWindow() to position candidate window. +- Backends: GLFW: Pass localized keys (matching keyboard layout). Fix e.g. CTRL+A, CTRL+Z, CTRL+Y shortcuts. + We are now converting GLFW untranslated keycodes back to translated keycodes in order to match the behavior of + other backend, and facilitate the use of GLFW with lettered-shortcuts API. (#456, #2625) +- Backends: GLFW: Submit keys and key mods using io.AddKeyEvent(). (#2625, #4921) +- Backends: GLFW: Submit mouse data using io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() functions. (#4921) +- Backends: GLFW: Retrieve mouse position using glfwSetCursorPosCallback() + fallback when focused but not hovered/captured. +- Backends: GLFW: Submit gamepad data using io.AddKeyEvent/AddKeyAnalogEvent() functions, stopped writing to io.NavInputs[]. (#4921) +- Backends: GLFW: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing + callbacks after iniitializing backend. (#4981) +- Backends: Win32: Submit keys and key mods using io.AddKeyEvent(). (#2625, #4921) +- Backends: Win32: Retrieve mouse position using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback when focused but not hovered/captured. +- Backends: Win32: Submit mouse data using io.AddMousePosEvent(), AddMouseButtonEvent(), AddMouseWheelEvent() functions. (#4921) +- Backends: Win32: Maintain a MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. +- Backends: Win32: Submit gamepad data using io.AddKeyEvent/AddKeyAnalogEvent() functions, stopped writing to io.NavInputs[]. (#4921) +- Backends: SDL: Pass localized keys (matching keyboard layout). Fix e.g. CTRL+A, CTRL+Z, CTRL+Y shortcuts. (#456, #2625) +- Backends: SDL: Submit key data using io.AddKeyEvent(). Submit keymods using io.AddKeyModsEvent() at the same time. (#2625) +- Backends: SDL: Retrieve mouse position using SDL_MOUSEMOTION/SDL_WINDOWEVENT_LEAVE + fallback when focused but not hovered/captured. +- Backends: SDL: Submit mouse data using io.AddMousePosEvent(), AddMouseButtonEvent(), AddMouseWheelEvent() functions. (#4921) +- Backends: SDL: Maintain a MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. +- Backends: SDL: Submit gamepad data using io.AddKeyEvent/AddKeyAnalogEvent() functions, stopped writing to io.NavInputs[]. (#4921) +- Backends: Allegro5: Submit keys using io.AddKeyEvent(). Submit keymods using io.AddKeyModsEvent() at the same time. (#2625) +- Backends: Allegro5: Submit mouse data using io.AddMousePosEvent(), AddMouseButtonEvent(), AddMouseWheelEvent() functions. (#4921) +- Backends: OSX: Submit keys using io.AddKeyEvent(). Submit keymods using io.AddKeyModsEvent() at the same time. (#2625) +- Backends: OSX: Submit mouse data using io.AddMousePosEvent(), AddMouseButtonEvent(), AddMouseWheelEvent() functions. (#4921) +- Backends: OSX: Submit gamepad data using io.AddKeyEvent/AddKeyAnalogEvent() functions, stopped writing to io.NavInputs[]. (#4921) +- Backends: OSX: Added basic Platform IME support. (#3108, #2598) [@liuliu] +- Backends: OSX: Fix Game Controller nav mapping to use shoulder for both focusing and tweak speed. (#4759) +- Backends: OSX: Fix building with old Xcode versions that are missing gamepad features. [@rokups] +- Backends: OSX: Forward keyDown/keyUp events to OS when unused by Dear ImGui. +- Backends: Android, GLUT: Submit keys using io.AddKeyEvent(). Submit keymods using io.AddKeyModsEvent() at the same time. (#2625) +- Backends: Android, GLUT: Submit mouse data using io.AddMousePosEvent(), AddMouseButtonEvent(), AddMouseWheelEvent() functions. (#4858) +- Backends: OpenGL3: Fixed a buffer overflow in imgui_impl_opengl3_loader.h init (added in 1.86). (#4468, #4830) [@dymk] + It would generally not have noticeable side-effect at runtime but would be detected by runtime checkers. +- Backends: OpenGL3: Fix OpenGL ES2 includes on Apple systems. [@rokups] +- Backends: Metal: Added Apple Metal C++ API support. (#4824, #4746) [@luigifcruz] + Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file. +- Backends: Metal: Ignore ImDrawCmd where ElemCount == 0, which are normally not emitted by the library but + can theoretically be created by user code manipulating a ImDrawList. (#4857) +- Backends: Vulkan: Added support for ImTextureID as VkDescriptorSet, add ImGui_ImplVulkan_AddTexture(). (#914) [@martty] +- Backends: SDL_Renderer: Fix texture atlas format on big-endian hardware (#4927) [@Clownacy] +- Backends: WebGPU: Fixed incorrect size parameters in wgpuRenderPassEncoderSetIndexBuffer() and + wgpuRenderPassEncoderSetVertexBuffer() calls. (#4891) [@FeepsDev] + + ----------------------------------------------------------------------- VERSION 1.86 (Released 2021-12-22) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.86 + Breaking Changes: - Removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. @@ -47,7 +1568,7 @@ Other Changes: - Added an assertion for the common user mistake of using "" as an identifier at the root level of a window instead of using "##something". Empty identifiers are valid and useful in a very small amount of cases, but 99.9% of the time if you need an empty label you should use "##something". (#1414, #2562, #2807, #4008, - #4158, #4375, #4548, #4657, #4796). READ THE FAQ ABOUT HOW THE ID STACK WORKS -> https://dearimgui.org/faq + #4158, #4375, #4548, #4657, #4796). READ THE FAQ ABOUT HOW THE ID STACK WORKS -> https://dearimgui.com/faq - Added GetMouseClickedCount() function, returning the number of successive clicks. (#3229) [@kudaba] (so IsMouseDoubleClicked(ImGuiMouseButton_Left) is same as GetMouseClickedCount(ImGuiMouseButton_Left) == 2, but it allows testing for triple clicks and more). @@ -86,7 +1607,7 @@ Other Changes: Fixes issue where e.g. drag and dropping an item and scrolling ensure the item source location is still submitted. (#3841, #1725) [@GamingMinds-DanielC, @ocornut] - Clipper: added ForceDisplayRangeByIndices() to force a given item (or several) to be stepped out - during a clipping operation. (#3841) [@@GamingMinds-DanielC] + during a clipping operation. (#3841) [@GamingMinds-DanielC] - Clipper: rework so gamepad/keyboard navigation doesn't create spikes in number of items requested by the clipper to display. (#3841) - Clipper: fixed content height declaration slightly mismatching the value of when not using a clipper. @@ -130,6 +1651,8 @@ Other Changes: VERSION 1.85 (Released 2021-10-12) ----------------------------------------------------------------------- +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.85 + This is the last release officially supporting C++03 and Visual Studio 2008/2010. (#4537) We expect that the next release will require a subset of the C++11 language (VS 2012~, GCC 4.8.1, Clang 3.3). We may use some C++11 language features but we will not use any C++ library headers. @@ -137,7 +1660,7 @@ If you are stuck on ancient compiler you may need to stay at this version onward Breaking Changes: -- Removed GetWindowContentRegionWidth() function. keep inline redirection helper. +- Removed GetWindowContentRegionWidth() function. Kept inline redirection helper. Can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead but it's not very useful in practice, and the only use of it in the demo was illfit. Using 'GetContentRegionAvail().x' is generally a better choice. @@ -219,7 +1742,7 @@ Other Changes: VERSION 1.84.2 (Released 2021-08-23) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.84.2 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.84.2 - Disabled: Fixed nested BeginDisabled()/EndDisabled() calls. (#211, #4452, #4453, #4462) [@Legulysse] - Backends: OpenGL3: OpenGL: Fixed ES 3.0 shader ("#version 300 es") to use normal precision @@ -230,7 +1753,7 @@ Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.84.2 VERSION 1.84.1 (Released 2021-08-20) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.84.1 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.84.1 - Disabled: Fixed BeginDisabled(false) - BeginDisabled(true) was working. (#211, #4452, #4453) @@ -239,14 +1762,14 @@ Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.84.1 VERSION 1.84 (Released 2021-08-20) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.84 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.84 Breaking Changes: - Commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019): - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList() - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder -- Backends: OpenGL3: added a third source file "imgui_impl_opengl3_loader.h". [@rokups] +- Backends: OpenGL3: added a third source file "imgui_impl_opengl3_loader.h". (#4445) [@rokups] - Backends: GLFW: backend now uses glfwSetCursorEnterCallback(). (#3751, #4377, #2445) - Backends: GLFW: backend now uses glfwSetWindowFocusCallback(). (#4388) [@thedmd] - If calling ImGui_ImplGlfw_InitXXX with install_callbacks=true: this is already done for you. @@ -289,7 +1812,7 @@ Other Changes: Convenient for some small columns. Name will still appear in context menu. (#4206). - Tables: Fixed columns order on TableSetupScrollFreeze() if previous data got frozen columns out of their section. - Tables: Fixed invalid data in TableGetSortSpecs() when SpecsDirty flag is unset. (#4233) -- TabBar: Fixed using more than 32 KB-worth of tab names. (#4176) +- Tabs: Fixed using more than 32 KB-worth of tab names. (#4176) - InputInt/InputFloat: When used with Steps values and _ReadOnly flag, the step button look disabled. (#211) - InputText: Fixed named filtering flags disabling newline or tabs in multiline inputs (#4409, #4410) [@kfsone] - Drag and Drop: drop target highlight doesn't try to bypass host clipping rectangle. (#4281, #3272) @@ -335,7 +1858,7 @@ Other Changes: about building on 32-bit systems. (#4225) [@kingofthebongo2008] - Backends: OpenGL3: Embed our own minimal GL headers/loader (imgui_impl_opengl3_loader.h) based on gl3w. Reduces the frequent issues and confusion coming from having to support multiple loaders and requiring users to use and - initialize the same loader as the backend. [@rokups] + initialize the same loader as the backend. (#4445) [@rokups] Removed support for gl3w, glew, glad, glad2, glbinding2, glbinding3 (all now unnecessary). - Backends: OpenGL3: Handle GL_CLIP_ORIGIN on <4.5 contexts if "GL_ARB_clip_control" extension is detected. (#4170, #3998) - Backends: OpenGL3: Destroy vertex/fragment shader objects right after they are linked into main shader. (#4244) [@Crowbarous] @@ -355,7 +1878,7 @@ Other Changes: VERSION 1.83 (Released 2021-05-24) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.83 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.83 Breaking Changes: @@ -382,7 +1905,7 @@ Other Changes: - Tables: Expose TableSetColumnEnabled() in public api. (#3935) - Tables: Better preserve widths when columns count changes. (#4046) - Tables: Sharing more memory buffers between tables, reducing general memory footprints. (#3740) -- TabBar: Fixed mouse reordering with very fast movements (e.g. crossing multiple tabs in a single +- Tabs: Fixed mouse reordering with very fast movements (e.g. crossing multiple tabs in a single frame and then immediately standing still (would only affect automation/bots). [@rokups] - Menus: made MenuItem() in a menu bar reflect the 'selected' argument with a highlight. (#4128) [@mattelegende] - Drags, Sliders, Inputs: Specifying a NULL format to Float functions default them to "%.3f" to be @@ -439,7 +1962,7 @@ Other Changes: VERSION 1.82 (Released 2021-02-15) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.82 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.82 Breaking Changes: @@ -534,7 +2057,7 @@ Other Changes: VERSION 1.81 (Released 2021-02-10) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.81 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.81 Breaking Changes: @@ -615,7 +2138,7 @@ Other Changes: VERSION 1.80 (Released 2021-01-21) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.80 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.80 Breaking Changes: @@ -665,11 +2188,11 @@ Other Changes: - Added 2 enums: ImGuiSortDirection, ImGuiTableBgTarget - Added 1 style variable: ImGuiStyleVar_CellPadding - Added 5 style colors: ImGuiCol_TableHeaderBg, ImGuiCol_TableBorderStrong, ImGuiCol_TableBorderLight, ImGuiCol_TableRowBg, ImGuiCol_TableRowBgAlt. -- Tab Bar: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. -- Tab Bar: Fixed using more than 128 tabs in a tab bar (scrolling policy recommended). -- Tab Bar: Do not display a tooltip if the name already fits over a given tab. (#3521) -- Tab Bar: Fixed minor/unlikely bug skipping over a button when scrolling left with arrows. -- Tab Bar: Requested ideal content size (for auto-fit) doesn't affect horizontal scrolling. (#3414) +- Tabs: Made it possible to append to an existing tab bar by calling BeginTabBar()/EndTabBar() again. +- Tabs: Fixed using more than 128 tabs in a tab bar (scrolling policy recommended). +- Tabs: Do not display a tooltip if the name already fits over a given tab. (#3521) +- Tabs: Fixed minor/unlikely bug skipping over a button when scrolling left with arrows. +- Tabs: Requested ideal content size (for auto-fit) doesn't affect horizontal scrolling. (#3414) - Drag and Drop: Fix losing drop source ActiveID (and often source tooltip) when opening a TreeNode() or CollapsingHeader() while dragging. (#1738) - Drag and Drop: Fix drag and drop to tie same-size drop targets by chosen the later one. Fixes dragging @@ -734,7 +2257,7 @@ Other Changes: VERSION 1.79 (Released 2020-10-08) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.79 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.79 Breaking Changes: @@ -790,16 +2313,16 @@ Other Changes: rather than the Mouse Down+Up sequence, even if the _OpenOnArrow flag isn't set. This is standard behavior and amends the change done in 1.76 which only affected cases were _OpenOnArrow flag was set. (This is also necessary to support full multi/range-select/drag and drop operations.) -- Tab Bar: Added TabItemButton() to submit tab that behave like a button. (#3291) [@Xipiryon] -- Tab Bar: Added ImGuiTabItemFlags_Leading and ImGuiTabItemFlags_Trailing flags to position tabs or button +- Tabs: Added TabItemButton() to submit tab that behave like a button. (#3291) [@Xipiryon] +- Tabs: Added ImGuiTabItemFlags_Leading and ImGuiTabItemFlags_Trailing flags to position tabs or button at either end of the tab bar. Those tabs won't be part of the scrolling region, and when reordering cannot be moving outside of their section. Most often used with TabItemButton(). (#3291) [@Xipiryon] -- Tab Bar: Added ImGuiTabItemFlags_NoReorder flag to disable reordering a given tab. -- Tab Bar: Keep tab item close button visible while dragging a tab (independent of hovering state). -- Tab Bar: Fixed a small bug where closing a tab that is not selected would leave a tab hole for a frame. -- Tab Bar: Fixed a small bug where scrolling buttons (with ImGuiTabBarFlags_FittingPolicyScroll) would +- Tabs: Added ImGuiTabItemFlags_NoReorder flag to disable reordering a given tab. +- Tabs: Keep tab item close button visible while dragging a tab (independent of hovering state). +- Tabs: Fixed a small bug where closing a tab that is not selected would leave a tab hole for a frame. +- Tabs: Fixed a small bug where scrolling buttons (with ImGuiTabBarFlags_FittingPolicyScroll) would generate an unnecessary extra draw call. -- Tab Bar: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave +- Tabs: Fixed a small bug where toggling a tab bar from Reorderable to not Reorderable would leave tabs reordered in the tab list popup. [@Xipiryon] - Columns: Fix inverted ClipRect being passed to renderer when using certain primitives inside of a fully clipped column. (#3475) [@szreder] @@ -828,7 +2351,7 @@ Other Changes: VERSION 1.78 (Released 2020-08-18) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.78 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.78 Breaking Changes: @@ -893,7 +2416,7 @@ Other Changes: limits when close-enough by (WindowPadding - ItemPadding), which was a tweak with too many side-effects. The behavior is still present in SetScrollHere functions as they are more explicitly aiming at making widgets visible. May later be moved to a flag. -- Tab Bar: Allow calling SetTabItemClosed() after a tab has been submitted (will process next frame). +- Tabs: Allow calling SetTabItemClosed() after a tab has been submitted (will process next frame). - InvisibleButton: Made public a small selection of ImGuiButtonFlags (previously in imgui_internal.h) and allowed to pass them to InvisibleButton(): ImGuiButtonFlags_MouseButtonLeft/Right/Middle. This is a small but rather important change because lots of multi-button behaviors could previously @@ -929,7 +2452,7 @@ Other Changes: VERSION 1.77 (Released 2020-06-29) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.77 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.77 Breaking Changes: @@ -1020,7 +2543,7 @@ Other Changes: VERSION 1.76 (Released 2020-04-12) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.76 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.76 Other Changes: @@ -1092,7 +2615,7 @@ Other Changes: VERSION 1.75 (Released 2020-02-10) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.75 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.75 Breaking Changes: @@ -1190,7 +2713,7 @@ Other Changes: VERSION 1.74 (Released 2019-11-25) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.74 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.74 Breaking Changes: @@ -1248,7 +2771,7 @@ Other Changes: default implementation of ImFileXXX functions linking with fopen/fclose/fread/fwrite. (#2734) - Docs: Improved and moved FAQ to docs/FAQ.md so it can be readable on the web. [@ButternCream, @ocornut] - Docs: Moved misc/fonts/README.txt to docs/FONTS.txt. -- Docs: Added permanent redirect from https://www.dearimgui.org/faq to FAQ page. +- Docs: Added permanent redirect from https://www.dearimgui.com/faq to FAQ page. - Demo: Added simple item reordering demo in Widgets -> Drag and Drop section. (#2823, #143) [@rokups] - Metrics: Show wire-frame mesh and approximate surface area when hovering ImDrawCmd. [@ShironekoBen] - Metrics: Expose basic details of each window key/value state storage. @@ -1269,7 +2792,7 @@ Other Changes: VERSION 1.73 (Released 2019-09-24) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.73 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.73 Other Changes: @@ -1280,11 +2803,11 @@ Other Changes: - ColorPicker: Made rendering aware of global style alpha of the picker can be faded out. (#2711) Note that some elements won't accurately fade down with the same intensity, and the color wheel when enabled will have small overlap glitches with (style.Alpha < 1.0). -- TabBar: Fixed single-tab not shrinking their width down. -- TabBar: Fixed clicking on a tab larger than tab-bar width creating a bouncing feedback loop. -- TabBar: Feed desired width (sum of unclipped tabs width) into layout system to allow for auto-resize. (#2768) +- Tabs: Fixed single-tab not shrinking their width down. +- Tabs: Fixed clicking on a tab larger than tab-bar width creating a bouncing feedback loop. +- Tabs: Feed desired width (sum of unclipped tabs width) into layout system to allow for auto-resize. (#2768) (before 1.71 tab bars fed the sum of current width which created feedback loops in certain situations). -- TabBar: Improved shrinking for large number of tabs to avoid leaving extraneous space on the right side. +- Tabs: Improved shrinking for large number of tabs to avoid leaving extraneous space on the right side. Individuals tabs are given integer-rounded width and remainder is spread between tabs left-to-right. - Columns, Separator: Fixed a bug where non-visible separators within columns would alter the next row position differently than visible ones. @@ -1331,7 +2854,7 @@ Other Changes: VERSION 1.72b (Released 2019-07-31) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.72b +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.72b Other Changes: @@ -1348,7 +2871,7 @@ Other Changes: VERSION 1.72 (Released 2019-07-27) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.72 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.72 Breaking Changes: @@ -1384,7 +2907,7 @@ Other Changes: - Scrollbar: Avoid overlapping the opposite side when window (often a child window) is forcibly too small. - Combo: Hide arrow when there's not enough space even for the square button. - InputText: Testing for newly added ImGuiKey_KeyPadEnter key. (#2677, #2005) [@amc522] -- TabBar: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). +- Tabs: Fixed unfocused tab bar separator color (was using ImGuiCol_Tab, should use ImGuiCol_TabUnfocusedActive). - Columns: Fixed a regression from 1.71 where the right-side of the contents rectangle within each column would wrongly use a WindowPadding.x instead of ItemSpacing.x like it always did. (#125, #2666) - Columns: Made the right-most edge reaches up to the clipping rectangle (removing half of WindowPadding.x @@ -1406,8 +2929,8 @@ Other Changes: returning true. This also effectively make ColorEdit4() not incorrect trigger IsItemDeactivatedAfterEdit() when clicking the color button to open the picker popup. (#1875) - Misc: Added IMGUI_DISABLE_METRICS_WINDOW imconfig.h setting to explicitly compile out ShowMetricsWindow(). -- Debug, Metrics: Added "Tools->Item Picker" tool which allow clicking on a widget to break in the debugger - within the item code. The tool calls IM_DEBUG_BREAK() which can be redefined in imconfig.h if needed. +- Debug Tools: Added "Metrics->Tools->Item Picker" tool which allow clicking on a widget to break in the + debugger within the item code. The tool calls IM_DEBUG_BREAK() which can be redefined in imconfig.h. - ImDrawList: Fixed CloneOutput() helper crashing. (#1860) [@gviot] - ImDrawList::ChannelsSplit(), ImDrawListSplitter: Fixed an issue with merging draw commands between channel 0 and 1. (#2624) @@ -1433,7 +2956,7 @@ Other Changes: VERSION 1.71 (Released 2019-06-12) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.71 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.71 Breaking Changes: @@ -1479,7 +3002,7 @@ Other Changes: viewport triggering the issue. (#2609) - TreeNode, CollapsingHeader: Fixed highlight frame not covering horizontal area fully when using horizontal scrolling. (#2211, #2579) -- TabBar: Fixed BeginTabBar() within a window with horizontal scrolling from creating a feedback +- Tabs: Fixed BeginTabBar() within a window with horizontal scrolling from creating a feedback loop with the horizontal contents size. - Columns: Fixed Columns() within a window with horizontal scrolling from not covering the full horizontal area (previously only worked with an explicit contents size). (#125) @@ -1517,7 +3040,7 @@ Other Changes: VERSION 1.70 (Released 2019-05-06) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.70 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.70 Breaking Changes: @@ -1608,7 +3131,7 @@ Other Changes: VERSION 1.69 (Released 2019-03-13) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.69 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.69 Breaking Changes: @@ -1648,14 +3171,14 @@ Other Changes: - ColorEdit: Fixed tooltip not honoring the ImGuiColorEditFlags_NoAlpha contract of never reading the 4th float in the array (value was read and discarded). (#2384) [@haldean] - MenuItem, Selectable: Fixed disabled widget interfering with navigation (fix c2db7f63 in 1.67). -- TabBar: Fixed a crash when using many BeginTabBar() recursively (didn't affect docking). (#2371) -- TabBar: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to +- Tabs: Fixed a crash when using many BeginTabBar() recursively (didn't affect docking). (#2371) +- Tabs: Added extra mis-usage error recovery. Past the assert, common mis-usage don't lead to hard crashes any more, facilitating integration with scripting languages. (#1651) -- TabBar: Fixed ImGuiTabItemFlags_SetSelected being ignored if the tab is not visible (with +- Tabs: Fixed ImGuiTabItemFlags_SetSelected being ignored if the tab is not visible (with scrolling policy enabled) or if is currently appearing. -- TabBar: Fixed Tab tooltip code making drag and drop tooltip disappear during the frame where +- Tabs: Fixed Tab tooltip code making drag and drop tooltip disappear during the frame where the drag payload activate a tab. -- TabBar: Reworked scrolling policy (when ImGuiTabBarFlags_FittingPolicyScroll is set) to +- Tabs: Reworked scrolling policy (when ImGuiTabBarFlags_FittingPolicyScroll is set) to teleport the view when aiming at a tab far away the visible section, and otherwise accelerate the scrolling speed to cap the scrolling time to 0.3 seconds. - Text: Fixed large Text/TextUnformatted calls not feeding their size into layout when starting @@ -1686,7 +3209,7 @@ Other Changes: VERSION 1.68 (Released 2019-02-19) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.68 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.68 Breaking Changes: @@ -1756,7 +3279,7 @@ Other Changes: VERSION 1.67 (Released 2019-01-14) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.67 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.67 Breaking Changes: @@ -1821,7 +3344,7 @@ Other Changes: VERSION 1.66b (Released 2018-12-01) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.66b +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.66b Other Changes: @@ -1840,7 +3363,7 @@ Other Changes: VERSION 1.66 (Released 2018-11-22) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.66 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.66 Breaking Changes: @@ -1901,7 +3424,7 @@ Other Changes: VERSION 1.65 (Released 2018-09-06) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.65 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.65 Breaking Changes: @@ -1927,7 +3450,7 @@ Other Changes: VERSION 1.64 (Released 2018-08-31) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.64 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.64 Changes: @@ -1951,7 +3474,7 @@ Changes: VERSION 1.63 (Released 2018-08-29) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.63 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.63 Breaking Changes: @@ -2045,7 +3568,7 @@ Other Changes: VERSION 1.62 (Released 2018-06-22) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.62 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.62 Breaking Changes: @@ -2126,7 +3649,7 @@ Other Changes: VERSION 1.61 (Released 2018-05-14) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.61 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.61 Breaking Changes: @@ -2202,7 +3725,7 @@ Other Changes: VERSION 1.60 (Released 2018-04-07) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.60 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.60 The gamepad/keyboard navigation branch (which has been in the work since July 2016) has been merged. Gamepad/keyboard navigation is still marked as Beta and has to be enabled explicitly. @@ -2368,7 +3891,7 @@ Other Changes: VERSION 1.53 (Released 2017-12-25) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.53 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.53 Breaking Changes: @@ -2507,7 +4030,7 @@ Other Changes: VERSION 1.52 (2017-10-27) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.52 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.52 Breaking Changes: @@ -2613,7 +4136,7 @@ Beta Navigation Branch: VERSION 1.51 (2017-08-24) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.51 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.51 Breaking Changes: @@ -2677,7 +4200,7 @@ Other Changes: VERSION 1.50 (2017-06-02) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.50 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.50 Breaking Changes: @@ -2773,7 +4296,7 @@ Other Changes: VERSION 1.49 (2016-05-09) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.49 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.49 Breaking Changes: @@ -2851,7 +4374,7 @@ Other changes: VERSION 1.48 (2016-04-09) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.48 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.48 Breaking Changes: @@ -2921,7 +4444,7 @@ Other Changes: VERSION 1.47 (2015-12-25) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.47 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.47 Changes: @@ -2974,7 +4497,7 @@ Changes: VERSION 1.46 (2015-10-18) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.46 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.46 Changes: @@ -3026,7 +4549,7 @@ Changes: VERSION 1.45 (2015-09-01) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.45 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.45 Breaking Changes: @@ -3086,7 +4609,7 @@ Other Changes: VERSION 1.44 (2015-08-08) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.44 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.44 Breaking Changes: @@ -3130,7 +4653,7 @@ Other Changes: VERSION 1.43 (2015-07-17) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.43 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.43 Breaking Changes: @@ -3202,7 +4725,7 @@ Other Changes: VERSION 1.42 (2015-07-08) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.42 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.42 Breaking Changes: @@ -3247,7 +4770,7 @@ Other Changes: VERSION 1.41 (2015-06-26) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.41 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.41 Breaking Changes: @@ -3291,7 +4814,7 @@ Other Changes: VERSION 1.40 (2015-05-31) ----------------------------------------------------------------------- -Decorated log: https://github.com/ocornut/imgui/releases/tag/v1.40 +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.40 Breaking Changes: @@ -3380,6 +4903,663 @@ Other Changes: ----------------------------------------------------------------------- + VERSION 1.38 (2015-04-20) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.38 + +Breaking Changes: + +- Renamed IsClipped() to IsRectClipped(). Kept inline redirection function (will obsolete). +- Renamed ImDrawList::AddArc() to ImDrawList::AddArcFast(). + +Other Changes: + +- Added DragFloat(), DragInt() widget, click and drag to adjust value with given step. + Hold SHIFT/ALT to speed-up/slow-down. Double-click or CTRL+click to input text. + Passing min >= max makes the widget unbounded. +- Added DragFloat2(), DragFloat3(), DragFloat4(), DragInt2(), DragInt3(), DragInt4() helper variants. +- Added ShowMetricsWindow() which is mainly useful to debug ImGui internals. Added IO.MetricsRenderVertices counter. +- Added ResetMouseDragDelta() for iterative dragging operations. +- Added ImFontAtlas::AddFontFromCompressedTTF() helper + binary_to_compressed_c.cpp tool to compress a file and create a .c array from it. +- Added PushId() GetId() variants that takes string range to avoid user making unnecessary copies. +- Added IsItemVisible(). +- Fixed IsRectClipped() incorrectly returning false when log is enabled. +- Slider: visual fix in the unlikely that style.GrabMinSize is larger than a slider. +- SliderFloat: removed support for unbound slider (using FLT_MAX), caused various inconsistency. Use InputFloat()/DragFloat(). +- ColorEdit4: hide components prefix if there's no space for them. +- Combo: adding frame padding inside the combo box. +- Columns: mouse dragging uses absolute mouse coordinates.Fixed dragging left-most column of an auto-resizable window. #125 +- Selectable: render highlight into AutoFitPadding region but do not extend it, fixing visual gap. +- Focus: Allow SetWindowFocus(NULL) to remove focus. +- Focus: Clicking on void (outside an ImGui windows) loses keyboard-focus so application can use TAB. +- Popup: Fixed hovering over a popup's child (popups disable hovering on other windows but not their childs) #197 +- Fixed active widget not releasing its active state while being clipped. +- Fixed user-facing version of IsItemHovered() ignoring overlapping windows. +- Fixed label vertical alignment for InputInt2(), InputInt3(), InputInt4(). +- Fixed new collapsed auto-resizing window with saved .ini settings not calculating their initial width #176 +- Fixed Begin() returning true on collapsed windows that had loaded settings #176 +- Fixed style.DisplaySafeAreaPadding handling from being applied on window prior to them auto-fitting. +- ShowTestWindow(): added examples for DragFloat, DragInt and only custom label embedded in format strings. +- ShowTestWindow(): fixed "manipulating titles" example not doing the right thing, broken in ff35d24 +- Examples: OpenGL/GLFW: Fixed modifier key state setting in GLFW callbacks. +- Examples: OpenGL/GLFW: Added glBindTexture(0) in OpenGL fixed pipeline examples. Save restore current program and texture in the OpenGL3 example. +- Examples: DirectX11: Removed unnecessary vertices conversion and CUSTOMVERTEX types. +- Comments, fixes, tweaks. + + +----------------------------------------------------------------------- + VERSION 1.37 (2015-03-26) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.37 + +Other Changes: + +- Added a more convenient three parameters version of Begin() which covers the common uses better. +- Added mouse cursor types handling (resize, move, text input cursors, etc.) that user can query with GetMouseCursor(). Added demo and instructions in ShowTestWindow(). +- Added embedded mouse cursor data for MouseDrawCursor software cursor rendering, for consoles/tablets/etc. (#155). +- Added first version of BeginPopup/EndPopup() helper API to create popup menus. Popups automatically lock their position to the mouse cursor when first appearing. They close automatically when clicking outside, and inhibit hovering items from other windows when active (to allow for clicking outside). (#126) +- Added thickness parameter to ImDrawList::AddLine(). +- Added ImDrawList::PushClipRectFullScreen() helper. +- Added style.DisplaySafeAreaPadding which was previously hard-coded (useful if you can't see the edges of your display, e.g. TV screens). +- Added CalcItemRectClosestPoint() helper. +- Added GetMouseDragDelta(), IsMouseDragging() helpers, given a mouse button and an optional "unlock" threshold. Added io.MouseDragThreshold setting. (#167) +- IsItemHovered() return false if another widget is active, aka we can't use what we are hovering now. +- Added IsItemHoveredRect() if old behavior of IsItemHovered() is needed (e.g. for implementing the drop side of a drag'n drop operation). +- IsItemhovered() include space taken by label and behave consistently for all widgets (#145) +- Auto-filling child window feed their content size to parent (#170) +- InputText() removed the odd ~ characters when clipping. +- InputText() update its width in case of resize initiated programmatically while the widget is active. +- InputText() last active preserve scrolling position. Reset scroll if widget size becomes bigger than contents. +- Selectable(): not specifying a width defaults to using max of label width and remaining width. +- Selectable(const char*, bool) version has bool defaulting to false. +- Selectable(): fixed misusage of GetContentRegionMax().x leaking into auto-fitting. +- Windows starting Collapsed runs initial auto-fit to retrieve a width for their title bar (#175) +- Fixed new window from having an incorrect content size on their first frame, if queried by user. Fixed SetWindowPos/SetNextWindowPos having a side-effect size computation (#175) +- InputFloat(): fixed label alignment if total widget width forcefully bigger than space available. +- Auto contents size aware of enforced vertical scrollbar if window is larger than display size. +- Fixed new windows auto-fitting bigger than their .ini saved size. This was a bug but it may be a desirable effect sometimes, may reconsider it. +- Fixed negative clipping rectangle when collapsing windows that could affect manual submission to ImDrawList and end-user rendering function if unhandled (#177) +- Fixed bounding measurement of empty groups (fix #162) +- Fixed assignment order in Begin() making auto-fit size effectively lag by one frame. Also disabling "clamp into view" while windows are auto-fitting so that auto-fitting window in corners don't get pushed away. +- Fixed MouseClickedPos not updated on double-click update (#167) +- Fixed MouseDrawCursor feature submitting an empty trailing command in the draw list. Fixed unmerged draw calls for software mouse cursor. +- Fixed double-clicking on resize grip keeping the grip active if mouse button is kept held. +- Bounding box tests exclude higher bound, so touching items (zero spacing) don't report double hover when cursor is on edge. +- Setting io.LogFilename to NULL disable default LogToFile() (part of #175) +- Tweak stb_textedit integration to be lenient if another piece of code are leaking their STB_TEXTEDIT definitions/symbols. +- Shutdown() freeing a few extra vectors so they don't have to freed by destruction (#169) +- Examples: OpenGL2/3 examples automatically hide the OS mouse cursor if software cursor rendering is used. +- ShowTestWindow: Added Widgets Alignment demo under Layout section +- ShowTestWindow: Added simple dragging widget example. +- ShowTestWindow: Graph has checkbox under the label, also demo using BeginGroup/EndGroup(). +- ShowTestWindow: Using SetNextWindowSize() in examples to encourage its use. +- Fixes, tweaks, comments. + + +----------------------------------------------------------------------- + VERSION 1.36 (2015-03-18) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.36 + +Other Changes: + +- Added ImGui::GetVersion(), IMGUI_VERSION (#127) +- Added BeginGroup()/EndGroup() layout tools (#160). +- Added Indent() / Unindent(). +- Added InputInt2(), InputInt3(), InputInt4() for completeness. +- Added GetItemRectSize(). +- Added VSliderFloat(), VSliderInt(), vertical sliders. +- Added IsRootWindowFocused(), IsRootWindowOrAnyChildFocused(). +- Added io.KeyAlt + support in examples apps, in prevision for future usage of Alt modifier (was missing). +- Added ImGuiStyleVar_GrabMinSize enum value for PushStyleVar(). +- Various fixes related to vertical alignment of text after widget of varied sizes. Allow for multiple blocks of multiple lines text on the same "line". Added demos. +- Explicit size passed to Plot*(), Button() includes the frame padding. +- Style: Changed default Border and Column border colors to be most subtle. +- Renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing. +- Renamed GetWindowIsFocused() to IsWindowFocused(), kept inline redirection with old name (will obsolete). +- Renamed GetItemRectMin()/GetItemRectMax() to GetItemRectMin()/GetItemRectMax(), kept inline redirection with old name (will obsolete). +- Sliders: Fast-path when power=1.0f, also makes code easier to read. +- Sliders: Fixed parsing of decimal precision back from format string when using %%. +- Sliders: Fixed hovering bounding test excluding padding between outer frame and grab (there was a few pixels dead-zone). +- Separator() logs itself as text when passing through text log. +- Optimisation: TreeNodeV() early out if SkipItems is set without formatting. +- Moved various static buffers into state. Increase the formatted string buffer from 1K to 3K. +- Examples: Example console keeps focus on input box at all times. +- Examples: Updated to GLFW 3.1. Moved to examples/libs/ folder. +- Examples: Added 64-bit projects for MSVC. +- Examples: Increase warning level from /W3 to /W4 for MSVC. +- Examples: DirectX9: fixed duplicate creation of vertex buffer. +- Renamed internal type ImGuiAabb to ImRect. Changed mentions of 'box' or 'aabb' to say 'rect'. +- Tweaks, minor fixes and comments. + + +----------------------------------------------------------------------- + VERSION 1.35 (2015-03-09) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.35 + +Other Changes: + +- Examples: refactored all examples application to make it easier to isolate and grab the code you need for OpenGL 2/3, DirectX 9/11, and toward a more sensible format for samples. +- Scrollbar grab have a minimum size (style.GrabSizeMin), always visible even with huge scroll amount. (#150). +- Scrollbar: Clicking inside the grab box doesn't modify scroll value. Subsequent movement always relative. +- Added "###" labelling syntax to pass a label that isn't part of the hashed ID (#107), e.g. ("%d###static_id",rand()). +- Added GetColumnIndex(), GetColumnsCount() (#154) +- Added GetScrollPosY(), GetScrollMaxY(). +- Fixed the Chinese/Japanese glyph ranges; include missing punctuations (#156) +- Fixed Combo() and ListBox() labels not included in declared size, for use with SameLine(), etc. (fix #149, #151). +- Fixed ListBoxHeader() incorrect handling of SkipItems early out when window is collapsed. +- Fixed using IsItemHovered() after EndChild() (#151) +- Fixed malformed UTF-8 decoding errors leading to infinite loops (#158) +- InputText() handles buffer limit correctly for multi-byte UTF-8 characters, won't insert an incomplete UTF-8 character when reaching buffer limit (fix #158) +- Handle double-width space (0x3000) in various places the same as single-width spaces, for Chinese/Japanese users. +- Collapse triangle uses text color (not border color). +- Fixed font fallback glyph width. +- Renamed style.ScrollBarWidth to style.ScrollbarWidth to be consistent with other casing. +- Windows: setup a default handler for ImeSetInputScreenPosFn so the IME dialog (for Japanese/Chinese, etc.) is positioned correctly as you input text. +- Windows: default clipboard handlers for Windows handle UTF-8. +- Examples: Fixed DirectX 9/11 examples applications handling of Microsoft IME. +- Examples: Allow DirectX 9/11 examples applications to resize the window. +- ShowTestWindow: Fixed "undo" button of custom rendering applet. +- ShowTestWindow: Added "Manipulating Window Title" example. + + +----------------------------------------------------------------------- + VERSION 1.34 (2015-03-02) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.34 + +Other Changes: + +- Added Bullet() helper - equivalent to BulletText(""), SameLine(). +- Added SetWindowFocus(), SetWindowFocus(const char*), SetNextWindowFocus() (#146) +- Added SetWindowPos(), SetWindowSize(), SetWindowCollaposed() given a window name. +- Added SetNextTreeNodeOpened() with optional condition flag in replacement of OpenNextNode() and consistent with other API. +- Renamed ImGuiSetCondition_* to ImGuiSetCond_* and ImGuiCondition_FirstUseThisSession to ImGuiCond_Once. +- Added missing definition for ImGui::GetWindowCollapsed(). +- Fixed GetGlyphRangesJapanese() actually missing katakana ranges and a few useful extensions. +- Fixed clicking on a widget in a child window not focusing the parent window (#147). +- Fixed clicking on empty space of child window not setting keyboard focus for the child window (#147). +- Fixed IsItemHovered() behaving differently on Combo() (#145) +- Fixed ColumnOffsets storage not honoring SetStateStorage() (not very useful but consistent). +- Examples: Removed dependency on Glew for OpenGL examples. Removed Glew binaries for Windows. +- Examples: Fixed link warning for OpenGL windows examples. +- Comments, tweaks. + +----------------------------------------------------------------------- + VERSION 1.33b (2015-02-23) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.33b + +Other Changes: + +- Fixed resizing columns. + + +----------------------------------------------------------------------- + VERSION 1.33 (2015-02-22) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.33 + +Other Changes: + +- InputText: having a InputText widget active doesn't steal mouse inputs from clicking on a button before losing focus (relate to #134) +- InputText: cursor/selection/undo stack persist when using other widgets and getting back to same (#134). +- InputText: fix effective buffer size being smaller than necessary by 1 byte (so if you give 3 bytes you can input 2 ascii chars + zero terminator, which is correct). +- Added IsAnyItemActive(). +- Child window explicitly inherit collapse state from parent (so if user keeps submitting items even thought Begin has returned 'false' the child items will be clipped faster). +- BeginChild() return a bool the same way Begin() does. if true you can skip submitting content. +- Removed extraneous (1,1) padding on child window (pointed out in #125) +- Columns: doesn't bail out when SkipItems is set (fix #136) +- Columns: Separator() within column correctly vertical offset all cells (pointed out in #125) +- GetColumnOffset() / SetColumnOffset() handles padding values more correctly so matching columns can be lined up between a parent and a child window (cf. #125) +- Fix ImFont::BuildLookupTable() potential dangling pointer dereference (fix #131) +- Fix hovering of child window extending past their parent not taking account of parent clipping rectangle (fix #137) +- Sliders: value text is clipped inside the frame when resizing sliders to be small. +- ImGuITextFilter::Draw() use regular width call rather than computing its own arbitrary width. +- ImGuiTextFilter: can take a default filter string during construction. + + +----------------------------------------------------------------------- + VERSION 1.32 (2015-02-11) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.32 + +Other Changes: + +- Added Selectable() building block for various list boxes, combo boxes, etc. +- Added ListBox() (#129). +- Added ListBoxHeader(), ListBoxFooter() for customized list traversal and creating multi-selection boxes. +- Fixed title bar text clipping issue (fix #128). +- InputText: added ImGuiInputTextFlags_CallbackCharFilter system for filtering/replacement (#130). Callback now passed an "EventFlag" parameter. +- InputText: Added ImGuiInputTextFlags_CharsUppercase and ImGuiInputTextFlags_CharsNoBlank stock filters. +- PushItemWidth() can take negative value to right-align items. +- Optimisation: Columns offsets cached to avoid unnecessary binary search. +- Optimisation: Optimized CalcTextSize() function by about 25% (they are often the bottleneck when submitting thousands of clipped items). +- Added ImGuiCol_ChildWindowBg, ImGuiStyleVar_ChildWindowRounding for completeness and flexibility. +- Added BeginChild() variant that takes an ImGuiID. +- Tweak default ImGuiCol_HeaderActive color to be less bright. +- Calculate framerate for the user (IO.Framerate), as a purely luxurious feature and to reduce sample code size a little. + + +----------------------------------------------------------------------- + VERSION 1.31 (2015-02-08) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.31 + +Other Changes: + +- Added ImGuiWindowFlags_NoCollapse flag. +- Added a way to replace the internal state pointer so that we can optionally share it between modules (e.g. multiple DLLs). +- Added tint_col parameter to ImageButton(). +- Added CalcListClipping() helper to perform faster/coarse clipping on user side (when manipulating lists with thousands of items). +- Added GetCursorPosX() / GetCursorPosY() shortcuts. +- Renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing(). +- Combo box always appears above other child windows of a same parent. +- Combo/Label: label is properly clipped inside the frame (#23). +- Added cpu-side text clipping functions which are used in some instances to avoid extra draw calls. +- InputText: Filtering private Unicode range 0xE000-0xF8FF. +- Fixed holding button over scrollbar creating a small feedback loop with calculation of contents size. +- Calling SetCursorPos() automatically extends the contents size. +- Track ownership of mouse clicks. Avoid requesting IO.WantCaptureMouse if initial click was outside of ImGui. +- Removed the dependency on realloc(). +- Other fixes, tweaks and comments. + + +----------------------------------------------------------------------- + VERSION 1.30 (2015-02-01) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.30 + +Breaking Changes: + +- Big update! Initialisation had to be changed. You don't need to load PNG data anymore. The new system gives you uncompressed texture data. + - This sequence: + const void* png_data; + unsigned int png_size; + ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); + // + - Became: + unsigned char* pixels; + int width, height; + // io.Fonts->AddFontFromFileTTF("myfontfile.ttf", 24.0f); // Optionally load another font + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + // + io.Fonts->TexID = (your_texture_identifier); + - PixelCenterOffset has been removed and isn't a necessary setting anymore. Offset your projection matrix by 0.5 if you have rendering problems. + +Other Changes: + +- Loading TTF files with stb_truetype.h. +- We still embed a compressed pixel-perfect TTF version of ProggyClean for convenience. +- Runtime font rendering is a little faster than previously. +- You can load multiple fonts with multiple size inside the font atlas. Rendering with multiple fonts are still merged into a single draw call whenever possible. +- The system handles UTF-8 and provide ranges to easily load e.g. characters for Japanese display. +- Added PushFont() / PopFont(). +- Added Image() and ImageButton() to display your own texture data. +- Added callback system in command-list. This can be used if you want to do your own rendering (e.g. render a 3D scene) inside ImGui widgets. +- Added IsItemActive() to tell if last widget is being held / modified (as opposed to just being hovered). Useful for custom dragging behaviors. +- Style: Added FrameRounding setting for a more rounded look (default to 0 for now). +- Window: Fixed using multiple Begin/End pair on the same wnidow. +- Window: Fixed style.WindowMinSize not being honored properly. +- Window: Added SetCursorScreenPos() helper (WindowPos+CursorPos = ScreenPos). +- ColorEdit3: clicking on color square change the edition. The toggle button is hidden by default. +- Clipboard: Fixed logging to clipboard on architectures where va_list are passed by reference to vsnprintf. +- Clipboard: Improve memory reserve policy for Clipboard / ImGuiTextBuffer. +- Tooltip: Always auto-resize. +- Tooltip: Fixed TooltigBg color not being honored properly. +- Tooltip: Allow SetNextWindowPos() to be used on tooltips. +- Added io.DisplayVisibleMin / io.DisplayVisibleMax to ease integration of virtual / scrolling display. +- Added Set/GetVoidPtr in ImGuiStorage. +- Added ColorConvertHSVtoRGB, ColorConvertRGBtoHSV, ColorConvertFloat4ToU32 helpers. +- Added ImColor() inline helper to easily convert colors to packed 4x1 byte or 4x1 float formats. +- Added io.MouseDrawCursor option to draw a mouse cursor for now (on systems that don't have one) +- Examples: Added custom drawing app example for using ImDrawList api. +- Lots of others fixes, tweaks and comments! + + +----------------------------------------------------------------------- + VERSION 1.20 (2015-01-07) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.20 + +- Fixed InputInt() InputFloat() label not declaring their width, breaking usage of SameLine(). +- Fixed hovering of combo boxes that extend beyond the parent window limits. +- Fixed text input of Unicode character in the 128-255 range. +- Fixed clipboard pasting into an InputText box not filtering the characters according to contents semantic. +- Dragging outside area of a widget while it is active doesn't trigger hover on other widgets. +- Activating widget bring parent window to front if not already. +- Checkbox and Radio buttons activate on click-release to be consistent with other widgets and most UI. +- InputText() nows consume input characters immediately so they cannot be reused if ImGui::Update is called again with a call to ImGui::Render(). (fixes #105) +- Examples: Console: added support for History callbacks + some cleanup. +- Various small optimisations. +- Cleanup and other fixes. + + +----------------------------------------------------------------------- + VERSION 1.19 (2014-12-30) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.19 + +- Tightening default style a little. +- Added ImGuiStyleVar_WindowRounding enum for PushStyleVar() API. +- Added SliderInt2(), SliderInt3(), SliderInt4() for consistency. +- Widgets more consistently handle empty labels (starting with ## mark) for their size calculation. +- Fixed crashing with zero sized frame-buffer. +- Fixed ImGui::Combo() not registering its size properly when clipped out of screen. +- Renamed second parameter to Begin() to 'bool* p_opened' to be a little more self-explanatory. Added more comments on the use of Begin(). +- Logging: Added LogText() to pass text straight to the log output (tty/clipboard/file) without rendering it. +- Logging: Added LogFinish() to stop logging at an arbitrary point. +- Logging: Log depth padding relative to start depth. +- Logging: Tree nodes and headers looking better when logged to text. +- Logging: Log outputs \r\n under Windows to play it nicely with \n unaware tools such as Notepad. +- Style editor: added a button to output colors to clipboard/tty. +- OpenGL3 example: fix growing of VBO. +- Cleanup and other minor fixes. + + +----------------------------------------------------------------------- + VERSION 1.18 (2014-12-11) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.18 + +- Added ImGuiWindowFlags_NoScrollWithMouse, disable mouse wheel scrolling on a window. +- Added ImGuiWindowFlags_NoSavedSettings, disable loading/saving window state to .ini file. +- Added SetNextWindowPos(), SetNextWindowSize(), SetNextWindowCollapsed() API along with SetWindowPos(), SetWindowSize(), SetWindowCollapsed(). All functions include an optional second parameter to easily set current value vs session default value vs persistent default value. +- Removed rarely useful SetNewWindowDefaultPos() in favor of new API. +- Fixed hovering of lower-right resize grip when it is above a child window. +- Fixed InputInt() writing to output when it doesn't need to. +- Added IMGUI_INCLUDE_IMGUI_USER_H define to include user file at the bottom of imgui.h without modifying the vanilla distribution. +- ImGuiStorage helper can store float + added helpers to get pointer to stored data. +- Setup Travis CI integration. Builds the OpenGL examples on Linux with GCC and Clang. +- Examples: Added a "Fixed overlay" example in ShowTestWindow(). +- Examples: Re-added OpenGL 3 programmable-pipeline example (along with the existing fixed pipeline example). +- Examples: OpenGL examples can now resize the application window. +- Other minor fixes and comments. + + +----------------------------------------------------------------------- + VERSION 1.17 (2014-12-03) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.17 + +- Added ImGuiWindowFlags_AlwaysAutoResize + example app. +- Calling ImGui::SetWindowSize(0,0) force an autofit without zero-sizing first. +- ImGui::InputText() support for completion/history/custom callback + added fancy completion example in the console demo app. +- Not word-wrapping on apostrophes. +- Increased visibility of check box and radio button with smaller size. +- Smooth mouse scrolling on OSX (uses floating point scroll/wheel input). +- New version of IMGUI_ONCE_UPON_A_FRAME helper macro that works with all compilers. +- Moved IO.Font*** options to inside the IO.Font-> structure.. Added IO.FontGlobalScale setting (in addition to Font->Scale per individual font). +- Fixed more Clang -Weverything warnings. +- Examples: Added DirectX11 example application. +- Examples: Created single .sln solution for all example projects. +- Examples: Fixed DirectX9 example window initially showing an hourglass cursor. +- Examples: Removed Microsoft IME handler in examples, too niche/confusing. Moved equivalent code to imgui.cpp instruction block. + + +----------------------------------------------------------------------- + VERSION 1.16b (2014-11-21) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.16b + +- Fix broken PopStyleVar() crashing. + + +----------------------------------------------------------------------- + VERSION 1.16 (2014-11-21) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.16 + +- General fixing of Columns API to allow filling a cell with multiple widgets before switching to the next column. +- Added documentation INDEX to top of imgui.cpp. +- Fixed unaligned memory access for Emscripten compatibility. +- Various pedantic warning fixes (now testing with Clang). +- Added extra asserts to catch incorrect usage. +- PushStyleColor() / PushStyleVar() can be used outside the scope of a window (namely to change variables that are used within the Begin() call). +- PushTextWrapPos() defaults to 0.0 (right-end of current drawing region). +- Fixed compatibility with std::vector if user decide to #define ImVector. +- MouseWheel input is now normalized. +- Added IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT compile-time option to redefine the vertex layout. +- Style editor: colors listed inside a scrolling region. +- Examples: tweaks and fixes. + + +----------------------------------------------------------------------- + VERSION 1.15 (2014-11-07) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.15 + +- Renamed IsHovered() to IsItemHovered(). +- Added word-wrapping API: TextWrapped(), PushTextWrapPos(), PopTextWrapPos(). +- Added IsItemFocused() to tell if last widget is being focused for keyboard input. +- Added overloads of ImGui::PlotLines() and ImGui::PlotHistogram() taking a function pointer to get values. +- Added SetWindowSize(). +- Added GetContentRegionMax() supporting columns. Some bug fixes with using columns. +- Added PushStyleVar(),PopStyleVar() helpers to modify style from user code. +- Added dummy IMGUI_API definition in front of all entry-points for silly DLL action. +- Allowing BeginChild() allows to specify negative sizes to specify "use remaining minus xx". +- Windows with the NoResize flag can still use auto-fitting. +- Added a simple example console into the demo window. +- Comments and fixes. + + +----------------------------------------------------------------------- + VERSION 1.14 (2014-10-25) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.14 + +- Comments and fixes. +- Added SetKeyboardFocusHere() to set input focus from code. +- Added GetWindowFont(), GetWindowFontSize() for users of the low-level ImDrawList API. +- Added a UserData void *pointer so that the callback functions can access user state "Just in case a project has adverse reactions to adding globals or statics in their own code." +- Renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL + + +---------------------------------------------------------------------- + VERSION 1.13 (2014-09-30) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.13 + +- Added support for UTF-8 for international text display and text edition/input (if the font supports it). +- Added sample "M+ font" by Coji Morishita in extra_fonts/ to display Japanese text. +- Added IO.ImeSetInputScreenPosFn callback for positioning OS IME input. +- Added IO.FontFallbackGlyph (default to '?'). +- OpenGL example: added commented code to load custom font from file-system. +- OpenGL example: shared makefile for Linux and MacOSX. + + +---------------------------------------------------------------------- + VERSION 1.12 (2014-09-24) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.12 + +- Added IO.FontBaseScale value for easy scaling of all windows. +- Added IsMouseHoveringWindow(), IsMouseHoveringAnyWindow(), IsPosHoveringAnyWindow() helpers. +- Added va_list variations of all functions taking ellipsis (...) parameters. +- Added section in documentation to explicitly document cases of API breaking changes (e.g. renamed IM_MALLOC below). +- Moved IM_MALLOC / IM_FREE defines. to IO structure members that can be set at runtime (also allowing precompiled ImGui to cover more use cases). +- Fixed OpenGL samples for Retina display. +- Comments and minor fixes. + + +---------------------------------------------------------------------- + VERSION 1.11 (2014-09-10) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.11 + +- Added more comments in the code. +- Made radio buttons render ascii when logged into tty/file/clipboard. +- Added ImGuiInputTextFlags_EnterReturnsTrue flag to InputText() and variants. +- Added #define IMGUI_INCLUDE_IMGUI_USER_CPP to optionally include imgui_user.cpp from the end of imgui.cpp +- Fixed file-descriptor leak if ImBitmapFont::LoadFromFile() calls to fseek/ftell fails. + + +---------------------------------------------------------------------- + VERSION 1.10 (2014-08-31) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.10 + +- User can override memory allocators by #define-ing IM_MALLOC, IM_FREE, IM_REALLOC, +- Added SetCursorPosX(), SetCursorPosY() shortcuts. +- Checkbox() returns true when pressed. +- Added optional external fonts data in extra_fonts/ for reference. +- Removed the need to setup IO.FontHeight when using a custom font. +- Added comments on external fonts usage. + + +---------------------------------------------------------------------- + VERSION 1.09 (2014-08-28) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.09 + +Breaking Changes: + +- The behaviour of PixelCenterOffset changed! You may need to change your value if you had set it to non-default in your code and/or offset your projection matrix by 0.5 pixels. It is likely that the default PixelCenterOffset value of 0.0 is now suitable unless your rendering uses some form of multisampling. + +Other Changes: + +- Various minor render tweaks and fixes. Better support for renderers using multisampling. +- Moved IMGUI_FONT_TEX_UV_FOR_WHITE #define to a variable in the IO structure so font can be changed at runtime. +- Minor other fixes, tweaks, comments. + + +---------------------------------------------------------------------- + VERSION 1.08 (2014-08-25) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.09 + +- Fixed ImGuiTextFilter trimming of leading/trailing blanks. +- Fixed file descriptor leak on LoadSettings() failure. +- Fix type conversion compiler warnings. +- Added basic sizes edition in the style editor. +- Added CalcTextSize(), GetCursorScreenPos() functions. +- Disable client state in OpenGL example after rendering. +- Converted all Tabs to Spaces in sources. + + +---------------------------------------------------------------------- + VERSION 1.07 (2014-08-18) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.07 + +- Added InputFloat4(), SliderFloat4() helpers. +- Added global Alpha in ImGuiStyle structure. When Alpha=0.0, ImGui skips most of logic and all rendering processing. +- Fix clipping of title bar text. +- Fix to allow the user to call NewFrame() multiple times without calling Render(). +- Reduce inner window clipping to take account for the extend of CollapsingHeader() - share same clipping rectangle. +- Fix for child windows with inverted clip rectangles (when scrolled and out of screen, Etc.). +- Minor fixes, tweaks, comments. + + +---------------------------------------------------------------------- + VERSION 1.06 (2014-08-15) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.06 + +- Added BeginTooltip()/EndTooltip() helpers to create tooltips with custom contents. +- Added TextColored() helper. +- Added a 'stride' parameter to PlotLines() / PlotHistogram(). +- Fixed PlotLines() / PlotHistogram() from occasionally wrapping back to the most-left value. +- TreeNode() / CollapsingHeader() ignore clicks when CTRL or SHIFT are held. +- Slowed down mouse wheel scrolling inside combo boxes. +- Minor tweaks. +- Fixed trailing '\n' in text strings reporting extra line height. +- Fixed tooltip position needlessly leaking into .ini file. +- Fixed invalid .ini file data persistently being saved back into the file. + + +---------------------------------------------------------------------- + VERSION 1.05 (2014-08-14) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.05 + +- Added default clipboard functions for Windows + "private" clipboard on other systems (user can still override). +- Fixed logarithmic sliders and HSV conversions on Mac/Linux. +- Tidying up example applications so it looks easier to just grab code. +- Added GetItemBoxMin(), GetItemBoxMax(). +- Tweaks, more consistent #define names. +- Fix for doing multiple Begin()/End() during the same frame. + + +---------------------------------------------------------------------- + VERSION 1.04 (2014-08-13) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.04 + +- Fixes (v1.03 introduced a bug with combo box & scissoring bug OpenGL sample). +- Added ImGui::InputFloat2() and ImGui::SliderFloat2() functions. + + +---------------------------------------------------------------------- + VERSION 1.03 (2014-08-13) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.03 + +- OpenGL example now use the fixed function-pipeline + cleanups, down by 150 lines. +- Added quick & dirty Makefiles for MacOSX and Linux. +- Simplified the DrawList system, ImDrawCmd include the clipping rectangle + some optimisations. +- Fixed warnings for more stringent compilation settings. + + +---------------------------------------------------------------------- + VERSION 1.02 (2014-08-12) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.02 + +- Comments. +- Portability fixes. +- Fixing and tidying up sample applications. +- Checkboxes and radio buttons can be clicked on their labels as well as their icon. +- Checkboxes and radio buttons display in a different color when hovered. + + +---------------------------------------------------------------------- + VERSION 1.01 (2014-08-11) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.01 + +- Added PixelCenterOffset for OpenGL/DirectX compatibility. +- Commented and tweaked samples. +- Added Git ignore list. + + +---------------------------------------------------------------------- + VERSION 1.00 (2014-08-10) +----------------------------------------------------------------------- + +Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.00 -For older version, see https://github.com/ocornut/imgui/releases +- Initial release. diff --git a/third_party/imgui/docs/CONTRIBUTING.md b/third_party/imgui/docs/CONTRIBUTING.md new file mode 100644 index 00000000000..5cc9cdb53f4 --- /dev/null +++ b/third_party/imgui/docs/CONTRIBUTING.md @@ -0,0 +1,81 @@ +# Contributing Guidelines + +## Index + +- [Getting Started & General Advice](#getting-started--general-advice) +- [Issues vs Discussions](#issues-vs-discussions) +- [How to open an Issue](#how-to-open-an-issue) +- [How to open a Pull Request](#how-to-open-a-pull-request) +- [Copyright / Contributor License Agreement](#copyright--contributor-license-agreement) + +## Getting Started & General Advice + +- Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1). +- Please browse the [Wiki](https://github.com/ocornut/imgui/wiki) to find code snippets, links and other resources (e.g. [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started), [Useful extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions)). +- Please read [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) if your question relates to setting up Dear ImGui. +- Please read [docs/FAQ.md](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md). +- Please read [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) if your question relates to fonts or text. +- Please run `ImGui::ShowDemoWindow()` to explore the demo and its sources. +- Please use the search function of your IDE to search for symbols and comments related to your situation. +- Please use the search function of GitHub to look for similar topics (always include 'Closed' issues/pr in your search). +- You may [browse issues by Labels](https://github.com/ocornut/imgui/labels). +- Please use a web search engine to look for similar issues. +- If you get a crash or assert, use a debugger to locate the line triggering it and read the comments around. +- Please don't be a [Help Vampire](https://slash7.com/2006/12/22/vampires/). + +## 'Issues' vs 'Discussions' + +We are happy to use 'Issues' for many type of open-ended questions. We are encouraging 'Issues' becoming an enormous, centralized and cross-referenced database of Dear ImGui contents. + +Only if you: +- Cannot BUILD or LINK examples. +- Cannot BUILD, or LINK, or RUN Dear ImGui in your application or custom engine. +- Cannot LOAD a font. + +Then please [use the Discussions forums](https://github.com/ocornut/imgui/discussions) instead of opening an issue. + +If Dear ImGui is successfully showing in your app and you have used Dear ImGui before, you can open an Issue. Any form of discussions is welcome as a new issue. + +## How to open an issue + +You may use the Issue Tracker to submit bug reports, feature requests or suggestions. You may ask for help or advice as well. But **PLEASE CAREFULLY READ THIS WALL OF TEXT. ISSUES IGNORING THOSE GUIDELINES MAY BE CLOSED. USERS IGNORING THOSE GUIDELINES MIGHT BE BLOCKED.** + +Please do your best to clarify your request. The amount of incomplete or ambiguous requests due to people not following those guidelines is often overwhelming. Issues created without the requested information may be closed prematurely. Exceptionally entitled, impolite, or lazy requests may lead to bans. + +**PLEASE UNDERSTAND THAT OPEN-SOURCE SOFTWARE LIVES OR DIES BY THE AMOUNT OF ENERGY MAINTAINERS CAN SPARE. WE HAVE LOTS OF STUFF TO DO. THIS IS AN ATTENTION ECONOMY AND MANY LAZY OR MINOR ISSUES ARE HOGGING OUR ATTENTION AND DRAINING ENERGY, TAKING US AWAY FROM MORE IMPORTANT WORK.** + +Steps: + +- Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1). +- **PLEASE DO FILL THE REQUESTED NEW ISSUE TEMPLATE.** Including Dear ImGui version number, branch name, platform/renderer back-ends (imgui_impl_XXX files), operating system. +- **Try to be explicit with your GOALS, your EXPECTATIONS and what you have tried**. Be mindful of [The XY Problem](http://xyproblem.info/). What you have in mind or in your code is not obvious to other people. People frequently discuss problems and suggest incorrect solutions without first clarifying their goals. When requesting a new feature, please describe the usage context (how you intend to use it, why you need it, etc.). If you tried something and it failed, show us what you tried. +- **Please INCLUDE CODE. Provide a Minimal, Complete, and Verifiable Example ([MCVE](https://stackoverflow.com/help/mcve)) to demonstrate your problem**. An ideal submission includes a small piece of code that anyone can paste into one of the examples applications (examples/../main.cpp) or demo (imgui_demo.cpp) to understand and reproduce it. **Narrowing your problem to its shortest and purest form is the easiest way to understand it, explain it and fix it**. Please test your shortened code to ensure it exhibits the problem. **Often while creating the MCVE you will solve the problem!** Many questions that are missing a standalone verifiable example are missing the actual cause of their issue in the description, which ends up wasting everyone's time. +- **Attach screenshots (or GIF/video) to clarify the context**. They often convey useful information that is omitted by the description. You can drag pictures/files in the message edit box. Avoid using 3rd party image hosting services, prefer the long-term longevity of GitHub attachments (you can drag pictures into your post). On Windows, you can use [ScreenToGif](https://www.screentogif.com/) to easily capture .gif files. +- **If you are discussing an assert or a crash, please provide a debugger callstack**. Never state "it crashes" without additional information. If you don't know how to use a debugger and retrieve a callstack, learning about it will be useful. +- **Please make sure that your project has asserts enabled.** Calls to IM_ASSERT() are scattered in the code to help catch common issues. When an assert is triggered read the comments around it. By default IM_ASSERT() calls the standard assert() function. To verify that your asserts are enabled, add the line `IM_ASSERT(false);` in your main() function. Your application should display an error message and abort. If your application doesn't report an error, your asserts are disabled. +- Please state if you have made substantial modifications to your copy of Dear ImGui or the back-end. +- If you are not calling Dear ImGui directly from C++, please provide information about your Language and the wrapper/binding you are using. +- Be mindful that messages are being sent to the mailbox of "Watching" users. Try to proofread your messages before sending them. Edits are not seen by those users unless they browse the site. + +**Some unfortunate words of warning** +- If you are involved in cheating schemes (e.g. DLL injection) for competitive online multiplayer games, please don't post here. We won't answer and you will be blocked. It doesn't matter if your question relates to said project. We've had too many of you and need to protect our time and sanity. +- Due to frequent abuse of this service from the aforementioned users, if your GitHub account is anonymous and was created five minutes ago please understand that your post will receive more scrutiny and incomplete questions will be harshly dismissed. + +If you have been using Dear ImGui for a while or have been using C/C++ for several years or have demonstrated good behavior here, it is ok to not fulfill every item to the letter. Those are guidelines and experienced users or members of the community will know which information is useful in a given context. + +## How to open a Pull Request + +- **Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance.** PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it. +- Many PRs are useful to demonstrate a need and a possible solution but aren't adequate for merging (causing other issues, not seeing other aspects of the big picture, etc.). In doubt, don't hesitate to push a PR because that is always the first step toward pointing toward a problem, and finding the mergeable solution! Even if a PR stays unmerged for a long time, its presence can be useful for other users and helps toward finding a general solution. +- **When adding a feature,** please describe the usage context (how you intend to use it, why you need it, etc.). Be mindful of [The XY Problem](http://xyproblem.info/). +- **When fixing a warning or compilation problem,** please post the compiler log and specify the compiler version and platform you are using. +- **Attach screenshots (or GIF/video) to clarify the context and demonstrate the feature at a glance.** You can drag pictures/files in the message edit box. Prefer the long-term longevity of GitHub attachments over 3rd party hosting (you can drag pictures into your post). +- **Make sure your code follows the coding style already used in the codebase:** 4 spaces indentations (no tabs), `local_variable`, `FunctionName()`, `MemberName`, `// Text Comment`, `//CodeComment();`, C-style casts, etc.. We don't use modern C++ idioms and tend to use only a minimum of C++11 features. The applications under examples/ are generally less consistent because they sometimes try to mimic the coding style often adopted by a certain ecosystem (e.g. DirectX-related code tend to use the style of their sample). +- **Make sure you create a branch dedicated to the pull request**. In Git, 1 PR is associated to 1 branch. If you keep pushing to the same branch after you submitted the PR, your new commits will appear in the PR (we can still cherry-pick individual commits). + +## Copyright / Contributor License Agreement + +Any code you submit will become part of the repository and be distributed under the [Dear ImGui license](https://github.com/ocornut/imgui/blob/master/LICENSE.txt). By submitting code to the project you agree that the code is your work and that you can give it to the project. + +You also agree by submitting your code that you grant all transferrable rights to the code to the project maintainer, including for example re-licensing the code, modifying the code, and distributing it in source or binary forms. Specifically, this includes a requirement that you assign copyright to the project maintainer. For this reason, do not modify any copyright statements in files in any PRs. + diff --git a/third_party/imgui/docs/EXAMPLES.md b/third_party/imgui/docs/EXAMPLES.md index 8321aa1ee7a..edaddb0554f 100644 --- a/third_party/imgui/docs/EXAMPLES.md +++ b/third_party/imgui/docs/EXAMPLES.md @@ -10,69 +10,73 @@ integrating Dear ImGui in your own application/game/engine. **Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** You can find Windows binaries for some of those example applications at: - http://www.dearimgui.org/binaries + https://www.dearimgui.com/binaries ### Getting Started Integration in a typical existing application, should take <20 lines when using standard backends. - At initialization: - call ImGui::CreateContext() - call ImGui_ImplXXXX_Init() for each backend. +```cpp +At initialization: + call ImGui::CreateContext() + call ImGui_ImplXXXX_Init() for each backend. - At the beginning of your frame: - call ImGui_ImplXXXX_NewFrame() for each backend. - call ImGui::NewFrame() +At the beginning of your frame: + call ImGui_ImplXXXX_NewFrame() for each backend. + call ImGui::NewFrame() - At the end of your frame: - call ImGui::Render() - call ImGui_ImplXXXX_RenderDrawData() for your Renderer backend. +At the end of your frame: + call ImGui::Render() + call ImGui_ImplXXXX_RenderDrawData() for your Renderer backend. - At shutdown: - call ImGui_ImplXXXX_Shutdown() for each backend. - call ImGui::DestroyContext() +At shutdown: + call ImGui_ImplXXXX_Shutdown() for each backend. + call ImGui::DestroyContext() +``` Example (using [backends/imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp) + [backends/imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)): - // Create a Dear ImGui context, setup some options - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); - io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable some options - - // Initialize Platform + Renderer backends (here: using imgui_impl_win32.cpp + imgui_impl_dx11.cpp) - ImGui_ImplWin32_Init(my_hwnd); - ImGui_ImplDX11_Init(my_d3d_device, my_d3d_device_context); - - // Application main loop - while (true) - { - // Beginning of frame: update Renderer + Platform backend, start Dear ImGui frame - ImGui_ImplDX11_NewFrame(); - ImGui_ImplWin32_NewFrame(); - ImGui::NewFrame(); - - // Any application code here - ImGui::Text("Hello, world!"); - - // End of frame: render Dear ImGui - ImGui::Render(); - ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); - - // Swap - g_pSwapChain->Present(1, 0); - } - - // Shutdown - ImGui_ImplDX11_Shutdown(); - ImGui_ImplWin32_Shutdown(); - ImGui::DestroyContext(); +```cpp +// Create a Dear ImGui context, setup some options +ImGui::CreateContext(); +ImGuiIO& io = ImGui::GetIO(); +io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable some options + +// Initialize Platform + Renderer backends (here: using imgui_impl_win32.cpp + imgui_impl_dx11.cpp) +ImGui_ImplWin32_Init(my_hwnd); +ImGui_ImplDX11_Init(my_d3d_device, my_d3d_device_context); + +// Application main loop +while (true) +{ + // Beginning of frame: update Renderer + Platform backend, start Dear ImGui frame + ImGui_ImplDX11_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + // Any application code here + ImGui::Text("Hello, world!"); + + // End of frame: render Dear ImGui + ImGui::Render(); + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + // Swap + g_pSwapChain->Present(1, 0); +} + +// Shutdown +ImGui_ImplDX11_Shutdown(); +ImGui_ImplWin32_Shutdown(); +ImGui::DestroyContext(); +``` Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. Please read the comments and instruction at the top of each file. -Please read FAQ at http://www.dearimgui.org/faq +Please read FAQ at https://www.dearimgui.com/faq -If you are using of the backend provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) +If you are using any of the backends provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual Changelog, so if you want to update them later it will be easier to catch up with what changed. @@ -100,15 +104,10 @@ OSX + OpenGL2 example.
(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) -[example_emscripten_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten_opengl3/)
-Emcripten + SDL2 + OpenGL3+/ES2/ES3 example.
-= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp
-Note that other examples based on SDL or GLFW + OpenGL could easily be modified to work with Emscripten. -We provide this to make the Emscripten differences obvious, and have them not pollute all other examples. - [example_emscripten_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten_wgpu/)
Emcripten + GLFW + WebGPU example.
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_wgpu.cpp +Note that the 'example_glfw_opengl3' and 'example_sdl2_opengl3' examples also supports Emscripten! [example_glfw_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_metal/)
GLFW (Mac) + Metal example.
@@ -117,18 +116,18 @@ GLFW (Mac) + Metal example.
[example_glfw_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl2/)
GLFW + OpenGL2 example (legacy, fixed pipeline).
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp
-**DO NOT USE THIS IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+**DO NOT USE THIS IF YOUR CODE/ENGINE IS USING MODERN GL or WEBGL (SHADERS, VBO, VAO, etc.)**
This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. -If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to -make things more complicated, will require your code to reset many OpenGL attributes to their initial +If your code is using GL3+ context or any semi modern GL calls, using this renderer is likely to +make things more complicated, will require your code to reset many GL attributes to their initial state, and might confuse your GPU driver. One star, not recommended. [example_glfw_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl3/)
GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (modern, programmable pipeline).
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp
-This uses more modern OpenGL calls and custom shaders.
-This may actually also work with OpenGL 2.x contexts!
-Prefer using that if you are using modern OpenGL in your application (anything with shaders). +This uses more modern GL calls and custom shaders.
+This support building with Emscripten and targetting WebGL.
+Prefer using that if you are using modern GL or WebGL in your application. [example_glfw_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/)
GLFW (Win32, Mac, Linux) + Vulkan example.
@@ -147,39 +146,39 @@ Null example, compile and link imgui, create context, run headless with no input This is used to quickly test compilation of core imgui files in as many setups as possible. Because this application doesn't create a window nor a graphic context, there's no graphics output. -[example_sdl_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_directx11/)
+[example_sdl2_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_directx11/)
SDL2 + DirectX11 example, Windows only.
-= main.cpp + imgui_impl_sdl.cpp + imgui_impl_dx11.cpp
-This to demonstrate usage of DirectX with SDL. += main.cpp + imgui_impl_sdl2.cpp + imgui_impl_dx11.cpp
+This to demonstrate usage of DirectX with SDL2. -[example_sdl_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_metal/)
-SDL2 (Mac) + Metal example.
-= main.mm + imgui_impl_sdl.cpp + imgui_impl_metal.mm +[example_sdl2_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_metal/)
+SDL2 + Metal example, Mac only.
+= main.mm + imgui_impl_sdl2.cpp + imgui_impl_metal.mm -[example_sdl_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_opengl2/)
+[example_sdl2_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_opengl2/)
SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline).
-= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp
-**DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
+= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_opengl2.cpp
+**DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING GL OR WEBGL (SHADERS, VBO, VAO, etc.)**
This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. -If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to -make things more complicated, will require your code to reset many OpenGL attributes to their initial +If your code is using GL3+ context or any semi modern GL calls, using this renderer is likely to +make things more complicated, will require your code to reset many GL attributes to their initial state, and might confuse your GPU driver. One star, not recommended. -[example_sdl_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_opengl3/)
+[example_sdl2_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_opengl3/)
SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example.
-= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp
-This uses more modern OpenGL calls and custom shaders.
-This may actually also work with OpenGL 2.x contexts!
+= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_opengl3.cpp
+This uses more modern GL calls and custom shaders.
+This support building with Emscripten and targetting WebGL.
+Prefer using that if you are using modern GL or WebGL in your application. -[example_sdl_sdlrenderer/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_sdlrenderer/)
-SDL2 (Win32, Mac, Linux, etc.) + SDL_Renderer (most graphics backends are supported underneath)
-= main.cpp + imgui_impl_sdl.cpp + imgui_impl_sdlrenderer.cpp
-This requires SDL 2.0.17+ (expected to release November 2021)
-We do not really recommend using SDL_Renderer as it is a rather primitive API. +[example_sdl2_sdlrenderer2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_sdlrenderer2/)
+SDL2 (Win32, Mac, Linux, etc.) + SDL_Renderer for SDL2 (most graphics backends are supported underneath)
+= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_sdlrenderer.cpp
+This requires SDL 2.0.18+ (released November 2021)
-[example_sdl_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_vulkan/)
+[example_sdl2_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_vulkan/)
SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
-= main.cpp + imgui_impl_sdl.cpp + imgui_impl_vulkan.cpp
+= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_vulkan.cpp
This is quite long and tedious, because: Vulkan.
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. @@ -200,8 +199,12 @@ DirectX12 example, Windows only.
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp
This is quite long and tedious, because: DirectX12. +[example_win32_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_opengl3/)
+Raw Windows + OpenGL3 + example (modern, programmable pipeline)
+= main.cpp + imgui_impl_win32.cpp + imgui_impl_opengl3.cpp
+ -### Miscallaneous +### Miscellaneous **Building** @@ -222,7 +225,7 @@ If you are interested in using Cmake to build and links examples, see: **About mouse cursor latency** Dear ImGui has no particular extra lag for most behaviors, -e.g. the value of 'io.MousePos' provided at the time of NewFrame() will result in windows being moved +e.g. the last value passed to 'io.AddMousePosEvent()' before NewFrame() will result in windows being moved to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience should be pleasant. However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated diff --git a/third_party/imgui/docs/FAQ.md b/third_party/imgui/docs/FAQ.md index 009027c11d8..c86cc1368bb 100644 --- a/third_party/imgui/docs/FAQ.md +++ b/third_party/imgui/docs/FAQ.md @@ -1,7 +1,7 @@ -# FAQ (Frequenty Asked Questions) +# FAQ (Frequently Asked Questions) You may link to this document using short form: - https://www.dearimgui.org/faq + https://www.dearimgui.com/faq or its real address: https://github.com/ocornut/imgui/blob/master/docs/FAQ.md or view this file with any Markdown viewer. @@ -25,7 +25,8 @@ or view this file with any Markdown viewer. | **Q&A: Usage** | | **[About the ID Stack system..
Why is my widget not reacting when I click on it?
How can I have widgets with an empty label?
How can I have multiple widgets with the same label?
How can I have multiple windows with the same label?](#q-about-the-id-stack-system)** | | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| -| [How can I use my own math types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-math-types-instead-of-imvec2imvec4) | +| [How can I use maths operators with ImVec2?](#q-how-can-i-use-maths-operators-with-imvec2) | +| [How can I use my own maths types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-maths-types-instead-of-imvec2imvec4) | | [How can I interact with standard C++ types (such as std::string and std::vector)?](#q-how-can-i-interact-with-standard-c-types-such-as-stdstring-and-stdvector) | | [How can I display custom shapes? (using low-level ImDrawList API)](#q-how-can-i-display-custom-shapes-using-low-level-imdrawlist-api) | | **Q&A: Fonts, Text** | @@ -49,14 +50,15 @@ or view this file with any Markdown viewer. **This library is poorly documented at the moment and expects the user to be acquainted with C/C++.** - The [Wiki](https://github.com/ocornut/imgui/wiki) is a hub to many resources and links. -- Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder to explain how to integrate Dear ImGui with your own engine/application. You can run those applications and explore them. +- Handy [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide to integrate Dear ImGui in an existing application. +- 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder to explain how to integrate Dear ImGui with your own engine/application. You can run those applications and explore them. - See demo code in [imgui_demo.cpp](https://github.com/ocornut/imgui/blob/master/imgui_demo.cpp) and particularly the `ImGui::ShowDemoWindow()` function. The demo covers most features of Dear ImGui, so you can read the code and see its output. - See documentation: [Backends](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md), [Examples](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md), [Fonts](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). - See documentation and comments at the top of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp) + general API comments in [imgui.h](https://github.com/ocornut/imgui/blob/master/imgui.h). - The [Glossary](https://github.com/ocornut/imgui/wiki/Glossary) page may be useful. - The [Issues](https://github.com/ocornut/imgui/issues) and [Discussions](https://github.com/ocornut/imgui/discussions) sections can be searched for past questions and issues. - Your programming IDE is your friend, find the type or function declaration to find comments associated with it. -- The `ImGui::ShowMetricsWindow()` function exposes lots of internal information and tools. Although it is primary designed as a debugging tool, having access to that information tends to help understands concepts. +- The `ImGui::ShowMetricsWindow()` function exposes lots of internal information and tools. Although it is primarily designed as a debugging tool, having access to that information tends to help understands concepts. ##### [Return to Index](#index) @@ -89,6 +91,7 @@ Many projects are using this branch and it is kept in sync with master regularly ### Q: How to get started? +Read [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started).
Read [EXAMPLES.md](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md).
Read [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md).
Read `PROGRAMMER GUIDE` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp).
@@ -114,7 +117,7 @@ void MyLowLevelMouseButtonHandler(int button, bool down) { // (1) ALWAYS forward mouse data to ImGui! This is automatic with default backends. With your own backend: ImGuiIO& io = ImGui::GetIO(); - io.MouseDown[button] = down; + io.AddMouseButtonEvent(button, down); // (2) ONLY forward mouse data to your underlying app/game. if (!io.WantCaptureMouse) @@ -122,12 +125,7 @@ void MyLowLevelMouseButtonHandler(int button, bool down) } ``` - -**Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs. - -**Note:** Those flags are updated by `ImGui::NewFrame()`. However it is generally more correct and easier that you poll flags from the previous frame, then submit your inputs, then call `NewFrame()`. If you attempt to do the opposite (which is generally harder) you are likely going to submit your inputs after `NewFrame()`, and therefore too late. - -**Note:** If you are using a touch device, you may find use for an early call to `UpdateHoveredWindowAndCaptureFlags()` to correctly dispatch your initial touch. We will work on better out-of-the-box touch support in the future. +**Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handles mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs. **Note:** Text input widget releases focus on the "KeyDown" event of the Return key, so the subsequent "KeyUp" event that your application receive will typically have `io.WantCaptureKeyboard == false`. Depending on your application logic it may or not be inconvenient to receive that KeyUp event. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.) @@ -139,7 +137,7 @@ void MyLowLevelMouseButtonHandler(int button, bool down) - The gamepad/keyboard navigation is fairly functional and keeps being improved. The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. Gamepad support is particularly useful to use Dear ImGui on a game console (e.g. PS4, Switch, XB1) without a mouse connected! - Keyboard: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard` to enable. - Gamepad: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad` to enable (with a supporting backend). -- See [Control Sheets for Gamepads](http://www.dearimgui.org/controls_sheets) (reference PNG/PSD for for PS4, XB1, Switch gamepads). +- See [Control Sheets for Gamepads](https://www.dearimgui.com/controls_sheets) (reference PNG/PSD for PS4, XB1, Switch gamepads). - See `USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp) for more details. ##### [Return to Index](#index) @@ -162,8 +160,8 @@ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-lik --- ### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text... -Your renderer is not using the font texture correctly or it hasn't been uploaded to the GPU. -- If this happens using the standard backends: A) have you modified the font atlas after `ImGui_ImplXXX_NewFrame()`? B) maybe the texture failed to upload, which could happens if for some reason your texture is too big. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). +Your renderer backend is not using the font texture correctly or it hasn't been uploaded to the GPU. +- If this happens using the standard backends: A) have you modified the font atlas after `ImGui_ImplXXX_NewFrame()`? B) maybe the texture failed to upload, which **can if your texture atlas is too big**. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). - If this happens with a custom backend: make sure you have uploaded the font texture to the GPU, that all shaders are rendering states are setup properly (e.g. texture is bound). Compare your code to existing backends and use a graphics debugger such as [RenderDoc](https://renderdoc.org) to debug your rendering states. ##### [Return to Index](#index) @@ -177,8 +175,21 @@ Each draw command needs the triangle rendered using the clipping rectangle provi Rectangles provided by Dear ImGui are defined as `(x1=left,y1=top,x2=right,y2=bottom)` and **NOT** as -`(x1,y1,width,height)` -Refer to rendering backends in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder for references of how to handle the `ClipRect` field. +`(x1,y1,width,height)`. +Refer to rendering backends in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder for references of how to handle the `ClipRect` field. +For example, the [DirectX11 backend](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp) does this: +```cpp +// Project scissor/clipping rectangles into framebuffer space +ImVec2 clip_off = draw_data->DisplayPos; +ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); +ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); +if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + +// Apply scissor/clipping rectangle +const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; +ctx->RSSetScissorRects(1, &r); +``` ##### [Return to Index](#index) @@ -198,10 +209,10 @@ Dear ImGui internally needs to uniquely identify UI elements. Elements that are typically not clickable (such as calls to the Text functions) don't need an ID. Interactive widgets (such as calls to Button buttons) need a unique ID. -**Unique ID are used internally to track active widgets and occasionally associate state to widgets.
-Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.** +**Unique IDs are used internally to track active widgets and occasionally associate state to widgets.
+Unique IDs are implicitly built from the hash of multiple elements that identify the "path" to the UI element.** -Since Dear ImGui 1.85 you can use `Demo>Tools>Stack Tool` or call `ImGui::ShowStackToolWindow()`. The tool display intermediate values leading to the creation of a unique ID, making things easier to debug and understand. +Since Dear ImGui 1.85, you can use `Demo>Tools>ID Stack Tool` or call `ImGui::ShowIDStackToolWindow()`. The tool display intermediate values leading to the creation of a unique ID, making things easier to debug and understand. ![Stack tool](https://user-images.githubusercontent.com/8225057/136235657-a0ea5665-dcd1-423f-9be6-dc3f8ced8f12.png) @@ -240,12 +251,12 @@ Button("OK"); // ERROR: ID collision with the first button! Interacting wit Button(""); // ERROR: ID collision with Begin("MyWindow")! End(); ``` -Fear not! this is easy to solve and there are many ways to solve it! +Fear not! This is easy to solve and there are many ways to solve it! - Solving ID conflict in a simple/local context: -When passing a label you can optionally specify extra ID information within string itself. +When passing a label you can optionally specify extra ID information within the string itself. Use "##" to pass a complement to the ID that won't be visible to the end-user. -This helps solving the simple collision cases when you know e.g. at compilation time which items +This helps solve the simple collision cases when you know e.g. at compilation time which items are going to be created: ```cpp Begin("MyWindow"); @@ -259,8 +270,8 @@ End(); ```cpp Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox! ``` -- Occasionally/rarely you might want change a label while preserving a constant ID. This allows -you to animate labels. For example you may want to include varying information in a window title bar, +- Occasionally/rarely you might want to change a label while preserving a constant ID. This allows +you to animate labels. For example, you may want to include varying information in a window title bar, but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID: ```cpp Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID") @@ -273,9 +284,9 @@ Begin(buf); // Variable title, ID = hash of "MyGame" Use `PushID()` / `PopID()` to create scopes and manipulate the ID stack, as to avoid ID conflicts within the same window. This is the most convenient way of distinguishing ID when iterating and creating many UI elements programmatically. -You can push a pointer, a string or an integer value into the ID stack. -Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack. -At each level of the stack we store the seed used for items at this level of the ID stack. +You can push a pointer, a string, or an integer value into the ID stack. +Remember that IDs are formed from the concatenation of _everything_ pushed into the ID stack. +At each level of the stack, we store the seed used for items at this level of the ID stack. ```cpp Begin("Window"); for (int i = 0; i < 100; i++) @@ -310,7 +321,7 @@ PushID("node"); PopID(); PopID(); ``` -- Tree nodes implicitly creates a scope for you by calling `PushID()`: +- Tree nodes implicitly create a scope for you by calling `PushID()`: ```cpp Button("Click"); // Label = "Click", ID = hash of (..., "Click") if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag) @@ -320,8 +331,8 @@ if (TreeNode("node")) // <-- this function call will do a PushID() for you (unl } ``` -When working with trees, ID are used to preserve the open/close state of each tree node. -Depending on your use cases you may want to use strings, indices or pointers as ID. +When working with trees, IDs are used to preserve the open/close state of each tree node. +Depending on your use cases you may want to use strings, indices, or pointers as ID. - e.g. when following a single pointer that may change over time, using a static string as ID will preserve your node open/closed state when the targeted object change. - e.g. when displaying a list of objects, using indices or pointers as ID will preserve the @@ -342,11 +353,11 @@ Short explanation: **Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.** Long explanation: -- Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices. At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.). +- Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices. At the end of the frame, those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code to render them is generally fairly short (a few dozen lines). In the examples/ folder, we provide functions for popular graphics APIs (OpenGL, DirectX, etc.). - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API. We carry the information to identify a "texture" in the ImTextureID type. -ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice. -Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function. +ImTextureID is nothing more than a void*, aka 4/8 bytes worth of data: just enough to store one pointer or integer of your choice. +Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely passes ImTextureID values until they reach your rendering function. - In the [examples/](https://github.com/ocornut/imgui/tree/master/examples) backends, for each graphics API we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: ```cpp OpenGL: @@ -371,9 +382,9 @@ DirectX12: For example, in the OpenGL example backend we store raw OpenGL texture identifier (GLuint) inside ImTextureID. Whereas in the DirectX11 example backend we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure tying together both the texture and information about its format and how to read it. -- If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them. +- If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better by knowing how your codebase is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them. If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID representation suggested by the example backends is probably the best choice. -(Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer) +(Advanced users may also decide to keep a low-level type in ImTextureID, use ImDrawList callback and pass information to their renderer) User code may do: ```cpp @@ -387,15 +398,15 @@ The renderer function called after ImGui::Render() will receive that same value MyTexture* texture = (MyTexture*)pcmd->GetTexID(); MyEngineBindTexture2D(texture); ``` -Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui. -This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them. -If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using. +Once you understand this design, you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui. +This is by design and is a good thing because it means your code has full control over your data types and how you display them. +If you want to display an image file (e.g. PNG file) on the screen, please refer to documentation and tutorials for the graphics API you are using. Refer to [Image Loading and Displaying Examples](https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples) on the [Wiki](https://github.com/ocornut/imgui/wiki) to find simplified examples for loading textures with OpenGL, DirectX9 and DirectX11. C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa. Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*. -Examples: +Here are some examples: ```cpp GLuint my_tex = XXX; void* my_void_ptr; @@ -413,17 +424,25 @@ Finally, you may call `ImGui::ShowMetricsWindow()` to explore/visualize/understa --- -### Q: How can I use my own math types instead of ImVec2/ImVec4? +### Q: How can I use maths operators with ImVec2? -You can edit [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) and setup the `IM_VEC2_CLASS_EXTRA`/`IM_VEC4_CLASS_EXTRA` macros to add implicit type conversions. -This way you'll be able to use your own types everywhere, e.g. passing `MyVector2` or `glm::vec2` to ImGui functions instead of `ImVec2`. +We do not export maths operators by default in imgui.h in order to not conflict with the use of your own maths types and maths operators. As a convenience, you may use `#define IMGUI_DEFINE_MATH_OPERATORS` + `#include "imgui.h"` to access our basic maths operators. + +##### [Return to Index](#index) + +--- + +### Q: How can I use my own maths types instead of ImVec2/ImVec4? + +You can setup your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file with `IM_VEC2_CLASS_EXTRA`/`IM_VEC4_CLASS_EXTRA` macros to add implicit type conversions to our own maths types. +This way you will be able to use your own types everywhere, e.g. passing `MyVector2` or `glm::vec2` to ImGui functions instead of `ImVec2`. ##### [Return to Index](#index) --- ### Q: How can I interact with standard C++ types (such as std::string and std::vector)? -- Being highly portable (backends/bindings for several languages, frameworks, programming style, obscure or older platforms/compilers), and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases. +- Being highly portable (backends/bindings for several languages, frameworks, programming styles, obscure or older platforms/compilers), and aiming for compatibility & performance suitable for every modern real-time game engine, Dear ImGui does not use any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases. - To use ImGui::InputText() with a std::string or any resizable string class, see [misc/cpp/imgui_stdlib.h](https://github.com/ocornut/imgui/blob/master/misc/cpp/imgui_stdlib.h). - To use combo boxes and list boxes with `std::vector` or any other data structure: the `BeginCombo()/EndCombo()` API lets you iterate and submit items yourself, so does the `ListBoxHeader()/ListBoxFooter()` API. @@ -432,12 +451,12 @@ Prefer using them over the old and awkward `Combo()/ListBox()` api. You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code). - Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application. -Please bear in mind that using `std::string` on applications with large amount of UI may incur unsatisfactory performances. +Please bear in mind that using `std::string` on applications with a large amount of UI may incur unsatisfactory performances. Modern implementations of `std::string` often include small-string optimization (which is often a local buffer) but those are not configurable and not the same across implementations. -- If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount -of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern -is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead. +- If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to an excessive amount +of heap allocations. Consider using literals, statically sized buffers, and your own helper functions. A common pattern +is that you will need to build lots of strings on the fly, and their maximum length can be easily scoped ahead. One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str This is a small helper where you can instance strings with configurable local buffers length. Many game engines will provide similar or better string helpers. @@ -458,12 +477,12 @@ ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImVec2 p = ImGui::GetCursorScreenPos(); // Draw a red circle -draw_list->AddCircleFilled(ImVec2(p.x + 50, p.y + 50), 30.0f, IM_COL32(255, 0, 0, 255), 16); +draw_list->AddCircleFilled(ImVec2(p.x + 50, p.y + 50), 30.0f, IM_COL32(255, 0, 0, 255)); // Draw a 3 pixel thick yellow line draw_list->AddLine(ImVec2(p.x, p.y), ImVec2(p.x + 100.0f, p.y + 100.0f), IM_COL32(255, 255, 0, 255), 3.0f); -// Advance the ImGui cursor to claim space in the window (otherwise the window will appears small and needs to be resized) +// Advance the ImGui cursor to claim space in the window (otherwise the window will appear small and needs to be resized) ImGui::Dummy(ImVec2(200, 200)); ImGui::End(); @@ -472,8 +491,8 @@ ImGui::End(); - Refer to "Demo > Examples > Custom Rendering" in the demo window and read the code of `ShowExampleAppCustomRendering()` in `imgui_demo.cpp` from more examples. - To generate colors: you can use the macro `IM_COL32(255,255,255,255)` to generate them at compile time, or use `ImGui::GetColorU32(IM_COL32(255,255,255,255))` or `ImGui::GetColorU32(ImVec4(1.0f,1.0f,1.0f,1.0f))` to generate a color that is multiplied by the current value of `style.Alpha`. -- Math operators: if you have setup `IM_VEC2_CLASS_EXTRA` in `imconfig.h` to bind your own math types, you can use your own math types and their natural operators instead of ImVec2. ImVec2 by default doesn't export any math operators in the public API. You may use `#define IMGUI_DEFINE_MATH_OPERATORS` `#include "imgui_internal.h"` to use the internally defined math operators, but instead prefer using your own math library and set it up in `imconfig.h`. -- You can use `ImGui::GetBackgroundDrawList()` or `ImGui::GetForegroundDrawList()` to access draw lists which will be displayed behind and over every other dear imgui windows (one bg/fg drawlist per viewport). This is very convenient if you need to quickly display something on the screen that is not associated to a dear imgui window. +- Math operators: if you have setup `IM_VEC2_CLASS_EXTRA` in `imconfig.h` to bind your own math types, you can use your own math types and their natural operators instead of ImVec2. ImVec2 by default doesn't export any math operators in the public API. You may use `#define IMGUI_DEFINE_MATH_OPERATORS` `#include "imgui.h"` to use our math operators, but instead prefer using your own math library and set it up in `imconfig.h`. +- You can use `ImGui::GetBackgroundDrawList()` or `ImGui::GetForegroundDrawList()` to access draw lists which will be displayed behind and over every other Dear ImGui window (one bg/fg drawlist per viewport). This is very convenient if you need to quickly display something on the screen that is not associated with a Dear ImGui window. - You can also create your own empty window and draw inside it. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags (The `ImGuiWindowFlags_NoDecoration` flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse). Then you can retrieve the ImDrawList* via `GetWindowDrawList()` and draw to it in any way you like. - You can create your own ImDrawList instance. You'll need to initialize them with `ImGui::GetDrawListSharedData()`, or create your own instancing `ImDrawListSharedData`, and then call your renderer function with your own ImDrawList or ImDrawData data. - Looking for fun? The [ImDrawList coding party 2020](https://github.com/ocornut/imgui/issues/3606) thread is full of "don't do this at home" extreme uses of the ImDrawList API. @@ -486,7 +505,7 @@ ImGui::End(); ### Q: How should I handle DPI in my application? -The short answer is: obtain the desired DPI scale, load your fonts resized with that scale (always round down fonts size to nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. +The short answer is: obtain the desired DPI scale, load your fonts resized with that scale (always round down fonts size to the nearest integer), and scale your Style structure accordingly using `style.ScaleAllSizes()`. Your application may want to detect DPI change and reload the fonts and reset style between frames. @@ -496,16 +515,24 @@ Down the line Dear ImGui will provide a variety of standardized reference values Applications in the `examples/` folder are not DPI aware partly because they are unable to load a custom font from the file-system (may change that in the future). -The reason DPI is not auto-magically solved in stock examples is that we don't yet have a satisfying solution for the "multi-dpi" problem (using the `docking` branch: when multiple viewport windows are over multiple monitors using different DPI scale). The current way to handle this on the application side is: +The reason DPI is not auto-magically solved in stock examples is that we don't yet have a satisfying solution for the "multi-dpi" problem (using the `docking` branch: when multiple viewport windows are over multiple monitors using different DPI scales). The current way to handle this on the application side is: - Create and maintain one font atlas per active DPI scale (e.g. by iterating `platform_io.Monitors[]` before `NewFrame()`). - Hook `platform_io.OnChangedViewport()` to detect when a `Begin()` call makes a Dear ImGui window change monitor (and therefore DPI). -- In the hook: swap atlas, swap style with correctly sized one, remap the current font from one atlas to the other (may need to maintain a remapping table of your fonts at variying DPI scale). +- In the hook: swap atlas, swap style with correctly sized one, and remap the current font from one atlas to the other (you may need to maintain a remapping table of your fonts at varying DPI scales). -This approach is relatively easy and functional but come with two issues: +This approach is relatively easy and functional but comes with two issues: - It's not possibly to reliably size or position a window ahead of `Begin()` without knowing on which monitor it'll land. - Style override may be lost during the `Begin()` call crossing monitor boundaries. You may need to do some custom scaling mumbo-jumbo if you want your `OnChangedViewport()` handler to preserve style overrides. -Please note that if you are not using multi-viewports with multi-monitors using different DPI scale, you can ignore all of this and use the simpler technique recommended at the top. +Please note that if you are not using multi-viewports with multi-monitors using different DPI scales, you can ignore that and use the simpler technique recommended at the top. + +On Windows, in addition to scaling the font size (make sure to round to an integer) and using `style.ScaleAllSizes()`, you will need to inform Windows that your application is DPI aware. If this is not done, Windows will scale the application window and the UI text will be blurry. Potential solutions to indicate DPI awareness on Windows are: + +- For SDL: the flag `SDL_WINDOW_ALLOW_HIGHDPI` needs to be passed to `SDL_CreateWindow()``. +- For GLFW: this is done automatically. +- For other Windows projects with other backends, or wrapper projects: + - We provide a `ImGui_ImplWin32_EnableDpiAwareness()` helper method in the Win32 backend. + - Use an [application manifest file](https://learn.microsoft.com/en-us/windows/win32/hidpi/setting-the-default-dpi-awareness-for-a-process) to set the `` property. ### Q: How can I load a different font than the default? Use the font atlas to load the TTF/OTF file you want: @@ -527,7 +554,7 @@ backslash \ within a string literal, you need to write it double backslash "\\": ```cpp io.Fonts->AddFontFromFileTTF("MyFolder\MyFont.ttf", size); // WRONG (you are escaping the M here!) -io.Fonts->AddFontFromFileTTF("MyFolder\\MyFont.ttf", size; // CORRECT (Windows only) +io.Fonts->AddFontFromFileTTF("MyFolder\\MyFont.ttf", size); // CORRECT (Windows only) io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT ``` @@ -536,46 +563,17 @@ io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT --- ### Q: How can I easily use icons in my application? -The most convenient and practical way is to merge an icon font such as FontAwesome inside you +The most convenient and practical way is to merge an icon font such as FontAwesome inside your main font. Then you can refer to icons within your strings. -You may want to see `ImFontConfig::GlyphMinAdvanceX` to make your icon look monospace to facilitate alignment. -(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file for more details about icons font loading.) -With some extra effort, you may use colorful icon by registering custom rectangle space inside the font atlas, -and copying your own graphics data into it. See docs/FONTS.md about using the AddCustomRectFontGlyph API. +Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file for more details about icons font loading. ##### [Return to Index](#index) --- ### Q: How can I load multiple fonts? -Use the font atlas to pack them into a single texture: -(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file and the code in ImFontAtlas for more details.) -```cpp -ImGuiIO& io = ImGui::GetIO(); -ImFont* font0 = io.Fonts->AddFontDefault(); -ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); -ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); -io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() -// the first loaded font gets used by default -// use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime - -// Options -ImFontConfig config; -config.OversampleH = 2; -config.OversampleV = 1; -config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up -config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters -io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config); - -// Combine multiple fonts into one (e.g. for icon fonts) -static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; -ImFontConfig config; -config.MergeMode = true; -io.Fonts->AddFontDefault(); -io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font -io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs -``` +Use the font atlas to pack them into a single texture. Read [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) for more details. ##### [Return to Index](#index) @@ -586,7 +584,7 @@ When loading a font, pass custom Unicode ranges to specify the glyphs to load. ```cpp // Add default Japanese ranges -io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); +io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, nullptr, io.Fonts->GetGlyphRangesJapanese()); // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need) ImVector ranges; @@ -595,20 +593,21 @@ builder.AddText("Hello world"); // Add a string (here "He builder.AddChar(0x7262); // Add a specific character builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) -io.Fonts->AddFontFromFileTTF("myfontfile.ttf", 16.0f, NULL, ranges.Data); +io.Fonts->AddFontFromFileTTF("myfontfile.ttf", 16.0f, nullptr, ranges.Data); ``` -All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 -by using the u8"hello" syntax. Specifying literal in your source code using a local code page -(such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work! -Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. +All your strings need to use UTF-8 encoding. +You need to tell your compiler to use UTF-8, or in C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. +Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work! +See [About UTF-8 Encoding](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md#about-utf-8-encoding) section +of [FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) for details about UTF-8 Encoding. Text input: it is up to your application to pass the right character code by calling `io.AddInputCharacter()`. The applications in examples/ are doing that. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). -You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state. -Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for -the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly. +You may also use `MultiByteToWideChar()` or `ToUnicode()` to retrieve Unicode codepoints from MultiByte characters or keyboard state. +Windows: if your language is relying on an Input Method Editor (IME), you can write your HWND to ImGui::GetMainViewport()->PlatformHandleRaw +for the default implementation of io.SetPlatformImeDataFn() to set your Microsoft IME position correctly. ##### [Return to Index](#index) @@ -623,7 +622,7 @@ You may take a look at: - [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) -- [Gallery](https://github.com/ocornut/imgui/issues/4451) +- [Gallery](https://github.com/ocornut/imgui/issues/6897) ##### [Return to Index](#index) @@ -631,11 +630,11 @@ You may take a look at: ### Q: Can you create elaborate/serious tools with Dear ImGui? -Yes. People have written game editors, data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools). The list of sponsors below is also an indicator that serious game teams have been using the library. +Yes. People have written game editors, data browsers, debuggers, profilers, and all sorts of non-trivial tools with the library. In my experience, the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools). The list of sponsors below is also an indicator that serious game teams have been using the library. -Dear ImGui is very programmer centric and the immediate-mode GUI paradigm might require you to readjust some habits before you can realize its full potential. Dear ImGui is about making things that are simple, efficient and powerful. +Dear ImGui is very programmer centric and the immediate-mode GUI paradigm might require you to readjust some habits before you can realize its full potential. Dear ImGui is about making things that are simple, efficient, and powerful. -Dear ImGui is built to be efficient and scalable toward the needs for AAA-quality applications running all day. The IMGUI paradigm offers different opportunities for optimization that the more typical RMGUI paradigm. +Dear ImGui is built to be efficient and scalable toward the needs for AAA-quality applications running all day. The IMGUI paradigm offers different opportunities for optimization than the more typical RMGUI paradigm. ##### [Return to Index](#index) @@ -643,9 +642,9 @@ Dear ImGui is built to be efficient and scalable toward the needs for AAA-qualit ### Q: Can you reskin the look of Dear ImGui? -Somehow. You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as Dear ImGui is designed and optimized to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. Dear ImGui is NOT designed to create user interface for games, although with ingenious use of the low-level API you can do it. +Somewhat. You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, and fonts. However, as Dear ImGui is designed and optimized to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. Dear ImGui is NOT designed to create a user interface for games, although with ingenious use of the low-level API you can do it. -A reasonably skinned application may look like (screenshot from [#2529](https://github.com/ocornut/imgui/issues/2529#issuecomment-524281119)) +A reasonably skinned application may look like (screenshot from [#2529](https://github.com/ocornut/imgui/issues/2529#issuecomment-524281119)): ![minipars](https://user-images.githubusercontent.com/314805/63589441-d9794f00-c5b1-11e9-8d96-cfc1b93702f7.png) ##### [Return to Index](#index) @@ -654,7 +653,7 @@ A reasonably skinned application may look like (screenshot from [#2529](https:// ### Q: Why using C++ (as opposed to C)? -Dear ImGui takes advantage of a few C++ languages features for convenience but nothing anywhere Boost insanity/quagmire. Dear ImGui does NOT require C++11 so it can be used with most old C++ compilers. Dear ImGui doesn't use any C++ header file. Language-wise, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience. +Dear ImGui takes advantage of a few C++ language features for convenience but nothing anywhere Boost insanity/quagmire. Dear ImGui doesn't use any C++ header file. Dear ImGui uses a very small subset of C++11 features. In particular, function overloading and default parameters are used to make the API easier to use and code terser. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors, and templates (in the case of the ImVector<> class) are also relied on as a convenience. There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/cimgui/cimgui) by Sonoro1234 and Stephan Dilly. It is designed for creating bindings to other languages. If possible, I would suggest using your target language functionalities to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. Also see [Bindings](https://github.com/ocornut/imgui/wiki/Bindings) for various third-party bindings. @@ -665,11 +664,11 @@ There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/ci # Q&A: Community ### Q: How can I help? -- Businesses: please reach out to `contact AT dearimgui.com` if you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project. +- Businesses: please reach out to `omar AT dearimgui.com` if you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance, or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people to work on this project. - Individuals: you can support continued maintenance and development via PayPal donations. See [README](https://github.com/ocornut/imgui/blob/master/docs/README.md). -- If you are experienced with Dear ImGui and C++, look at [GitHub Issues](https://github.com/ocornut/imgui/issues), [GitHub Discussions](https://github.com/ocornut/imgui/discussions), the [Wiki](https://github.com/ocornut/imgui/wiki), read [docs/TODO.txt](https://github.com/ocornut/imgui/blob/master/docs/TODO.txt) and see how you want to help and can help! -- Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. -You may post screenshot or links in the [gallery threads](https://github.com/ocornut/imgui/issues/4451). Visuals are ideal as they inspire other programmers. Disclosing your use of Dear ImGui helps the library grow credibility, and help other teams and programmers with taking decisions. +- If you are experienced with Dear ImGui and C++, look at [GitHub Issues](https://github.com/ocornut/imgui/issues), [GitHub Discussions](https://github.com/ocornut/imgui/discussions), the [Wiki](https://github.com/ocornut/imgui/wiki), read [docs/TODO.txt](https://github.com/ocornut/imgui/blob/master/docs/TODO.txt), and see how you want to help and can help! +- Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere, etc. +You may post screenshots or links in the [gallery threads](https://github.com/ocornut/imgui/issues/6897). Visuals are ideal as they inspire other programmers. Disclosing your use of Dear ImGui helps the library grow credibility, and helps other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues or sometimes incomplete PR. ##### [Return to Index](#index) diff --git a/third_party/imgui/docs/FONTS.md b/third_party/imgui/docs/FONTS.md index 09c1cb9a51e..df8b610e563 100644 --- a/third_party/imgui/docs/FONTS.md +++ b/third_party/imgui/docs/FONTS.md @@ -8,49 +8,71 @@ a 13 pixels high, pixel-perfect font used by default. We embed it in the source You may also load external .TTF/.OTF files. In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience. -**Also read the FAQ:** https://www.dearimgui.org/faq (there is a Fonts section!) +**Also read the FAQ:** https://www.dearimgui.com/faq (there is a Fonts section!) ## Index -- [Readme First](#readme-first) +- [Troubleshooting](#troubleshooting) - [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application) -- [Fonts Loading Instructions](#font-loading-instructions) +- [Fonts Loading Instructions](#fonts-loading-instructions) +- [Loading Font Data from Memory](#loading-font-data-from-memory) +- [Loading Font Data Embedded In Source Code](#loading-font-data-embedded-in-source-code) - [Using Icon Fonts](#using-icon-fonts) - [Using FreeType Rasterizer (imgui_freetype)](#using-freetype-rasterizer-imgui_freetype) - [Using Colorful Glyphs/Emojis](#using-colorful-glyphsemojis) - [Using Custom Glyph Ranges](#using-custom-glyph-ranges) - [Using Custom Colorful Icons](#using-custom-colorful-icons) -- [Using Font Data Embedded In Source Code](#using-font-data-embedded-in-source-code) -- [About filenames](#about-filenames) +- [About Filenames](#about-filenames) +- [About UTF-8 Encoding](#about-utf-8-encoding) +- [Debug Tools](#debug-tools) - [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository) - [Font Links](#font-links) --------------------------------------- - ## Readme First -- You can use the `Metrics/Debugger` window (available in `Demo>Tools`) to browse your fonts and understand what's going on if you have an issue. You can also reach it in `Demo->Tools->Style Editor->Fonts`. The same information are also available in the Style Editor under Fonts. +## Troubleshooting -![imgui_capture_0008](https://user-images.githubusercontent.com/8225057/135429892-0e41ef8d-33c5-4991-bcf6-f997a0bcfd6b.png) +**A vast majority of font and text related issues encountered comes from 4 things:** -- All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas. +### (1) Invalid filename due to use of `\` or unexpected working directory. -- Make sure your font ranges data are persistent (available during the calls to `GetTexDataAsAlpha8()`/`GetTexDataAsRGBA32()/`Build()`. +See [About Filenames](#about-filenames). AddFontXXX functions should assert if the filename is incorrect. -- Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.: -```cpp -u8"hello" -u8"ã“ã‚“ã«ã¡ã¯" // this will be encoded as UTF-8 -``` +### (2) Invalid UTF-8 encoding of your non-ASCII strings. + +See [About UTF-8 Encoding](#about-utf-8-encoding). Use the encoding viewer to confirm encoding of string literal in your source code is correct. + +### (3) Missing glyph ranges. + +You need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See [Fonts Loading Instructions](#fonts-loading-instructions). Use [Debug Tools](#debug-tools) confirm loaded fonts and loaded glyph ranges. + +This is a current constraint of Dear ImGui (which we will lift in the future): when loading a font you need to specify which characters glyphs to load. +All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas. This is generally called by the Renderer backend, e.g. `ImGui_ImplDX11_NewFrame()` calls it. **If you use custom glyphs ranges, make sure the array is persistent** and available during the calls to `GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build()`. + +### (4) Font atlas texture fails to upload to GPU. + +This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. **The typical result of failing to upload a texture is if every glyph or everything appears as empty black or white rectangle.** Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. + +Some solutions: +- You may reduce oversampling, e.g. `font_config.OversampleH = 1`, this will half your texture size for a quality loss. + Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample). +- Reduce glyphs ranges by calculating them from source localization data. + You can use the `ImFontGlyphRangesBuilder` for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win! +- Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. +- Set `io.Fonts.TexDesiredWidth` to specify a texture width to reduce maximum texture height (see comment in `ImFontAtlas::Build()` function). ##### [Return to Index](#index) +--------------------------------------- + ## How should I handle DPI in my application? See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application). ##### [Return to Index](#index) +--------------------------------------- -## Font Loading Instructions +## Fonts Loading Instructions **Load default font:** ```cpp @@ -58,14 +80,12 @@ ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontDefault(); ``` - **Load .TTF/.OTF file with:** ```cpp ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ``` -If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully. - +If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read [About filenames](#about-filenames) carefully. **Load multiple fonts:** ```cpp @@ -74,15 +94,15 @@ ImGuiIO& io = ImGui::GetIO(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); ``` + +In your application loop, select which font to use: ```cpp -// In application loop: select font at runtime ImGui::Text("Hello"); // use the default font (which is the first loaded font) ImGui::PushFont(font2); ImGui::Text("Hello with another font"); ImGui::PopFont(); ``` - **For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** ```cpp ImFontConfig config; @@ -92,7 +112,6 @@ config.GlyphExtraSpacing.x = 1.0f; ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); ``` - **Combine multiple fonts into one:** ```cpp // Load a first font @@ -113,22 +132,21 @@ io.Fonts->Build(); ```cpp // Basic Latin, Extended Latin -io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesDefault()); // Default + Selection of 2500 Ideographs used by Simplified Chinese -io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs -io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); +io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesJapanese()); ``` See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges. - **Example loading and using a Japanese font:** ```cpp ImGuiIO& io = ImGui::GetIO(); -io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); +io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); ``` ```cpp ImGui::Text(u8"ã“ã‚“ã«ã¡ã¯ï¼ãƒ†ã‚¹ãƒˆ %d", 123); @@ -143,24 +161,50 @@ ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png)
_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_ -**Font Atlas too large?** +##### [Return to Index](#index) -- If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. The typical result of failing to upload a texture is if every glyphs appears as white rectangles. -- Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. +--------------------------------------- -Some solutions: +## Loading Font Data from Memory + +```cpp +ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, ...); +``` -1. Reduce glyphs ranges by calculating them from source localization data. - You can use the `ImFontGlyphRangesBuilder` for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win! -2. You may reduce oversampling, e.g. `font_config.OversampleH = 2`, this will largely reduce your texture size. - Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable. -3. Set `io.Fonts.TexDesiredWidth` to specify a texture width to minimize texture height (see comment in `ImFontAtlas::Build()` function). -4. Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. -5. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample). -6. To support the extended range of unicode beyond 0xFFFF (e.g. emoticons, dingbats, symbols, shapes, ancient languages, etc...) add `#define IMGUI_USE_WCHAR32`in your `imconfig.h`. +IMPORTANT: `AddFontFromMemoryTTF()` by default transfer ownership of the data buffer to the font atlas, which will attempt to free it on destruction. +This was to avoid an unnecessary copy, and is perhaps not a good API (a future version will redesign it). +If you want to keep ownership of the data and free it yourself, you need to clear the `FontDataOwnedByAtlas` field: + +```cpp +ImFontConfig font_cfg; +font_cfg.FontDataOwnedByAtlas = false; +ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg); +``` + +##### [Return to Index](#index) + +--------------------------------------- + +## Loading Font Data Embedded In Source Code + +- Compile and use [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) to create a compressed C style array that you can embed in source code. +- See the documentation in [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) for instructions on how to use the tool. +- You may find a precompiled version binary_to_compressed_c.exe for Windows inside the demo binaries package (see [README](https://github.com/ocornut/imgui/blob/master/docs/README.md)). +- The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the actual binary will be about 20% bigger. + +Then load the font with: +```cpp +ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); +``` +or +```cpp +ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); +``` ##### [Return to Index](#index) +--------------------------------------- + ## Using Icon Fonts Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. @@ -193,11 +237,19 @@ ImGui::Button(ICON_FA_SEARCH " Search"); ``` See Links below for other icons fonts and related tools. +**Monospace Icons?** + +To make your icon look more monospace and facilitate alignment, you may want to set the ImFontConfig::GlyphMinAdvanceX value when loading an icon font. + +**Screenshot** + Here's an application using icons ("Avoyd", https://www.avoyd.com): ![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg) ##### [Return to Index](#index) +--------------------------------------- + ## Using FreeType Rasterizer (imgui_freetype) - Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. @@ -208,9 +260,11 @@ Here's an application using icons ("Avoyd", https://www.avoyd.com): ##### [Return to Index](#index) +--------------------------------------- + ## Using Colorful Glyphs/Emojis -- Rendering of colored emojis is only supported by imgui_freetype with FreeType 2.10+. +- Rendering of colored emojis is supported by imgui_freetype with FreeType 2.10+. - You will need to load fonts with the `ImGuiFreeTypeBuilderFlags_LoadColor` flag. - Emojis are frequently encoded in upper Unicode layers (character codes >0x10000) and will need dear imgui compiled with `IMGUI_USE_WCHAR32`. - Not all types of color fonts are supported by FreeType at the moment. @@ -230,6 +284,8 @@ io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg, ra ##### [Return to Index](#index) +--------------------------------------- + ## Using Custom Glyph Ranges You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. @@ -241,12 +297,14 @@ builder.AddChar(0x7262); // Add a specific charact builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) -io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); +io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, nullptr, ranges.Data); io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. ``` ##### [Return to Index](#index) +--------------------------------------- + ## Using Custom Colorful Icons As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)** @@ -267,14 +325,14 @@ rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1); io.Fonts->Build(); // Retrieve texture in RGBA format -unsigned char* tex_pixels = NULL; +unsigned char* tex_pixels = nullptr; int tex_width, tex_height; io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) { - int rect_id = rects_ids[rect_n]; - if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) + int rect_id = rect_ids[rect_n]; + if (const ImFontAtlasCustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) { // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!) for (int y = 0; y < rect->Height; y++) @@ -289,46 +347,89 @@ for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) ##### [Return to Index](#index) -## Using Font Data Embedded In Source Code +--------------------------------------- -- Compile and use [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) to create a compressed C style array that you can embed in source code. -- See the documentation in [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) for instruction on how to use the tool. -- You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see [README](https://github.com/ocornut/imgui/blob/master/docs/README.md)). -- The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the actual binary will be about 20% bigger. +## About Filenames -Then load the font with: +**Please note that many new C/C++ users have issues loading their files _because the filename they provide is wrong_ due to incorrect assumption of what is the current directory.** + +Two things to watch for: + +(1) In C/C++ and most programming languages if you want to use a backslash `\` within a string literal, you need to write it double backslash `\\`. At it happens, Windows uses backslashes as a path separator, so be mindful. ```cpp -ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); +io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!! +io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT ``` -or +In some situations, you may also use `/` path separator under Windows. + +(2) Make sure your IDE/debugger settings starts your executable from the right working (current) directory. In Visual Studio you can change your working directory in project `Properties > General > Debugging > Working Directory`. People assume that their execution will start from the root folder of the project, where by default it often starts from the folder where object or executable files are stored. ```cpp -ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); +io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); // Relative filename depends on your Working Directory when running your program! +io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); // Load from the parent folder of your Working Directory ``` - ##### [Return to Index](#index) -## About filenames +--------------------------------------- -**Please note that many new C/C++ users have issues their files _because the filename they provide is wrong_.** +## About UTF-8 Encoding + +**For non-ASCII characters display, a common user issue is not passing correctly UTF-8 encoded strings.** + +(1) We provide a function `ImGui::DebugTextEncoding(const char* text)` which you can call to verify the content of your UTF-8 strings. +This is a convenient way to confirm that your encoding is correct. -Two things to watch for: -- Make sure your IDE/debugger settings starts your executable from the right working directory. In Visual Studio you can change your working directory in project `Properties > General > Debugging > Working Directory`. People assume that their execution will start from the root folder of the project, where by default it oftens start from the folder where object or executable files are stored. ```cpp -// Relative filename depends on your Working Directory when running your program! -io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); +ImGui::SeparatorText("CORRECT"); +ImGui::DebugTextEncoding(u8"ã“ã‚“ã«ã¡ã¯"); -// Load from the parent folder of your Working Directory -io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); +ImGui::SeparatorText("INCORRECT"); +ImGui::DebugTextEncoding("ã“ã‚“ã«ã¡ã¯"); ``` -- In C/C++ and most programming languages if you want to use a backslash `\` within a string literal, you need to write it double backslash `\\`. At it happens, Windows uses backslashes as a path separator, so be mindful. +![UTF-8 Encoding viewer](https://github.com/ocornut/imgui/assets/8225057/61c1696a-9a94-46c5-9627-cf91211111f0) + +You can also find this tool under `Metrics/Debuggers->Tools->UTF-8 Encoding viewer` if you want to paste from clipboard, but this won't validate the UTF-8 encoding done by your compiler. + +(2) To encode in UTF-8: + +There are also compiler-specific ways to enforce UTF-8 encoding by default: + +- Visual Studio compiler: `/utf-8` command-line flag. +- Visual Studio compiler: `#pragma execution_character_set("utf-8")` inside your code. +- Since May 2023 we have changed the Visual Studio projects of all our examples to use `/utf-8` ([see commit](https://github.com/ocornut/imgui/commit/513af1efc9080857bbd10000d98f98f2a0c96803)). + +Or, since C++11, you can use the `u8"my text"` syntax to encode literal strings as UTF-8. e.g.: ```cpp -io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!! -io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT +ImGui::Text(u8"hello"); +ImGui::Text(u8"ã“ã‚“ã«ã¡ã¯"); // this will always be encoded as UTF-8 +ImGui::Text("ã“ã‚“ã«ã¡ã¯"); // the encoding of this is depending on compiler settings/flags and may be incorrect. ``` -In some situations, you may also use `/` path separator under Windows. + +Since C++20, because the C++ committee hate its users, they decided to change the `u8""` syntax to not return `const char*` but a new type `const char8_t*` which doesn't cast to `const char*`. +Because of type usage of `u8""` in C++20 is a little more tedious: +```cpp +ImGui::Text((const char*)u8"ã“ã‚“ã«ã¡ã¯"); +``` +However, you can disable this behavior completely using the compiler option [`/Zc:char8_t-`](https://learn.microsoft.com/en-us/cpp/build/reference/zc-char8-t?view=msvc-170) for MSVC and [`-fno-char8_t`](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1423r3.html) for Clang and GCC. +##### [Return to Index](#index) + +--------------------------------------- + +## Debug Tools + +#### Metrics/Debugger->Fonts +You can use the `Metrics/Debugger` window (available in `Demo>Tools`) to browse your fonts and understand what's going on if you have an issue. You can also reach it in `Demo->Tools->Style Editor->Fonts`. The same information are also available in the Style Editor under Fonts. + +![Fonts debugging](https://user-images.githubusercontent.com/8225057/135429892-0e41ef8d-33c5-4991-bcf6-f997a0bcfd6b.png) + +#### UTF-8 Encoding Viewer** +You can use the `UTF-8 Encoding viewer` in `Metrics/Debugger` to verify the content of your UTF-8 strings. From C/C++ code, you can call `ImGui::DebugTextEncoding("my string");` function to verify that your UTF-8 encoding is correct. + +![UTF-8 Encoding viewer](https://user-images.githubusercontent.com/8225057/166505963-8a0d7899-8ee8-4558-abb2-1ae523dc02f9.png) ##### [Return to Index](#index) +--------------------------------------- + ## Credits/Licenses For Fonts Included In Repository Some fonts files are available in the `misc/fonts/` folder: @@ -381,7 +482,7 @@ Some fonts files are available in the `misc/fonts/` folder: #### MONOSPACE FONTS Pixel Perfect: -- Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net +- Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php - Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font (also include an .inl file to use directly in dear imgui.) Regular: diff --git a/third_party/imgui/docs/README.md b/third_party/imgui/docs/README.md index 3190f7d0a1a..a2be7fde27b 100644 --- a/third_party/imgui/docs/README.md +++ b/third_party/imgui/docs/README.md @@ -1,43 +1,51 @@ Dear ImGui ===== -[![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) [![Static Analysis Status](https://github.com/ocornut/imgui/workflows/static-analysis/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=static-analysis) +
"Give someone state and they'll have a bug one day, but teach them how to represent state in two separate locations that have to be kept in sync and they'll have bugs for a lifetime."
-ryg + +---- + +[![Build Status](https://github.com/ocornut/imgui/workflows/build/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=build) [![Static Analysis Status](https://github.com/ocornut/imgui/workflows/static-analysis/badge.svg)](https://github.com/ocornut/imgui/actions?workflow=static-analysis) [![Tests Status](https://github.com/ocornut/imgui_test_engine/workflows/tests/badge.svg)](https://github.com/ocornut/imgui_test_engine/actions?workflow=tests) (This library is available under a free and permissive license, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out.) -Businesses: support continued development and maintenance via invoiced technical support, maintenance, sponsoring contracts: +Businesses: support continued development and maintenance via invoiced sponsoring/support contracts:
  _E-mail: contact @ dearimgui dot com_ +
Individuals: support continued development and maintenance [here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). Also see [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) page. -Individuals: support continued development and maintenance [here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). - -Also see [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) page. +| [The Pitch](#the-pitch) - [Usage](#usage) - [How it works](#how-it-works) - [Releases & Changelogs](#releases--changelogs) - [Demo](#demo) - [Integration](#integration) | +:----------------------------------------------------------: | +| [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) - [Credits](#credits) - [License](#license) | +| [Wiki](https://github.com/ocornut/imgui/wiki) - [Extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions) - [Languages bindings & frameworks backends](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | ----- +### The Pitch -Dear ImGui is a **bloat-free graphical user interface library for C++**. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies). +Dear ImGui is a **bloat-free graphical user interface library for C++**. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline-enabled application. It is fast, portable, renderer agnostic, and self-contained (no external dependencies). -Dear ImGui is designed to **enable fast iterations** and to **empower programmers** to create **content creation tools and visualization / debug tools** (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and lacks certain features normally found in more high-level libraries. +Dear ImGui is designed to **enable fast iterations** and to **empower programmers** to create **content creation tools and visualization / debug tools** (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal and lacks certain features commonly found in more high-level libraries. -Dear ImGui is particularly suited to integration in games engine (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on consoles platforms where operating system features are non-standard. +Dear ImGui is particularly suited to integration in game engines (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on console platforms where operating system features are non-standard. -| [Usage](#usage) - [How it works](#how-it-works) - [Releases & Changelogs](#releases--changelogs) - [Demo](#demo) - [Integration](#integration) | -:----------------------------------------------------------: | -| [Upcoming changes](#upcoming-changes) - [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - [Sponsors](#sponsors) - [Credits](#credits) - [License](#license) | -| [Wiki](https://github.com/ocornut/imgui/wiki) - [Languages & frameworks backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | + - Minimize state synchronization. + - Minimize UI-related state storage on user side. + - Minimize setup and maintenance. + - Easy to use to create dynamic UI which are the reflection of a dynamic data set. + - Easy to use to create code-driven and data-driven tools. + - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. + - Easy to hack and improve. + - Portable, minimize dependencies, run on target (consoles, phones, etc.). + - Efficient runtime and memory consumption. + - Battle-tested, used by [many major actors in the game industry](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui). ### Usage -**The core of Dear ImGui is self-contained within a few platform-agnostic files** which you can easily compile in your application/engine. They are all the files in the root folder of the repository (imgui*.cpp, imgui*.h). +**The core of Dear ImGui is self-contained within a few platform-agnostic files** which you can easily compile in your application/engine. They are all the files in the root folder of the repository (imgui*.cpp, imgui*.h). **No specific build process is required**. You can add the .cpp files into your existing project. -**No specific build process is required**. You can add the .cpp files to your existing project. +**Backends for a variety of graphics API and rendering platforms** are provided in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder, along with example applications in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui. -You will need a backend to integrate Dear ImGui in your app. The backend passes mouse/keyboard/gamepad inputs and variety of settings to Dear ImGui, and is in charge of rendering the resulting vertices. +See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide and [Integration](#integration) section of this document for more details. -**Backends for a variety of graphics api and rendering platforms** are provided in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder, along with example applications in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder. See the [Integration](#integration) section of this document for details. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui. - -After Dear ImGui is setup in your application, you can use it from \_anywhere\_ in your program loop: - -Code: +After Dear ImGui is set up in your application, you can use it from \_anywhere\_ in your program loop: ```cpp ImGui::Text("Hello, world %d", 123); if (ImGui::Button("Save")) @@ -45,11 +53,9 @@ if (ImGui::Button("Save")) ImGui::InputText("string", buf, IM_ARRAYSIZE(buf)); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ``` -Result: -
![sample code output (dark)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v175/capture_readme_styles_0001.png) ![sample code output (light)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v175/capture_readme_styles_0002.png) -
_(settings: Dark style (left), Light style (right) / Font: Roboto-Medium, 16px)_ +![sample code output (dark, segoeui font, freetype)](https://user-images.githubusercontent.com/8225057/191050833-b7ecf528-bfae-4a9f-ac1b-f3d83437a2f4.png) +![sample code output (light, segoeui font, freetype)](https://user-images.githubusercontent.com/8225057/191050838-8742efd4-504d-4334-a9a2-e756d15bc2ab.png) -Code: ```cpp // Create a window called "My First Tool", with a menu bar. ImGui::Begin("My First Tool", &my_tool_active, ImGuiWindowFlags_MenuBar); @@ -65,12 +71,14 @@ if (ImGui::BeginMenuBar()) ImGui::EndMenuBar(); } -// Edit a color (stored as ~4 floats) +// Edit a color stored as 4 floats ImGui::ColorEdit4("Color", my_color); -// Plot some values -const float my_values[] = { 0.2f, 0.1f, 1.0f, 0.5f, 0.9f, 2.2f }; -ImGui::PlotLines("Frame Times", my_values, IM_ARRAYSIZE(my_values)); +// Generate samples and plot them +float samples[100]; +for (int n = 0; n < 100; n++) + samples[n] = sinf(n * 0.2f + ImGui::GetTime() * 1.5f); +ImGui::PlotLines("Samples", samples, 100); // Display contents in a scrolling region ImGui::TextColored(ImVec4(1,1,0,1), "Important Stuff"); @@ -80,137 +88,108 @@ for (int n = 0; n < 50; n++) ImGui::EndChild(); ImGui::End(); ``` -Result: -
![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v180/code_sample_04_color.gif) +![my_first_tool_v188](https://user-images.githubusercontent.com/8225057/191055698-690a5651-458f-4856-b5a9-e8cc95c543e2.gif) -Dear ImGui allows you to **create elaborate tools** as well as very short-lived ones. On the extreme side of short-livedness: using the Edit&Continue (hot code reload) feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! Dear ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, an entire game making editor/framework, etc. +Dear ImGui allows you to **create elaborate tools** as well as very short-lived ones. On the extreme side of short-livedness: using the Edit&Continue (hot code reload) feature of modern compilers you can add a few widgets to tweak variables while your application is running, and remove the code a minute later! Dear ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, an entire game-making editor/framework, etc. ### How it works -Check out the Wiki's [About the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#about-the-imgui-paradigm) section if you want to understand the core principles behind the IMGUI paradigm. An IMGUI tries to minimize superfluous state duplication, state synchronization and state retention from the user's point of view. It is less error prone (less code and less bugs) than traditional retained-mode interfaces, and lends itself to create dynamic user interfaces. +The IMGUI paradigm through its API tries to minimize superfluous state duplication, state synchronization, and state retention from the user's point of view. It is less error-prone (less code and fewer bugs) than traditional retained-mode interfaces, and lends itself to creating dynamic user interfaces. Check out the Wiki's [About the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#about-the-imgui-paradigm) section for more details. Dear ImGui outputs vertex buffers and command lists that you can easily render in your application. The number of draw calls and state changes required to render them is fairly small. Because Dear ImGui doesn't know or touch graphics state directly, you can call its functions anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate Dear ImGui with your existing codebase. -_A common misunderstanding is to mistake immediate mode gui for immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes as the gui functions are called. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely._ +_A common misunderstanding is to mistake immediate mode GUI for immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes as the GUI functions are called. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely._ ### Releases & Changelogs -See [Releases](https://github.com/ocornut/imgui/releases) page. +See [Releases](https://github.com/ocornut/imgui/releases) page for decorated Changelogs. Reading the changelogs is a good way to keep up to date with the things Dear ImGui has to offer, and maybe will give you ideas of some features that you've been ignoring until now! ### Demo -Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. - -![screenshot demo](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png) +Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing a variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. [Here's how the demo looks](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png). -You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: -- [imgui-demo-binaries-20210331.zip](https://www.dearimgui.org/binaries/imgui-demo-binaries-20210331.zip) (Windows, 1.83 WIP, built 2021/03/31, master branch) or [older demo binaries](https://www.dearimgui.org/binaries). +You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: +- [imgui-demo-binaries-20240105.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20240105.zip) (Windows, 1.90.1 WIP, built 2024/01/05, master) or [older binaries](https://www.dearimgui.com/binaries). -The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.org/faq)). +The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at a different scale and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.com/faq)). ### Integration -On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/backends) backends without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more of the imgui_impl_xxxx files instead of rewriting them: this will be less work for you and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. +See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide for details. -Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading one texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that. If you are an experienced programmer at ease with those concepts, it should take you less than two hours to integrate Dear ImGui in your custom engine. **Make sure to spend time reading the [FAQ](https://www.dearimgui.org/faq), comments, and some of the examples/ application!** +On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/backends) backends without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more imgui_impl_xxxx files instead of rewriting them: this will be less work for you, and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. + +Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles, which is essentially what Backends are doing. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that: setting up a window and using backends. If you follow the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide it should in theory takes you less than an hour to integrate Dear ImGui. **Make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!** Officially maintained backends/bindings (in repository): - Renderers: DirectX9, DirectX10, DirectX11, DirectX12, Metal, OpenGL/ES/ES2, SDL_Renderer, Vulkan, WebGPU. -- Platforms: GLFW, SDL2, Win32, Glut, OSX, Android. +- Platforms: GLFW, SDL2/SDL3, Win32, Glut, OSX, Android. - Frameworks: Allegro5, Emscripten. [Third-party backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) wiki page: -- Languages: C, C# and: Beef, ChaiScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lobster, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... -- Frameworks: AGS/Adventure Game Studio, Amethyst, Blender, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, GLEQ, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, Monogame, NanoRT, nCine, Nim Game Lib, Nintendo 3DS & Switch (homebrew), Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SDL_Renderer, SFML, Sokol, Unity, Unreal Engine 4, vtk, VulkanHpp, VulkanSceneGraph, Win32 GDI, WxWidgets. -- Note that C bindings ([cimgui](https://github.com/cimgui/cimgui)) are auto-generated, you can use its json/lua output to generate bindings for other languages. +- Languages: C, C# and: Beef, ChaiScript, CovScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lobster, Lua, Nim, Odin, Pascal, PureBasic, Python, ReaScript, Ruby, Rust, Swift, Zig... +- Frameworks: AGS/Adventure Game Studio, Amethyst, Blender, bsf, Cinder, Cocos2d-x, Defold, Diligent Engine, Ebiten, Flexium, GML/Game Maker Studio, GLEQ, Godot, GTK3, Irrlicht Engine, JUCE, LÖVE+LUA, Mach Engine, Magnum, Marmalade, Monogame, NanoRT, nCine, Nim Game Lib, Nintendo 3DS/Switch/WiiU (homebrew), Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, raylib, SFML, Sokol, Unity, Unreal Engine 4/5, UWP, vtk, VulkanHpp, VulkanSceneGraph, Win32 GDI, WxWidgets. +- Many bindings are auto-generated (by good old [cimgui](https://github.com/cimgui/cimgui) or newer/experimental [dear_bindings](https://github.com/dearimgui/dear_bindings)), you can use their metadata output to generate bindings for other languages. [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page: -- Text editors, node editors, timeline editors, plotting, software renderers, remote network access, memory editors, gizmos etc. +- Automation/testing, Text editors, node editors, timeline editors, plotting, software renderers, remote network access, memory editors, gizmos, etc. Notable and well supported extensions include [ImPlot](https://github.com/epezent/implot) and [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine). Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. -### Upcoming Changes - -Some of the goals for 2021 are: -- Work on Docking (see [#2109](https://github.com/ocornut/imgui/issues/2109), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch) -- Work on Multi-Viewport / Multiple OS windows. (see [#1542](https://github.com/ocornut/imgui/issues/1542), in public [docking](https://github.com/ocornut/imgui/tree/docking) branch looking for feedback) -- Work on gamepad/keyboard controls. (see [#787](https://github.com/ocornut/imgui/issues/787)) -- Work on automation and testing system, both to test the library and end-user apps. (see [#435](https://github.com/ocornut/imgui/issues/435)) -- Make the examples look better, improve styles, improve font support, make the examples hi-DPI and multi-DPI aware. - ### Gallery -For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/4451)! +Examples projects using Dear ImGui: [Tracy](https://github.com/wolfpld/tracy) (profiler), [ImHex](https://github.com/WerWolv/ImHex) (hex editor/data analysis), [RemedyBG](https://remedybg.itch.io/remedybg) (debugger) and [hundreds of others](https://github.com/ocornut/imgui/wiki/Software-using-Dear-ImGui). -For a list of third-party widgets and extensions, check out the [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page. - -Custom engine -[![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) +For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/6897)! -Custom engine -[![screenshot tool](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/editor_white_preview.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/editor_white.png) +For a list of third-party widgets and extensions, check out the [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page. -[Tracy Profiler](https://github.com/wolfpld/tracy) -![tracy profiler](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v176/tracy_profiler.png) +| | | +|--|--| +| Custom engine [erhe](https://github.com/tksuoran/erhe) (docking branch)
[![erhe](https://user-images.githubusercontent.com/8225057/190203358-6988b846-0686-480e-8663-1311fbd18abd.jpg)](https://user-images.githubusercontent.com/994606/147875067-a848991e-2ad2-4fd3-bf71-4aeb8a547bcf.png) | Custom engine for [Wonder Boy: The Dragon's Trap](http://www.TheDragonsTrap.com) (2017)
[![the dragon's trap](https://user-images.githubusercontent.com/8225057/190203379-57fcb80e-4aec-4fec-959e-17ddd3cd71e5.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) | +| Custom engine (untitled)
[![editor white](https://user-images.githubusercontent.com/8225057/190203393-c5ac9f22-b900-4d1e-bfeb-6027c63e3d92.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/editor_white.png) | Tracy Profiler ([github](https://github.com/wolfpld/tracy))
[![tracy profiler](https://user-images.githubusercontent.com/8225057/190203401-7b595f6e-607c-44d3-97ea-4c2673244dfb.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v176/tracy_profiler.png) | ### Support, Frequently Asked Questions (FAQ) See: [Frequently Asked Questions (FAQ)](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md) where common questions are answered. -See: [Wiki](https://github.com/ocornut/imgui/wiki) for many links, references, articles. +See: [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) and [Wiki](https://github.com/ocornut/imgui/wiki) for many links, references, articles. See: [Articles about the IMGUI paradigm](https://github.com/ocornut/imgui/wiki#about-the-imgui-paradigm) to read/learn about the Immediate Mode GUI paradigm. -Getting started? For first-time users having issues compiling/linking/running or issues loading fonts, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions). +See: [Upcoming Changes](https://github.com/ocornut/imgui/wiki/Upcoming-Changes). + +See: [Dear ImGui Test Engine + Test Suite](https://github.com/ocornut/imgui_test_engine) for Automation & Testing. -For other questions, bug reports, requests, feedback, you may post on [GitHub Issues](https://github.com/ocornut/imgui/issues). Please read and fill the New Issue template carefully. +Getting started? For first-time users having issues compiling/linking/running or issues loading fonts, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions). For ANY other questions, bug reports, requests, feedback, please post on [GitHub Issues](https://github.com/ocornut/imgui/issues). Please read and fill the New Issue template carefully. Private support is available for paying business customers (E-mail: _contact @ dearimgui dot com_). **Which version should I get?** -We occasionally tag [Releases](https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. - -Advanced users may want to use the `docking` branch with [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features. This branch is kept in sync with master regularly. +We occasionally tag [Releases](https://github.com/ocornut/imgui/releases) (with nice releases notes) but it is generally safe and recommended to sync to latest `master` or `docking` branch. The library is fairly stable and regressions tend to be fixed fast when reported. Advanced users may want to use the `docking` branch with [Multi-Viewport](https://github.com/ocornut/imgui/issues/1542) and [Docking](https://github.com/ocornut/imgui/issues/2109) features. This branch is kept in sync with master regularly. **Who uses Dear ImGui?** -See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors), [Software using dear imgui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also see the [Gallery Threads](https://github.com/ocornut/imgui/issues/4451)! +See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors), and [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also, see the [Gallery Threads](https://github.com/ocornut/imgui/issues/6897)! How to help ----------- **How can I help?** -- See [GitHub Forum/issues](https://github.com/ocornut/imgui/issues) and [Github Discussions](https://github.com/ocornut/imgui/discussions). -- You may help with development and submit pull requests! Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance forever. PR should be crafted both in the interest in the end-users and also to ease the maintainer into understanding and accepting it. +- See [GitHub Forum/Issues](https://github.com/ocornut/imgui/issues). +- You may help with development and submit pull requests! Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance forever. PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it. - See [Help wanted](https://github.com/ocornut/imgui/wiki/Help-Wanted) on the [Wiki](https://github.com/ocornut/imgui/wiki/) for some more ideas. -- Have your company financially support this project (please reach by e-mail) - -**How can I help financing further development of Dear ImGui?** - -See [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) page. +- Be a [sponsor](https://github.com/ocornut/imgui/wiki/Sponsors)! Have your company financially support this project via invoiced sponsors/maintenance or by buying a license for [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine) (please reach out: omar AT dearimgui DOT com). Sponsors -------- -Ongoing Dear ImGui development is currently financially supported by users and private sponsors: - -*Platinum-chocolate sponsors* -- [Blizzard](https://careers.blizzard.com/en-us/openings/engineering/all/all/all/1) - -*Double-chocolate sponsors* -- [Ubisoft](https://montreal.ubisoft.com/en/ubisoft-sponsors-user-interface-library-for-c-dear-imgui), [Supercell](https://supercell.com) - -*Chocolate sponsors* -- [Activision](https://careers.activision.com/c/programmingsoftware-engineering-jobs), [Adobe](https://www.adobe.com/products/medium.html), [Aras PranckeviÄius](https://aras-p.info), [Arkane Studios](https://www.arkane-studios.com), [Epic](https://www.unrealengine.com/en-US/megagrants), [Google](https://github.com/google/filament), [Nvidia](https://developer.nvidia.com/nvidia-omniverse), [RAD Game Tools](http://www.radgametools.com/) - -*Salty-caramel sponsors* -- [Framefield](http://framefield.com), [Grinding Gear Games](https://www.grindinggear.com), [Kylotonn](https://www.kylotonn.com), [Next Level Games](https://www.nextlevelgames.com), [O-Net Communications (USA)](http://en.o-netcom.com) - -Please see [detailed list of Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors) for past sponsors. -From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. +Ongoing Dear ImGui development is and has been financially supported by users and private sponsors. +
Please see the **[detailed list of current and past Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors)** for details. +
From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. **THANK YOU to all past and present supporters for helping to keep this project alive and thriving!** @@ -224,16 +203,14 @@ Credits Developed by [Omar Cornut](https://www.miracleworld.net) and every direct or indirect [contributors](https://github.com/ocornut/imgui/graphs/contributors) to the GitHub. The early version of this library was developed with the support of [Media Molecule](https://www.mediamolecule.com) and first used internally on the game [Tearaway](https://tearaway.mediamolecule.com) (PS Vita). -Recurring contributors (2020): Omar Cornut [@ocornut](https://github.com/ocornut), Rokas Kupstys [@rokups](https://github.com/rokups), Ben Carter [@ShironekoBen](https://github.com/ShironekoBen). -A large portion of work on automation systems, regression tests and other features are currently unpublished. +Recurring contributors include Rokas Kupstys [@rokups](https://github.com/rokups) (2020-2022): a good portion of work on automation system and regression tests now available in [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine). -Sponsoring, support contracts and other B2B transactions are hosted and handled by [Lizardcube](https://www.lizardcube.com). +Sponsoring, maintenance/support contracts and other B2B transactions are hosted and handled by [Disco Hello](https://www.discohello.com). Omar: "I first discovered the IMGUI paradigm at [Q-Games](https://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it." -Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license). - -Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). +Embeds [ProggyClean.ttf](https://www.proggyfonts.net) font by Tristan Grimmer (MIT license). +
Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Also thank you to everyone posting feedback, questions and patches on GitHub. diff --git a/third_party/imgui/docs/TODO.txt b/third_party/imgui/docs/TODO.txt index 9d005ed4e60..80f4e307e96 100644 --- a/third_party/imgui/docs/TODO.txt +++ b/third_party/imgui/docs/TODO.txt @@ -1,111 +1,94 @@ dear imgui ISSUES & TODO LIST -Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues/XXXX +Issue numbers (#) refer to GitHub issues listed at https://github.com/ocornut/imgui/issues/XXXX +THIS LIST IS NOT WELL MAINTAINED. MOST OF THE WORK HAPPENS ON GITHUB NOWADAYS. The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point they usually exist on the github issue tracker). It's mostly a bunch of personal notes, probably incomplete. Feel free to query if you have any questions. - - doc/test: add a proper documentation+regression testing system (#435) - - doc/test: checklist app to verify backends/integration of imgui (test inputs, rendering, callback, etc.). + - doc: add a proper documentation system (maybe relying on automation? #435) + - doc: checklist app to verify backends/integration of imgui (test inputs, rendering, callback, etc.). - doc/tips: tips of the day: website? applet in imgui_club? - doc/wiki: work on the wiki https://github.com/ocornut/imgui/wiki - - window: preserve/restore relative focus ordering (persistent or not) (#2304) -> also see docking reference to same #. + - window: preserve/restore relative focus ordering (persistent or not), and e.g. of multiple reappearing windows (#2304) -> also see docking reference to same #. - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis). (#690) - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. - window: begin with *p_open == false could return false. - window: get size/pos helpers given names (see discussion in #249) - - window: a collapsed window can be stuck behind the main menu bar? - window: when window is very small, prioritize resize button over close button. - - window: detect extra End() call that pop the "Debug" window out and assert at End() call site instead of at end of frame. - - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd. - - window: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? + - window: double-clicking on title bar to minimize isn't consistent interaction, perhaps move to single-click on left-most collapse icon? - window: expose contents size. (#1045) - window: using SetWindowPos() inside Begin() and moving the window with the mouse reacts a very ugly glitch. We should just defer the SetWindowPos() call. - window: GetWindowSize() returns (0,0) when not calculated? (#1045) - window: investigate better auto-positioning for new windows. - - window: top most window flag? (#2574) + - window: top most window flag? more z-order contrl? (#2574) - window/size: manually triggered auto-fit (double-click on grip) shouldn't resize window down to viewport size? - window/size: how to allow to e.g. auto-size vertically to fit contents, but be horizontally resizable? Assuming SetNextWindowSize() is modified to treat -1.0f on each axis as "keep as-is" (would be good but might break erroneous code): Problem is UpdateWindowManualResize() and lots of code treat (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) together. - window/opt: freeze window flag: if not focused/hovered, return false, render with previous ImDrawList. and/or reduce refresh rate. -> this may require enforcing that it is illegal to submit contents if Begin returns false. - window/child: background options for child windows, border option (disable rounding). - window/child: allow resizing of child windows (possibly given min/max for each axis?.) - - window/child: the first draw command of a child window could be moved into the current draw command of the parent window (unless child+tooltip?). - - window/child: border could be emitted in parent as well. - window/child: allow SetNextWindowContentSize() to work on child windows. - window/clipping: some form of clipping when DisplaySize (or corresponding viewport) is zero. - - window/tabbing: add a way to signify that a window or docked window requires attention (e.g. blinking title bar). - - window/id_stack: add e.g. window->GetIDFromPath() with support for leading / and ../ (#1390, #331) + - window/tabbing: add a way to signify that a window or docked window requires attention (e.g. blinking title bar, trying to click behind a modal). + - window/id_stack: add e.g. window->GetIDFromPath() with support for leading / and ../ (#1390, #331) -> model from test engine. ! scrolling: exposing horizontal scrolling with Shift+Wheel even when scrollbar is disabled expose lots of issues (#2424, #1463) - scrolling: while holding down a scrollbar, try to keep the same contents visible (at least while not moving mouse) - scrolling: allow immediately effective change of scroll after Begin() if we haven't appended items yet. - scrolling: forward mouse wheel scrolling to parent window when at the edge of scrolling limits? (useful for listbox,tables?) - - scrolling/clipping: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y). (2017-08-20: can't repro) - scrolling/style: shadows on scrollable areas to denote that there is more contents (see e.g. DaVinci Resolve ui) - - drawdata: make it easy to clone (or swap?) a full ImDrawData so user can easily save that data if they use threaded rendering. (e.g. #2646) - ! drawlist: add calctextsize func to facilitate consistent code from user pov (currently need to use ImGui or ImFont alternatives!) - - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. - - drawlist: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). - - drawlist: primitives/helpers to manipulate vertices post submission, so e.g. a quad/rect can be resized to fit later submitted content, _without_ using the ChannelSplit api + - drawdata: make it easy to deep-copy (or swap?) a full ImDrawData so user can easily save that data if they use threaded rendering. (e.g. #2646) + ! drawlist: add CalcTextSize() func to facilitate consistent code from user pov (currently need to use ImGui or ImFont alternatives!) + - drawlist: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). (WIP branch) - drawlist: make it easier to toggle AA per primitive, so we can use e.g. non-AA fill + AA borders more naturally - drawlist: non-AA strokes have gaps between points (#593, #288), glitch especially on RenderCheckmark() and ColorPicker4(). - - drawlist: would be good to be able to deep copy of ImDrawData (we have a deep copy of ImDrawList now). - - drawlist: rendering: provide a way for imgui to output to a single/global vertex buffer, re-order indices only at the end of the frame (ref: https://gist.github.com/floooh/10388a0afbe08fce9e617d8aefa7d302) - drawlist: callback: add an extra void* in ImDrawCallback to allow passing render-local data to the callback (would break API). - drawlist: AddRect vs AddLine position confusing (#2441) - - drawlist: channel splitter should be external helper and not stored in ImDrawList. - - drawlist: Add quadratic bezier curves? (#3127) - drawlist/opt: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. (#1962) - drawlist/opt: AddRect() axis aligned pixel aligned (no-aa) could use 8 triangles instead of 16 and no normal calculation. - drawlist/opt: thick AA line could be doable in same number of triangles as 1.0 AA line by storing gradient+full color in atlas. - - main: find a way to preserve relative orders of multiple reappearing windows (so an app toggling between "modes" e.g. fullscreen vs all tools) won't lose relative ordering. - - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes - - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? + - items: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. (#395) - widgets: clean up widgets internal toward exposing everything and stabilizing imgui_internals.h. - - widgets: add visuals for Disabled/ReadOnly mode and expose publicly (#211) - widgets: add always-allow-overlap mode. This should perhaps be the default? one problem is that highlight after mouse-wheel scrolling gets deferred, makes scrolling more flickery. - widgets: start exposing PushItemFlag() and ImGuiItemFlags - widgets: alignment options in style (e.g. center Selectable, Right-Align within Button, etc.) #1260 - widgets: activate by identifier (trigger button, focus given id) - - widgets: a way to represent "mixed" values, so e.g. all values replaced with *, including check-boxes, colors, etc. with support for multi-components widgets (e.g. SliderFloat3, make only "Y" mixed) (#2644) - - widgets: checkbox: checkbox with custom glyph inside frame. + - widgets: custom glyph/shapes replacements for stock sapes. (also #6090 #2431 #2235 #6517) - widgets: coloredit: keep reporting as active when picker is on? - widgets: group/scalarn functions: expose more per-component information. e.g. store NextItemData.ComponentIdx set by scalarn function, groups can expose them back somehow. - selectable: using (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. - - selectable: generic BeginSelectable()/EndSelectable() mechanism. + - selectable: generic BeginSelectable()/EndSelectable() mechanism. (work out alongside range-select branch) - selectable: a way to visualize partial/mixed selection (e.g. parent tree node has children with mixed selection) - - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. + - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. (WIP branch) - input text: preserve scrolling when unfocused? - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) - input text: expose CursorPos in char filter event (#816) - input text: try usage idiom of using InputText with data only exposed through get/set accessors, without extraneous copy/alloc. (#3009) - - input text: access public fields via a non-callback API e.g. InputTextGetState("xxx") that may return NULL if not active. + - input text: access public fields via a non-callback API e.g. InputTextGetState("xxx") that may return nullptr if not active (available in internals) - input text: flag to disable live update of the user buffer (also applies to float/int text input) (#701) - input text: hover tooltip could show unclamped text - input text: support for INSERT key to toggle overwrite mode. currently disabled because stb_textedit behavior is unsatisfactory on multi-line. (#2863) - input text: option to Tab after an Enter validation. - input text: add ImGuiInputTextFlags_EnterToApply? (off #218) - input text: easier ways to update buffer (from source char*) while owned. preserve some sort of cursor position for multi-line text. - - input text: add flag (e.g. ImGuiInputTextFlags_EscapeClearsBuffer) to clear instead of revert. what to do with focus? (also see #2890) - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725) - input text: display bug when clicking a drag/slider after an input text in a different window has all-selected text (order dependent). actually a very old bug but no one appears to have noticed it. - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. - - input text: decorrelate layout from inputs - e.g. what's the easiest way to implement a nice IP/Mac address input editor? + - input text: decorrelate display layout from inputs with custom template - e.g. what's the easiest way to implement a nice IP/Mac address input editor? - input text: global callback system so user can plug in an expression evaluator easily. (#1691) - input text: force scroll to end or scroll to a given line/contents (so user can implement a log or a search feature) - input text: a way to preview completion (e.g. disabled text completing from the cursor) - input text: a side bar that could e.g. preview where errors are. probably left to the user to draw but we'd need to give them the info there. - input text: a way for the user to provide syntax coloring. - input text: Shift+TAB with ImGuiInputTextFlags_AllowTabInput could eat preceding blanks, up to tab_count. - - input text: facilitate patterns like if (InputText(..., obj.get_string_ref()) { obj.set_string(...); } relying on internally held buffer. - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). - - input text multi-line: support for cut/paste without selection (cut/paste the current line) + - input text multi-line: support for copy/cut without selection (copy/cut current line?) - input text multi-line: line numbers? status bar? (follow up on #200) - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725) - input text multi-line: better horizontal scrolling support (#383, #1224) @@ -113,7 +96,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - input number: optional range min/max for Input*() functions - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) - input number: use mouse wheel to step up/down - - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. - layout: helper or a way to express ImGui::SameLine(ImGui::GetCursorStartPos().x + ImGui::CalcItemWidth() + ImGui::GetStyle().ItemInnerSpacing.x); in a simpler manner. - layout, font: horizontal tab support, A) text mode: forward only tabs (e.g. every 4 characters/N pixels from pos x1), B) manual mode: explicit tab stops acting as mini columns, no clipping (for menu items, many kind of uses, also vaguely relate to #267, #395) @@ -126,21 +108,17 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - layout: (R&D) local multi-pass layout mode. - layout: (R&D) bind authored layout data (created by an off-line tool), items fetch their pos/size at submission, self-optimize data structures to stable linear access. + - tables: see https://github.com/ocornut/imgui/issues/2957#issuecomment-569726095 + - group: BeginGroup() needs a border option. (~#1496) - - group: IsHovered() after EndGroup() covers whole aabb rather than the intersection of individual items. Is that desirable? + - group: IsItemHovered() after EndGroup() covers whole AABB rather than the intersection of individual items. Is that desirable? - group: merge deactivation/activation within same group (fwd WasEdited flag). (#2550) !- color: the color conversion helpers/types are a mess and needs sorting out. - color: (api breaking) ImGui::ColorConvertXXX functions should be loose ImColorConvertXX to match imgui_internals.h - - plot: full featured plot/graph api w/ scrolling, zooming etc. all bell & whistle. why not! - - plot: PlotLines() should use the polygon-stroke facilities, less vertices (currently issues with averaging normals) - - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) - - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) - - plot: option/feature: draw the zero line - - plot: option/feature: draw grid, vertical markers - - plot: option/feature: draw unit - - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) + - plot: full featured plot/graph api w/ scrolling, zooming etc. --> ImPlot + - (plot: deleted all other todo lines on 2023-06-28) - clipper: ability to disable the clipping through a simple flag/bool. - clipper: ability to run without knowing full count in advance. @@ -148,28 +126,19 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - separator: expose flags (#759) - separator: take indent into consideration (optional) - - separator: width, thickness, centering (#1643) + - separator: width, thickness, centering (#1643, #2657) - splitter: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - - dock: merge docking branch (#2109) - - dock: dock out from a collapsing header? would work nicely but need emitting window to keep submitting the code. + - docking: merge docking branch (#2109) - - tabs: "there is currently a problem because TabItem() will try to submit their own tooltip after 0.50 second, and this will have the effect of making your tooltip flicker once." -> tooltip priority work - - tabs: close button tends to overlap unsaved-document star - - tabs: consider showing the star at the same spot as the close button, like VS Code does. + - tabs: "there is currently a problem because TabItem() will try to submit their own tooltip after 0.50 second, and this will have the effect of making your tooltip flicker once." -> tooltip priority work (WIP branch) - tabs: make EndTabBar fail if users doesn't respect BeginTabBar return value, for consistency/future-proofing. - tabs: persistent order/focus in BeginTabBar() api (#261, #351) - - tabs: TabItem could honor SetNextItemWidth()? - tabs: explicit api (even if internal) to cleanly manipulate tab order. - - tabs: Mouse wheel over tab bar could scroll? (#2702) - image/image button: misalignment on padded/bordered button? - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? - - image button: not taking an explicit id can be problematic. (#2464, #1390) - - button: provide a button that looks framed. (?) - - slider/drag: ctrl+click when format doesn't include a % character.. disable? display underlying value in default format? (see TempInputTextScalar) - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). (#1946) - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) - slider: relative dragging? + precision dragging @@ -181,16 +150,13 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - drag float: power != 0.0f with current value being outside the range keeps the value stuck. - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) - - combo: use clipper: make it easier to disable clipper with a single flag. - - combo: flag for BeginCombo to not return true when unchanged (#1182) - - combo: a way/helper to customize the combo preview (#1658) -> exeperimental BeginComboPreview() + - combo: use clipper. + - combo: a way/helper to customize the combo preview (#1658) -> experimental BeginComboPreview() - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203) - - listbox: multiple selection. + - listbox: multiple selection (WIP range-select branch) - listbox: unselect option (#1208) - - listbox: make it easier/more natural to implement range-select (need some sort of info/ref about the last clicked/focused item that user can translate to an index?) (wip stash) + - listbox: make it easier/more natural to implement range-select (need some sort of info/ref about the last clicked/focused item that user can translate to an index?) (WIP range-select branch) - listbox: user may want to initial scroll to focus on the one selected value? - - listbox: expose hovered item for a simplified ListBox api - - listbox: keyboard navigation. - listbox: disable capturing mouse wheel if the listbox has no scrolling. (#1681) - listbox: scrolling should track modified selection. - listbox: future api should allow to enable horizontal scrolling (#2510) @@ -202,23 +168,18 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - popups: clicking outside (to close popup) and holding shouldn't drag window below. - popups: add variant using global identifier similar to Begin/End (#402) - popups: border options. richer api like BeginChild() perhaps? (#197) - - popups: flags could be reworked to allow both mouse buttons as index (0..5 and as flags using higher-bit) allowing to or them. - popups/modals: although it is sometimes convenient that popups/modals lifetime is owned by imgui, we could also a bool-owned-by-user api as long as Begin() return value testing is enforced. - tooltip: drag and drop with tooltip near monitor edges lose/changes its last direction instead of locking one. The drag and drop tooltip should always follow without changing direction. - tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. - - tooltip: tooltips with delay timers? or general timer policy? (instantaneous vs timed): IsItemHovered() with timer + implicit aabb-id for items with no ID. (#1485) - - tooltip: drag tooltip hovering over source widget with IsItemHovered/SetTooltip flickers. + - tooltip: drag tooltip hovering over source widget with IsItemHovered/SetTooltip flickers (WIP branch) - - menus: menu bars inside modal windows are acting weird. - - status-bar: add a per-window status bar helper similar to what menu-bar does. + - status-bar: add a per-window status bar helper similar to what menu-bar does. generalize concept of layer0 rect in window (can make _MenuBar window flag obsolete too). - shortcuts: local-style shortcut api, e.g. parse "&Save" - shortcuts,menus: global-style shortcut api e.g. "Save (CTRL+S)" -> explicit flag for recursing into closed menu - shortcuts: programmatically access shortcuts "Focus("&Save")) - - menus: hovering a disabled BeginMenu or MenuItem won't close another menu - menus: menu-bar: main menu-bar could affect clamping of windows position (~ akin to modifying DisplayMin) - menus: hovering from menu to menu on a menu-bar has 1 frame without any menu, which is a little annoying. ideally either 0 either longer. - - menus: could merge draw call in most cases (how about storing an optional aabb in ImDrawCmd to move the burden of merging in a single spot). - menus: would be nice if the Selectable() supported horizontal alignment (must be given the equivalent of WorkRect.Max.x matching the position of the shortcut column) - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? @@ -226,7 +187,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) - tree node: tweak color scheme to distinguish headers from selected tree node (#581) - tree node: leaf/non-leaf highlight mismatch. - - tree node: flag to disable formatting and/or detect "%s" - tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height? format only %s/%c to be able to count height?) - settings: write more decent code to allow saving/loading new fields: columns, selected tree nodes? @@ -253,20 +213,17 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. - - log: obsolete LogButtons() all together. - - log: LogButtons() options for specifying depth and/or hiding depth slider + - log: obsolete LogButtons().... (was: LogButtons() options for specifying depth and/or hiding depth slider) - - filters: set a current filter that tree node can automatically query to hide themselves + - filters: set a current filter that certains items (e.g. tree node) can automatically query to hide themselves - filters: handle wild-cards (with implicit leading/trailing *), reg-exprs - filters: fuzzy matches (may use code at blog.forrestthewoods.com/4cffeed33fdb) - - drag and drop: fix/support/options for overlapping drag sources. - drag and drop: focus drag target window on hold (even without open) - drag and drop: releasing a drop shows the "..." tooltip for one frame - since e13e598 (#1725) - drag and drop: drag source on a group object (would need e.g. an invisible button covering group in EndGroup) https://twitter.com/paniq/status/1121446364909535233 - drag and drop: have some way to know when a drag begin from BeginDragDropSource() pov. (see 2018/01/11 post in #143) - drag and drop: allow preview tooltip to be submitted from a different place than the drag source. (#1725) - - drag and drop: allow using with other mouse buttons (where activeid won't be set). (#1637) - drag and drop: make it easier and provide a demo to have tooltip both are source and target site, with a more detailed one on target site (tooltip ordering problem) - drag and drop: demo with reordering nodes (in a list, or a tree node). (#143) - drag and drop: test integrating with os drag and drop (make it easy to do a naive WM_DROPFILE integration) @@ -275,13 +232,10 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - drag and drop: (#143) "both an in-process pointer and a promise to generate a serialized version, for whether the drag ends inside or outside the same process" - drag and drop: feedback when hovering a region blocked by modal (mouse cursor "NO"?) - - node/graph editors (#306) (also see https://github.com/ocornut/imgui/wiki#node-editors) - - pie menus patterns (#434) - - markup: simple markup language for color change? (#902) + - markup: simple markup language for color change? (#902, #3130) - text: selectable text (for copy) as a generic feature (ItemFlags?) - text: proper alignment options in imgui_internal.h - - text: it's currently impossible to have a window title with "##". perhaps an official workaround would be nice. \ style inhibitor? non-visible ascii code to insert between #? - text: provided a framed text helper, e.g. https://pastebin.com/1Laxy8bT - text: refactor TextUnformatted (or underlying function) to more explicitly request if we need width measurement or not - text/layout/tabs: \t pulling position from base pos + step, or offset array (e.g. could be used in text edit, menus for simple icon+text alignment, etc.) @@ -317,17 +271,14 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - font: add support for kerning, probably optional. A) perhaps default to (32..128)^2 matrix ~ 9K entries = 36KB, then hash for non-ascii?. B) or sparse lookup into per-char list? - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) - font: fix AddRemapChar() to work before atlas has been built. - - font: support for unicode codepoints higher than 0xFFFF? (pr #2815) - font: (api breaking) remove "TTF" from symbol names. also because it now supports OTF. - font/opt: Considering storing standalone AdvanceX table as 16-bit fixed point integer? - - font/opt: Glyph currently 40 bytes (2+9*4). Consider storing UV as 16 bits integer? (->32 bytes). X0/Y0/X1/Y1 as 16 fixed-point integers? Or X0/Y0 as float and X1/Y1 as fixed8_8? + - font/opt: Glyph currently 40 bytes (2+9*4). Consider storing UV as 16-bits integer? (->32 bytes). X0/Y0/X1/Y1 as 16 fixed-point integers? Or X0/Y0 as float and X1/Y1 as fixed8_8? - - nav: some features such as PageUp/Down/Home/End should probably work without ImGuiConfigFlags_NavEnableKeyboard? (where do we draw the line?) - - nav: configuration flag to disable global shortcuts (currently only CTRL-Tab) ? + - nav: visual feedback on button press. + - nav: some features such as PageUp/Down/Home/End should probably work without ImGuiConfigFlags_NavEnableKeyboard? (where do we draw the line? how about CTRL+Tab) ! nav: never clear NavId on some setup (e.g. gamepad centric) - - nav: scroll up/down if possible when move request fails - nav: there's currently no way to completely clear focus with the keyboard. depending on patterns used by the application to dispatch inputs, it may be desirable. - - nav: code to focus child-window on restoring NavId appears to have issue: e.g. when focus change is implicit because of window closure. - nav: Home/End behavior when navigable item is not fully visible at the edge of scrolling? should be backtrack to keep item into view? - nav: NavScrollToBringItemIntoView() with item bigger than view should focus top-right? Repro: using Nav in "About Window" - nav: wrap around logic to allow e.g. grid based layout (pressing NavRight on the right-most element would go to the next row, etc.). see internal's NavMoveRequestTryWrapping(). @@ -339,22 +290,19 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - nav: NavFlattened: ESC on a flattened child should select something. - nav: NavFlattened: broken: in typical usage scenario, the items of a fully clipped child are currently not considered to enter into a NavFlattened child. - nav: NavFlattened: cannot access menu-bar of a flattened child window with Alt/menu key (not a very common use case..). - - nav: simulate right-click or context activation? (SHIFT+F10) + - nav: simulate right-click or context activation? (SHIFT+F10, keyboard Menu key?) - nav/popup: esc/enter default behavior for popups, e.g. be able to mark an "ok" or "cancel" button that would get triggered by those keys, default validation button, etc. - nav/treenode: left within a tree node block as a fallback (ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default?) - nav/menus: pressing left-right on a vertically clipped menu bar tends to jump to the collapse/close buttons. - nav/menus: allow pressing Menu to leave a sub-menu. - nav/menus: a way to access the main menu bar with Alt? (currently needs CTRL+TAB) or last focused window menu bar? - nav/menus: when using the main menu bar, even though we restore focus after, the underlying window loses its title bar highlight during menu manipulation. could we prevent it? - - nav/menus: main menu bar currently cannot restore a NULL focus. Could save NavWindow at the time of being focused, similarly to what popup do? + - nav/menus: main menu bar currently cannot restore a nullptr focus. Could save NavWindow at the time of being focused, similarly to what popup do? - nav/menus: Alt,Up could open the first menu (e.g. "File") currently it tends to nav into the window/collapse menu. Do do that we would need custom transition? - - nav/windowing: configure fade-in/fade-out delay on Ctrl+Tab? - - nav/windowing: when CTRL-Tab/windowing is active, the HoveredWindow detection doesn't take account of the window display re-ordering. + - nav/windowing: when CTRL+Tab/windowing is active, the HoveredWindow detection doesn't take account of the window display re-ordering. - nav/windowing: Resizing window will currently fail with certain types of resizing constraints/callback applied - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) - - inputs: we need an explicit flag about whether the imgui window is focused, to be able to distinguish focused key releases vs alt-tabbing all release behaviors. - - inputs: rework IO system to be able to pass actual ordered/timestamped events. use an event queue? (~#335, #71) - inputs: support track pad style scrolling & slider edit. - inputs/io: backspace and arrows in the context of a text input could use system repeat rate. - inputs/io: clarify/standardize/expose repeat rate and repeat delays (#1808) @@ -367,12 +315,9 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - misc: make the ImGuiCond values linear (non-power-of-two). internal storage for ImGuiWindow can use integers to combine into flags (Why?) - misc: PushItemFlag(): add a flag to disable keyboard capture when used with mouse? (#1682) - misc: use more size_t in public api? - - misc: possible compile-time support for string view/range instead of char* would e.g. facilitate usage with Rust (#683) + - misc: possible compile-time support for string view/range instead of char* would e.g. facilitate usage with Rust (#683, #3038, WIP string_view branch) - misc: possible compile-time support for wchar_t instead of char*? - - remote: make a system like RemoteImGui first-class citizen/project (#75) - - - demo: find a way to demonstrate textures in the examples application, as it such a common issue for new users. - demo: demonstrate using PushStyleVar() in more details. - demo: add vertical separator demo - demo: add virtual scrolling example? @@ -382,23 +327,20 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i - examples: window minimize, maximize (#583) - examples: provide a zero frame-rate/idle example. - examples: dx11/dx12: try to use new swapchain blit models (#2970) - - backends: move to backends/ folder? - backends: report it better when not able to create texture? - - backends: apple: example_apple should be using modern GL3. - backends: glfw: could go idle when minimized? if (glfwGetWindowAttrib(window, GLFW_ICONIFIED)) { glfwWaitEvents(); continue; } // issue: DeltaTime will be super high on resume, perhaps provide a way to let impl know (#440) - backends: opengl: rename imgui_impl_opengl2 to impl_opengl_legacy and imgui_impl_opengl3 to imgui_impl_opengl? (#1900) - backends: opengl: could use a single vertex buffer and glBufferSubData for uploads? - backends: opengl: explicitly disable GL_STENCIL_TEST in bindings. - backends: vulkan: viewport: support for synchronized swapping of multiple swap chains. - backends: bgfx: https://gist.github.com/RichardGale/6e2b74bc42b3005e08397236e4be0fd0 - - backends: mscriptem: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) + - backends: emscriptem: with refactored examples, we could provide a direct imgui_impl_emscripten platform layer (see eg. https://github.com/floooh/sokol-samples/blob/master/html5/imgui-emsc.cc#L42) - - bindings: ways to use clang ast dump to generate bindings or helpers for bindings? (e.g. clang++ -Xclang -ast-dump=json imgui.h) + - bindings: ways to use clang ast dump to generate bindings or helpers for bindings? (e.g. clang++ -Xclang -ast-dump=json imgui.h) (WIP project "dear-bindings" still private) - - optimization: replace vsnprintf with stb_printf? using IMGUI_USE_STB_SPRINTF.(#1038) + - optimization: replace vsnprintf with stb_printf? using IMGUI_USE_STB_SPRINTF. (#1038 + needed for string_view) - optimization: add clipping for multi-component widgets (SliderFloatX, ColorEditX, etc.). one problem is that nav branch can't easily clip parent group when there is a move request. - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) - optimization: fully covered window (covered by another with non-translucent bg + WindowRounding worth of padding) may want to clip rendering. - optimization: use another hash function than crc32, e.g. FNV1a - - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? - optimization: turn some the various stack vectors into statically-sized arrays diff --git a/third_party/imgui/examples/example_allegro5/README.md b/third_party/imgui/examples/example_allegro5/README.md index d6d812eabd3..4af31f6f3a2 100644 --- a/third_party/imgui/examples/example_allegro5/README.md +++ b/third_party/imgui/examples/example_allegro5/README.md @@ -12,7 +12,7 @@ Note that the backend supports _BOTH_ 16-bit and 32-bit indices, but 32-bit indi ### On Ubuntu 14.04+ and macOS ```bash -g++ -DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" -I .. -I ../.. main.cpp ../../backends/imgui_impl_allegro5.cpp ../../imgui*.cpp -lallegro -lallegro_main -lallegro_primitives -o allegro5_example +g++ -DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" -I .. -I ../.. -I ../../backends main.cpp ../../backends/imgui_impl_allegro5.cpp ../../imgui*.cpp -lallegro -lallegro_main -lallegro_primitives -o allegro5_example ``` On macOS, install Allegro with homebrew: `brew install allegro`. @@ -32,5 +32,5 @@ vcpkg integrate install ; register include / libs in Visual Studio Build: ``` set ALLEGRODIR=path_to_your_allegro5_folder -cl /Zi /MD /I %ALLEGRODIR%\include /DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" /I .. /I ..\.. main.cpp ..\..\backends\imgui_impl_allegro5.cpp ..\..\imgui*.cpp /link /LIBPATH:%ALLEGRODIR%\lib allegro-5.0.10-monolith-md.lib user32.lib +cl /Zi /MD /utf-8 /I %ALLEGRODIR%\include /DIMGUI_USER_CONFIG=\"examples/example_allegro5/imconfig_allegro5.h\" /I .. /I ..\.. /I ..\..\backends main.cpp ..\..\backends\imgui_impl_allegro5.cpp ..\..\imgui*.cpp /link /LIBPATH:%ALLEGRODIR%\lib allegro-5.0.10-monolith-md.lib user32.lib ``` diff --git a/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj b/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj index 69b0ece3081..02f6a474123 100644 --- a/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj +++ b/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj @@ -91,6 +91,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -105,6 +106,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -122,6 +124,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -142,6 +145,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -171,10 +175,11 @@ + - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj.filters b/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj.filters index 7fea78b3ca6..84881d37158 100644 --- a/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj.filters +++ b/third_party/imgui/examples/example_allegro5/example_allegro5.vcxproj.filters @@ -52,7 +52,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_allegro5/main.cpp b/third_party/imgui/examples/example_allegro5/main.cpp index 4fd379a393b..3ca061cc697 100644 --- a/third_party/imgui/examples/example_allegro5/main.cpp +++ b/third_party/imgui/examples/example_allegro5/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for Allegro 5 -// 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 + +// 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 // On Windows, you can install Allegro5 using vcpkg: // git clone https://github.com/Microsoft/vcpkg @@ -35,11 +39,11 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplAllegro5_Init(display); @@ -47,17 +51,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); bool show_demo_window = true; bool show_another_window = false; @@ -69,8 +74,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. ALLEGRO_EVENT ev; while (al_get_next_event(queue, &ev)) @@ -94,7 +99,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -113,7 +118,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } diff --git a/third_party/imgui/examples/example_android_opengl3/android/app/build.gradle b/third_party/imgui/examples/example_android_opengl3/android/app/build.gradle index aa7f0eadd69..53181baa215 100644 --- a/third_party/imgui/examples/example_android_opengl3/android/app/build.gradle +++ b/third_party/imgui/examples/example_android_opengl3/android/app/build.gradle @@ -2,13 +2,15 @@ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' android { - compileSdkVersion 29 - buildToolsVersion "30.0.3" - ndkVersion "21.4.7075529" + compileSdkVersion 33 + buildToolsVersion "33.0.2" + ndkVersion "25.2.9519653" + defaultConfig { applicationId "imgui.example.android" - minSdkVersion 23 - targetSdkVersion 29 + namespace "imgui.example.android" + minSdkVersion 24 + targetSdkVersion 33 versionCode 1 versionName "1.0" } @@ -20,9 +22,19 @@ android { } } + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget="11" + } + externalNativeBuild { cmake { path "../../CMakeLists.txt" + version '3.22.1' } } } diff --git a/third_party/imgui/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml b/third_party/imgui/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml index c4009e5291f..a87b95b4f8f 100644 --- a/third_party/imgui/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml +++ b/third_party/imgui/examples/example_android_opengl3/android/app/src/main/AndroidManifest.xml @@ -1,6 +1,5 @@ - + + android:configChanges="orientation|keyboardHidden|screenSize" + android:exported="false"> diff --git a/third_party/imgui/examples/example_android_opengl3/android/build.gradle b/third_party/imgui/examples/example_android_opengl3/android/build.gradle index 59f9c78e4dc..ccd218524cb 100644 --- a/third_party/imgui/examples/example_android_opengl3/android/build.gradle +++ b/third_party/imgui/examples/example_android_opengl3/android/build.gradle @@ -1,12 +1,12 @@ buildscript { - ext.kotlin_version = '1.4.31' + ext.kotlin_version = '1.8.0' repositories { google() mavenCentral() } dependencies { - classpath 'com.android.tools.build:gradle:4.1.0' + classpath 'com.android.tools.build:gradle:7.4.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } diff --git a/third_party/imgui/examples/example_android_opengl3/main.cpp b/third_party/imgui/examples/example_android_opengl3/main.cpp index 5ab6903489b..2316ce6ddb2 100644 --- a/third_party/imgui/examples/example_android_opengl3/main.cpp +++ b/third_party/imgui/examples/example_android_opengl3/main.cpp @@ -1,5 +1,10 @@ // dear imgui: standalone example application for Android + OpenGL ES 3 -// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" #include "imgui_impl_android.h" @@ -9,21 +14,84 @@ #include #include #include +#include // Data static EGLDisplay g_EglDisplay = EGL_NO_DISPLAY; static EGLSurface g_EglSurface = EGL_NO_SURFACE; static EGLContext g_EglContext = EGL_NO_CONTEXT; -static struct android_app* g_App = NULL; +static struct android_app* g_App = nullptr; static bool g_Initialized = false; static char g_LogTag[] = "ImGuiExample"; +static std::string g_IniFilename = ""; // Forward declarations of helper functions +static void Init(struct android_app* app); +static void Shutdown(); +static void MainLoopStep(); static int ShowSoftKeyboardInput(); static int PollUnicodeChars(); static int GetAssetData(const char* filename, void** out_data); -void init(struct android_app* app) +// Main code +static void handleAppCmd(struct android_app* app, int32_t appCmd) +{ + switch (appCmd) + { + case APP_CMD_SAVE_STATE: + break; + case APP_CMD_INIT_WINDOW: + Init(app); + break; + case APP_CMD_TERM_WINDOW: + Shutdown(); + break; + case APP_CMD_GAINED_FOCUS: + case APP_CMD_LOST_FOCUS: + break; + } +} + +static int32_t handleInputEvent(struct android_app* app, AInputEvent* inputEvent) +{ + return ImGui_ImplAndroid_HandleInputEvent(inputEvent); +} + +void android_main(struct android_app* app) +{ + app->onAppCmd = handleAppCmd; + app->onInputEvent = handleInputEvent; + + while (true) + { + int out_events; + struct android_poll_source* out_data; + + // Poll all events. If the app is not visible, this loop blocks until g_Initialized == true. + while (ALooper_pollAll(g_Initialized ? 0 : -1, nullptr, &out_events, (void**)&out_data) >= 0) + { + // Process one event + if (out_data != nullptr) + out_data->process(app, out_data); + + // Exit the app by returning from within the infinite loop + if (app->destroyRequested != 0) + { + // shutdown() should have been called already while processing the + // app command APP_CMD_TERM_WINDOW. But we play save here + if (!g_Initialized) + Shutdown(); + + return; + } + } + + // Initiate a new frame + MainLoopStep(); + } +} + +void Init(struct android_app* app) { if (g_Initialized) return; @@ -61,7 +129,7 @@ void init(struct android_app* app) if (g_EglContext == EGL_NO_CONTEXT) __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglCreateContext() returned EGL_NO_CONTEXT"); - g_EglSurface = eglCreateWindowSurface(g_EglDisplay, egl_config, g_App->window, NULL); + g_EglSurface = eglCreateWindowSurface(g_EglDisplay, egl_config, g_App->window, nullptr); eglMakeCurrent(g_EglDisplay, g_EglSurface, g_EglSurface, g_EglContext); } @@ -70,13 +138,14 @@ void init(struct android_app* app) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); - // Disable loading/saving of .ini file from disk. - // FIXME: Consider using LoadIniSettingsFromMemory() / SaveIniSettingsToMemory() to save in appropriate location for Android. - io.IniFilename = NULL; + // Redirect loading/saving of .ini file to our location. + // Make sure 'g_IniFilename' persists while we use Dear ImGui. + g_IniFilename = std::string(app->activity->internalDataPath) + "/imgui.ini"; + io.IniFilename = g_IniFilename.c_str();; // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplAndroid_Init(g_App->window); @@ -84,7 +153,7 @@ void init(struct android_app* app) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! @@ -99,21 +168,21 @@ void init(struct android_app* app) //void* font_data; //int font_data_size; //ImFont* font; + //font_data_size = GetAssetData("segoeui.ttf", &font_data); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); + //IM_ASSERT(font != nullptr); + //font_data_size = GetAssetData("DroidSans.ttf", &font_data); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); + //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("Roboto-Medium.ttf", &font_data); //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); - //IM_ASSERT(font != NULL); + //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("Cousine-Regular.ttf", &font_data); //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 15.0f); - //IM_ASSERT(font != NULL); - //font_data_size = GetAssetData("DroidSans.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); - //IM_ASSERT(font != NULL); - //font_data_size = GetAssetData("ProggyTiny.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 10.0f); - //IM_ASSERT(font != NULL); + //IM_ASSERT(font != nullptr); //font_data_size = GetAssetData("ArialUni.ttf", &font_data); - //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Arbitrary scale-up // FIXME: Put some effort into DPI awareness @@ -122,13 +191,14 @@ void init(struct android_app* app) g_Initialized = true; } -void tick() +void MainLoopStep() { ImGuiIO& io = ImGui::GetIO(); if (g_EglDisplay == EGL_NO_DISPLAY) return; // Our state + // (we use static, which essentially makes the variable globals, as a convenience to keep the example code easy to follow) static bool show_demo_window = true; static bool show_another_window = false; static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); @@ -152,7 +222,7 @@ void tick() if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -171,7 +241,7 @@ void tick() ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -194,7 +264,7 @@ void tick() eglSwapBuffers(g_EglDisplay, g_EglSurface); } -void shutdown() +void Shutdown() { if (!g_Initialized) return; @@ -225,85 +295,29 @@ void shutdown() g_Initialized = false; } -static void handleAppCmd(struct android_app* app, int32_t appCmd) -{ - switch (appCmd) - { - case APP_CMD_SAVE_STATE: - break; - case APP_CMD_INIT_WINDOW: - init(app); - break; - case APP_CMD_TERM_WINDOW: - shutdown(); - break; - case APP_CMD_GAINED_FOCUS: - break; - case APP_CMD_LOST_FOCUS: - break; - } -} - -static int32_t handleInputEvent(struct android_app* app, AInputEvent* inputEvent) -{ - return ImGui_ImplAndroid_HandleInputEvent(inputEvent); -} - -void android_main(struct android_app* app) -{ - app->onAppCmd = handleAppCmd; - app->onInputEvent = handleInputEvent; - - while (true) - { - int out_events; - struct android_poll_source* out_data; - - // Poll all events. If the app is not visible, this loop blocks until g_Initialized == true. - while (ALooper_pollAll(g_Initialized ? 0 : -1, NULL, &out_events, (void**)&out_data) >= 0) - { - // Process one event - if (out_data != NULL) - out_data->process(app, out_data); - - // Exit the app by returning from within the infinite loop - if (app->destroyRequested != 0) - { - // shutdown() should have been called already while processing the - // app command APP_CMD_TERM_WINDOW. But we play save here - if (!g_Initialized) - shutdown(); - - return; - } - } - - // Initiate a new frame - tick(); - } -} +// Helper functions // Unfortunately, there is no way to show the on-screen input from native code. // Therefore, we call ShowSoftKeyboardInput() of the main activity implemented in MainActivity.kt via JNI. static int ShowSoftKeyboardInput() { JavaVM* java_vm = g_App->activity->vm; - JNIEnv* java_env = NULL; + JNIEnv* java_env = nullptr; jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6); if (jni_return == JNI_ERR) return -1; - jni_return = java_vm->AttachCurrentThread(&java_env, NULL); + jni_return = java_vm->AttachCurrentThread(&java_env, nullptr); if (jni_return != JNI_OK) return -2; jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz); - if (native_activity_clazz == NULL) + if (native_activity_clazz == nullptr) return -3; jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "showSoftInput", "()V"); - if (method_id == NULL) + if (method_id == nullptr) return -4; java_env->CallVoidMethod(g_App->activity->clazz, method_id); @@ -321,22 +335,22 @@ static int ShowSoftKeyboardInput() static int PollUnicodeChars() { JavaVM* java_vm = g_App->activity->vm; - JNIEnv* java_env = NULL; + JNIEnv* java_env = nullptr; jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6); if (jni_return == JNI_ERR) return -1; - jni_return = java_vm->AttachCurrentThread(&java_env, NULL); + jni_return = java_vm->AttachCurrentThread(&java_env, nullptr); if (jni_return != JNI_OK) return -2; jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz); - if (native_activity_clazz == NULL) + if (native_activity_clazz == nullptr) return -3; jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "pollUnicodeChar", "()I"); - if (method_id == NULL) + if (method_id == nullptr) return -4; // Send the actual characters to Dear ImGui diff --git a/third_party/imgui/examples/example_apple_metal/README.md b/third_party/imgui/examples/example_apple_metal/README.md index c13df2f1c05..48a2b570294 100644 --- a/third_party/imgui/examples/example_apple_metal/README.md +++ b/third_party/imgui/examples/example_apple_metal/README.md @@ -4,7 +4,7 @@ This example shows how to integrate Dear ImGui with Metal. It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. -Consider basing your work off the example_glfw_metal/ or example_sdl_metal/ examples. They are better supported and will be portable unlike this one. +Consider basing your work off the example_glfw_metal/ or example_sdl2_metal/ examples. They are better supported and will be portable unlike this one. diff --git a/third_party/imgui/examples/example_apple_metal/main.mm b/third_party/imgui/examples/example_apple_metal/main.mm index bbe51d31f29..109ef6153c3 100644 --- a/third_party/imgui/examples/example_apple_metal/main.mm +++ b/third_party/imgui/examples/example_apple_metal/main.mm @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for OSX + Metal. -// 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 + +// 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 #import @@ -17,7 +21,7 @@ #include "imgui_impl_metal.h" #if TARGET_OS_OSX #include "imgui_impl_osx.h" -@interface AppViewController : NSViewController +@interface AppViewController : NSViewController @end #else @interface AppViewController : UIViewController @@ -54,12 +58,12 @@ -(instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullabl IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Renderer backend ImGui_ImplMetal_Init(_device); @@ -67,17 +71,18 @@ -(instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullabl // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); return self; } @@ -100,27 +105,8 @@ -(void)viewDidLoad self.mtkView.delegate = self; #if TARGET_OS_OSX - // Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view - NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect - options:NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways - owner:self - userInfo:nil]; - [self.view addTrackingArea:trackingArea]; - - // If we want to receive key events, we either need to be in the responder chain of the key view, - // or else we can install a local monitor. The consequence of this heavy-handed approach is that - // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our - // window, we'd want to be much more careful than just ingesting the complete event stream. - // To match the behavior of other backends, we pass every event down to the OS. - NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged; - [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) - { - ImGui_ImplOSX_HandleEvent(event, self.view); - return event; - }]; - ImGui_ImplOSX_Init(self.view); - + [NSApp activateIgnoringOtherApps:YES]; #endif } @@ -137,8 +123,6 @@ -(void)drawInMTKView:(MTKView*)view #endif io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale); - io.DeltaTime = 1 / float(view.preferredFramesPerSecond ?: 60); - id commandBuffer = [self.commandQueue commandBuffer]; MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor; @@ -164,7 +148,7 @@ -(void)drawInMTKView:(MTKView*)view if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -183,7 +167,7 @@ -(void)drawInMTKView:(MTKView*)view ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -223,21 +207,18 @@ -(void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size #if TARGET_OS_OSX -// Forward Mouse/Keyboard events to Dear ImGui OSX backend. -// Other events are registered via addLocalMonitorForEventsMatchingMask() --(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } --(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); } +- (void)viewWillAppear +{ + [super viewWillAppear]; + self.view.window.delegate = self; +} + +- (void)windowWillClose:(NSNotification *)notification +{ + ImGui_ImplMetal_Shutdown(); + ImGui_ImplOSX_Shutdown(); + ImGui::DestroyContext(); +} #else @@ -251,7 +232,8 @@ -(void)updateIOWithTouchEvent:(UIEvent *)event UITouch *anyTouch = event.allTouches.anyObject; CGPoint touchLocation = [anyTouch locationInView:self.view]; ImGuiIO &io = ImGui::GetIO(); - io.MousePos = ImVec2(touchLocation.x, touchLocation.y); + io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen); + io.AddMousePosEvent(touchLocation.x, touchLocation.y); BOOL hasActiveTouch = NO; for (UITouch *touch in event.allTouches) @@ -262,7 +244,7 @@ -(void)updateIOWithTouchEvent:(UIEvent *)event break; } } - io.MouseDown[0] = hasActiveTouch; + io.AddMouseButtonEvent(0, hasActiveTouch); } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; } @@ -301,9 +283,8 @@ -(instancetype)init backing:NSBackingStoreBuffered defer:NO]; self.window.contentViewController = rootViewController; - [self.window orderFront:self]; [self.window center]; - [self.window becomeKeyWindow]; + [self.window makeKeyAndOrderFront:self]; } return self; } diff --git a/third_party/imgui/examples/example_apple_opengl2/main.mm b/third_party/imgui/examples/example_apple_opengl2/main.mm index f859162e5d8..815c0f72e14 100644 --- a/third_party/imgui/examples/example_apple_opengl2/main.mm +++ b/third_party/imgui/examples/example_apple_opengl2/main.mm @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline -// 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 + +// 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 #import #import @@ -36,26 +40,17 @@ -(void)prepareOpenGL -(void)initialize { - // Some events do not raise callbacks of AppView in some circumstances (for example when CMD key is held down). - // This monitor taps into global event stream and captures these events. - NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged; - [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) - { - ImGui_ImplOSX_HandleEvent(event, self); - return event; - }]; - // Setup Dear ImGui context // FIXME: This example doesn't have proper cleanup... IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplOSX_Init(self); @@ -64,22 +59,24 @@ -(void)initialize // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); } -(void)updateAndDrawDemoView { // Start the Dear ImGui frame + ImGuiIO& io = ImGui::GetIO(); ImGui_ImplOpenGL2_NewFrame(); ImGui_ImplOSX_NewFrame(self); ImGui::NewFrame(); @@ -93,7 +90,7 @@ -(void)updateAndDrawDemoView if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -112,7 +109,7 @@ -(void)updateAndDrawDemoView ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -151,26 +148,6 @@ -(void)drawRect:(NSRect)bounds { [self updateAndDrawDemoView]; } -(void)animationTimerFired:(NSTimer*)timer { [self setNeedsDisplay:YES]; } -(void)dealloc { animationTimer = nil; } -//----------------------------------------------------------------------------------- -// Input processing -//----------------------------------------------------------------------------------- - -// Forward Mouse/Keyboard events to Dear ImGui OSX backend. -// Other events are registered via addLocalMonitorForEventsMatchingMask() --(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } --(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } - @end //----------------------------------------------------------------------------------- diff --git a/third_party/imgui/examples/example_emscripten_opengl3/README.md b/third_party/imgui/examples/example_emscripten_opengl3/README.md deleted file mode 100644 index e2b19e44bd0..00000000000 --- a/third_party/imgui/examples/example_emscripten_opengl3/README.md +++ /dev/null @@ -1,26 +0,0 @@ -## How to Build - -- You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions - -- Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools. - -- You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. - -- Then build using `make` while in the `example_emscripten_opengl3/` directory. - -## How to Run - -To run on a local machine: -- `make serve` will use Python3 to spawn a local webserver, you can then browse http://localhost:8000 to access your build. -- Otherwise, generally you will need a local webserver: - - Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
-_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ - - Emscripten SDK has a handy `emrun` command: `emrun web/example_emscripten_opengl3.html --browser firefox` which will spawn a temporary local webserver (in Firefox). See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. - - You may use Python 3 builtin webserver: `python -m http.server -d web` (this is what `make serve` uses). - - You may use Python 2 builtin webserver: `cd web && python -m SimpleHTTPServer`. - - If you are accessing the files over a network, certain browsers, such as Firefox, will restrict Gamepad API access to secure contexts only (e.g. https only). - -## Obsolete features: - -- Emscripten 2.0 (August 2020) obsoleted the fastcomp backend, only llvm is supported. -- Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile: `#EMS += -s BINARYEN_TRAP_MODE=clamp` diff --git a/third_party/imgui/examples/example_emscripten_opengl3/main.cpp b/third_party/imgui/examples/example_emscripten_opengl3/main.cpp deleted file mode 100644 index be338a8316b..00000000000 --- a/third_party/imgui/examples/example_emscripten_opengl3/main.cpp +++ /dev/null @@ -1,174 +0,0 @@ -// Dear ImGui: standalone example application for Emscripten, using SDL2 + OpenGL3 -// (Emscripten is a C++-to-javascript compiler, used to publish executables for the web. See https://emscripten.org/) -// 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 - -// This is mostly the same code as the SDL2 + OpenGL3 example, simply with the modifications needed to run on Emscripten. -// It is possible to combine both code into a single source file that will compile properly on Desktop and using Emscripten. -// See https://github.com/ocornut/imgui/pull/2492 as an example on how to do just that. - -#include "imgui.h" -#include "imgui_impl_sdl.h" -#include "imgui_impl_opengl3.h" -#include -#include -#include -#include - -// Emscripten requires to have full control over the main loop. We're going to store our SDL book-keeping variables globally. -// Having a single function that acts as a loop prevents us to store state in the stack of said function. So we need some location for this. -SDL_Window* g_Window = NULL; -SDL_GLContext g_GLContext = NULL; - -// For clarity, our main loop code is declared at the end. -static void main_loop(void*); - -int main(int, char**) -{ - // Setup SDL - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) - { - printf("Error: %s\n", SDL_GetError()); - return -1; - } - - // For the browser using Emscripten, we are going to use WebGL1 with GL ES2. See the Makefile. for requirement details. - // It is very likely the generated file won't work in many browsers. Firefox is the only sure bet, but I have successfully - // run this code on Chrome for Android for example. - const char* glsl_version = "#version 100"; - //const char* glsl_version = "#version 300 es"; - SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); - SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); - - // Create window with graphics context - SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); - SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); - SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); - SDL_DisplayMode current; - SDL_GetCurrentDisplayMode(0, ¤t); - SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - g_Window = SDL_CreateWindow("Dear ImGui Emscripten example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); - g_GLContext = SDL_GL_CreateContext(g_Window); - if (!g_GLContext) - { - fprintf(stderr, "Failed to initialize WebGL context!\n"); - return 1; - } - SDL_GL_SetSwapInterval(1); // Enable vsync - - // Setup Dear ImGui context - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - - // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. - // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. - io.IniFilename = NULL; - - // Setup Dear ImGui style - ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); - - // Setup Platform/Renderer backends - ImGui_ImplSDL2_InitForOpenGL(g_Window, g_GLContext); - ImGui_ImplOpenGL3_Init(glsl_version); - - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.md' for more instructions and details. - // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details. - //io.Fonts->AddFontDefault(); -#ifndef IMGUI_DISABLE_FILE_FUNCTIONS - io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); -#endif - - // This function call won't return, and will engage in an infinite loop, processing events from the browser, and dispatching them. - emscripten_set_main_loop_arg(main_loop, NULL, 0, true); -} - -static void main_loop(void* arg) -{ - ImGuiIO& io = ImGui::GetIO(); - IM_UNUSED(arg); // We can pass this argument as the second parameter of emscripten_set_main_loop_arg(), but we don't use that. - - // Our state (make them static = more or less global) as a convenience to keep the example terse. - static bool show_demo_window = true; - static bool show_another_window = false; - static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); - - // Poll and handle events (inputs, window resize, etc.) - // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. - // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. - // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. - // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. - SDL_Event event; - while (SDL_PollEvent(&event)) - { - ImGui_ImplSDL2_ProcessEvent(&event); - // Capture events here, based on io.WantCaptureMouse and io.WantCaptureKeyboard - } - - // Start the Dear ImGui frame - ImGui_ImplOpenGL3_NewFrame(); - ImGui_ImplSDL2_NewFrame(); - ImGui::NewFrame(); - - // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). - if (show_demo_window) - ImGui::ShowDemoWindow(&show_demo_window); - - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. - { - static float f = 0.0f; - static int counter = 0; - - ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. - - ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) - ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state - ImGui::Checkbox("Another Window", &show_another_window); - - ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color - - if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) - counter++; - ImGui::SameLine(); - ImGui::Text("counter = %d", counter); - - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); - ImGui::End(); - } - - // 3. Show another simple window. - if (show_another_window) - { - ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) - ImGui::Text("Hello from another window!"); - if (ImGui::Button("Close Me")) - show_another_window = false; - ImGui::End(); - } - - // Rendering - ImGui::Render(); - SDL_GL_MakeCurrent(g_Window, g_GLContext); - glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); - glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w); - glClear(GL_COLOR_BUFFER_BIT); - ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - SDL_GL_SwapWindow(g_Window); -} diff --git a/third_party/imgui/examples/example_emscripten_wgpu/Makefile b/third_party/imgui/examples/example_emscripten_wgpu/Makefile.emscripten similarity index 100% rename from third_party/imgui/examples/example_emscripten_wgpu/Makefile rename to third_party/imgui/examples/example_emscripten_wgpu/Makefile.emscripten diff --git a/third_party/imgui/examples/example_emscripten_wgpu/README.md b/third_party/imgui/examples/example_emscripten_wgpu/README.md index c4c4dec76fa..e60025da260 100644 --- a/third_party/imgui/examples/example_emscripten_wgpu/README.md +++ b/third_party/imgui/examples/example_emscripten_wgpu/README.md @@ -6,7 +6,7 @@ - You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. -- Then build using `make` while in the `example_emscripten_wgpu/` directory. +- Then build using `make -f Makefile.emscripten` while in the `example_emscripten_wgpu/` directory. - Requires recent Emscripten as WGPU is still a work-in-progress API. diff --git a/third_party/imgui/examples/example_emscripten_wgpu/main.cpp b/third_party/imgui/examples/example_emscripten_wgpu/main.cpp index d11d906c8a9..910da083396 100644 --- a/third_party/imgui/examples/example_emscripten_wgpu/main.cpp +++ b/third_party/imgui/examples/example_emscripten_wgpu/main.cpp @@ -1,56 +1,77 @@ // Dear ImGui: standalone example application for Emscripten, using GLFW + WebGPU // (Emscripten is a C++-to-javascript compiler, used to publish executables for the web. See https://emscripten.org/) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_wgpu.h" #include +#ifdef __EMSCRIPTEN__ #include #include #include +#endif #include #include #include -// Global WebGPU required states -static WGPUDevice wgpu_device = NULL; -static WGPUSurface wgpu_surface = NULL; -static WGPUSwapChain wgpu_swap_chain = NULL; -static int wgpu_swap_chain_width = 0; -static int wgpu_swap_chain_height = 0; +// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. +#ifdef __EMSCRIPTEN__ +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif -// States tracked across render frames -static bool show_demo_window = true; -static bool show_another_window = false; -static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); +// Global WebGPU required states +static WGPUDevice wgpu_device = nullptr; +static WGPUSurface wgpu_surface = nullptr; +static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm; +static WGPUSwapChain wgpu_swap_chain = nullptr; +static int wgpu_swap_chain_width = 0; +static int wgpu_swap_chain_height = 0; // Forward declarations -static bool init_wgpu(); -static void main_loop(void* window); -static void print_glfw_error(int error, const char* description); -static void print_wgpu_error(WGPUErrorType error_type, const char* message, void*); +static bool InitWGPU(); +static void CreateSwapChain(int width, int height); + +static void glfw_error_callback(int error, const char* description) +{ + printf("GLFW Error %d: %s\n", error, description); +} + +static void wgpu_error_callback(WGPUErrorType error_type, const char* message, void*) +{ + const char* error_type_lbl = ""; + switch (error_type) + { + case WGPUErrorType_Validation: error_type_lbl = "Validation"; break; + case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break; + case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break; + case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break; + default: error_type_lbl = "Unknown"; + } + printf("%s error: %s\n", error_type_lbl, message); +} +// Main code int main(int, char**) { - glfwSetErrorCallback(print_glfw_error); + glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return 1; // Make sure GLFW does not initialize any graphics context. - // This needs to be done explicitly later + // This needs to be done explicitly later. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+WebGPU example", NULL, NULL); - if (!window) - { - glfwTerminate(); + GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+WebGPU example", nullptr, nullptr); + if (window == nullptr) return 1; - } // Initialize the WebGPU environment - if (!init_wgpu()) + if (!InitWGPU()) { if (window) glfwDestroyWindow(window); @@ -63,54 +84,167 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls - - // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. - // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. - io.IniFilename = NULL; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOther(window, true); - ImGui_ImplWGPU_Init(wgpu_device, 3, WGPUTextureFormat_RGBA8Unorm); +#ifdef __EMSCRIPTEN__ + ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas"); +#endif + ImGui_ImplWGPU_InitInfo init_info; + init_info.Device = wgpu_device; + init_info.NumFramesInFlight = 3; + init_info.RenderTargetFormat = wgpu_preferred_fmt; + init_info.DepthStencilFormat = WGPUTextureFormat_Undefined; + ImGui_ImplWGPU_Init(&init_info); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details. //io.Fonts->AddFontDefault(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS - io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf", 18.0f); + io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); #endif - // This function will directly return and exit the main function. - // Make sure that no required objects get cleaned up. - // This way we can use the browsers 'requestAnimationFrame' to control the rendering. - emscripten_set_main_loop_arg(main_loop, window, 0, false); + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop +#ifdef __EMSCRIPTEN__ + // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. + // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. + io.IniFilename = nullptr; + EMSCRIPTEN_MAINLOOP_BEGIN +#else + while (!glfwWindowShouldClose(window)) +#endif + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + glfwPollEvents(); + + // React to changes in screen size + int width, height; + glfwGetFramebufferSize((GLFWwindow*)window, &width, &height); + if (width != wgpu_swap_chain_width && height != wgpu_swap_chain_height) + { + ImGui_ImplWGPU_InvalidateDeviceObjects(); + CreateSwapChain(width, height); + ImGui_ImplWGPU_CreateDeviceObjects(); + } + + // Start the Dear ImGui frame + ImGui_ImplWGPU_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + + WGPURenderPassColorAttachment color_attachments = {}; + color_attachments.loadOp = WGPULoadOp_Clear; + color_attachments.storeOp = WGPUStoreOp_Store; + color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; + color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain); + + WGPURenderPassDescriptor render_pass_desc = {}; + render_pass_desc.colorAttachmentCount = 1; + render_pass_desc.colorAttachments = &color_attachments; + render_pass_desc.depthStencilAttachment = nullptr; + + WGPUCommandEncoderDescriptor enc_desc = {}; + WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc); + + WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc); + ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass); + wgpuRenderPassEncoderEnd(pass); + + WGPUCommandBufferDescriptor cmd_buffer_desc = {}; + WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc); + WGPUQueue queue = wgpuDeviceGetQueue(wgpu_device); + wgpuQueueSubmit(queue, 1, &cmd_buffer); + } +#ifdef __EMSCRIPTEN__ + EMSCRIPTEN_MAINLOOP_END; +#endif + + // Cleanup + ImGui_ImplWGPU_Shutdown(); + ImGui_ImplGlfw_Shutdown(); + ImGui::DestroyContext(); + + glfwDestroyWindow(window); + glfwTerminate(); return 0; } -static bool init_wgpu() +static bool InitWGPU() { wgpu_device = emscripten_webgpu_get_device(); if (!wgpu_device) return false; - wgpuDeviceSetUncapturedErrorCallback(wgpu_device, print_wgpu_error, NULL); + wgpuDeviceSetUncapturedErrorCallback(wgpu_device, wgpu_error_callback, nullptr); // Use C++ wrapper due to misbehavior in Emscripten. // Some offset computation for wgpuInstanceCreateSurface in JavaScript @@ -121,125 +255,26 @@ static bool init_wgpu() wgpu::SurfaceDescriptor surface_desc = {}; surface_desc.nextInChain = &html_surface_desc; - // Use 'null' instance - wgpu::Instance instance = {}; - wgpu_surface = instance.CreateSurface(&surface_desc).Release(); + wgpu::Instance instance = wgpuCreateInstance(nullptr); + wgpu::Surface surface = instance.CreateSurface(&surface_desc); + wgpu::Adapter adapter = {}; + wgpu_preferred_fmt = (WGPUTextureFormat)surface.GetPreferredFormat(adapter); + wgpu_surface = surface.MoveToCHandle(); return true; } -static void main_loop(void* window) +static void CreateSwapChain(int width, int height) { - glfwPollEvents(); - - int width, height; - glfwGetFramebufferSize((GLFWwindow*) window, &width, &height); - - // React to changes in screen size - if (width != wgpu_swap_chain_width && height != wgpu_swap_chain_height) - { - ImGui_ImplWGPU_InvalidateDeviceObjects(); - - if (wgpu_swap_chain) - wgpuSwapChainRelease(wgpu_swap_chain); - - wgpu_swap_chain_width = width; - wgpu_swap_chain_height = height; - - WGPUSwapChainDescriptor swap_chain_desc = {}; - swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment; - swap_chain_desc.format = WGPUTextureFormat_RGBA8Unorm; - swap_chain_desc.width = width; - swap_chain_desc.height = height; - swap_chain_desc.presentMode = WGPUPresentMode_Fifo; - wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc); - - ImGui_ImplWGPU_CreateDeviceObjects(); - } - - // Start the Dear ImGui frame - ImGui_ImplWGPU_NewFrame(); - ImGui_ImplGlfw_NewFrame(); - ImGui::NewFrame(); - - // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). - if (show_demo_window) - ImGui::ShowDemoWindow(&show_demo_window); - - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. - { - static float f = 0.0f; - static int counter = 0; - - ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. - - ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) - ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state - ImGui::Checkbox("Another Window", &show_another_window); - - ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f - ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color - - if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) - counter++; - ImGui::SameLine(); - ImGui::Text("counter = %d", counter); - - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); - ImGui::End(); - } - - // 3. Show another simple window. - if (show_another_window) - { - ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) - ImGui::Text("Hello from another window!"); - if (ImGui::Button("Close Me")) - show_another_window = false; - ImGui::End(); - } - - // Rendering - ImGui::Render(); - - WGPURenderPassColorAttachment color_attachments = {}; - color_attachments.loadOp = WGPULoadOp_Clear; - color_attachments.storeOp = WGPUStoreOp_Store; - color_attachments.clearColor = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; - color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain); - WGPURenderPassDescriptor render_pass_desc = {}; - render_pass_desc.colorAttachmentCount = 1; - render_pass_desc.colorAttachments = &color_attachments; - render_pass_desc.depthStencilAttachment = NULL; - - WGPUCommandEncoderDescriptor enc_desc = {}; - WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc); - - WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc); - ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass); - wgpuRenderPassEncoderEndPass(pass); - - WGPUCommandBufferDescriptor cmd_buffer_desc = {}; - WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc); - WGPUQueue queue = wgpuDeviceGetQueue(wgpu_device); - wgpuQueueSubmit(queue, 1, &cmd_buffer); -} - -static void print_glfw_error(int error, const char* description) -{ - printf("Glfw Error %d: %s\n", error, description); -} - -static void print_wgpu_error(WGPUErrorType error_type, const char* message, void*) -{ - const char* error_type_lbl = ""; - switch (error_type) - { - case WGPUErrorType_Validation: error_type_lbl = "Validation"; break; - case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break; - case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break; - case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break; - default: error_type_lbl = "Unknown"; - } - printf("%s error: %s\n", error_type_lbl, message); + if (wgpu_swap_chain) + wgpuSwapChainRelease(wgpu_swap_chain); + wgpu_swap_chain_width = width; + wgpu_swap_chain_height = height; + WGPUSwapChainDescriptor swap_chain_desc = {}; + swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment; + swap_chain_desc.format = wgpu_preferred_fmt; + swap_chain_desc.width = width; + swap_chain_desc.height = height; + swap_chain_desc.presentMode = WGPUPresentMode_Fifo; + wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc); } diff --git a/third_party/imgui/examples/example_glfw_metal/Makefile b/third_party/imgui/examples/example_glfw_metal/Makefile index a174bc8f290..32a7aeca239 100644 --- a/third_party/imgui/examples/example_glfw_metal/Makefile +++ b/third_party/imgui/examples/example_glfw_metal/Makefile @@ -14,10 +14,10 @@ SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore -LIBS += -L/usr/local/lib -L/opt/homebrew/lib +LIBS += -L/usr/local/lib -L/opt/homebrew/lib -L/opt/local/lib LIBS += -lglfw -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include -I/opt/homebrew/include +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include -I/opt/homebrew/include -I/opt/local/include CXXFLAGS += -Wall -Wformat CFLAGS = $(CXXFLAGS) diff --git a/third_party/imgui/examples/example_glfw_metal/main.mm b/third_party/imgui/examples/example_glfw_metal/main.mm index 2776ba2e735..e9bc63acb1c 100644 --- a/third_party/imgui/examples/example_glfw_metal/main.mm +++ b/third_party/imgui/examples/example_glfw_metal/main.mm @@ -1,7 +1,11 @@ // Dear ImGui: standalone example application for GLFW + Metal, using programmable pipeline // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" #include "imgui_impl_glfw.h" @@ -27,27 +31,28 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Setup window glfwSetErrorCallback(glfw_error_callback); @@ -56,8 +61,8 @@ int main(int, char**) // Create window with graphics context glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Metal example", NULL, NULL); - if (window == NULL) + GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Metal example", nullptr, nullptr); + if (window == nullptr) return 1; id device = MTLCreateSystemDefaultDevice(); @@ -88,8 +93,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); @@ -115,7 +120,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -134,7 +139,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } diff --git a/third_party/imgui/examples/example_glfw_opengl2/Makefile b/third_party/imgui/examples/example_glfw_opengl2/Makefile index 5c19a27f19e..1f15c15c068 100644 --- a/third_party/imgui/examples/example_glfw_opengl2/Makefile +++ b/third_party/imgui/examples/example_glfw_opengl2/Makefile @@ -22,7 +22,7 @@ SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = diff --git a/third_party/imgui/examples/example_glfw_opengl2/build_win32.bat b/third_party/imgui/examples/example_glfw_opengl2/build_win32.bat index a0a75f90607..24c0e08fda7 100644 --- a/third_party/imgui/examples/example_glfw_opengl2/build_win32.bat +++ b/third_party/imgui/examples/example_glfw_opengl2/build_win32.bat @@ -5,4 +5,4 @@ @set SOURCES=main.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj b/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj index faf6d9a5ae8..2aa25506e2f 100644 --- a/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj +++ b/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj @@ -91,6 +91,7 @@ Level4 Disabled ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -105,6 +106,7 @@ Level4 Disabled ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -122,6 +124,7 @@ true ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -142,6 +145,7 @@ true ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -172,6 +176,7 @@ + diff --git a/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters b/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters index 69b285d1af4..049b0b1a312 100644 --- a/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters +++ b/third_party/imgui/examples/example_glfw_opengl2/example_glfw_opengl2.vcxproj.filters @@ -55,7 +55,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_glfw_opengl2/main.cpp b/third_party/imgui/examples/example_glfw_opengl2/main.cpp index ee785b1f51b..5e47b000847 100644 --- a/third_party/imgui/examples/example_glfw_opengl2/main.cpp +++ b/third_party/imgui/examples/example_glfw_opengl2/main.cpp @@ -1,7 +1,11 @@ // Dear ImGui: standalone example application for GLFW + OpenGL2, using legacy fixed pipeline // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **Prefer using the code in the example_glfw_opengl2/ folder** @@ -25,17 +29,19 @@ static void glfw_error_callback(int error, const char* description) { - fprintf(stderr, "Glfw Error %d: %s\n", error, description); + fprintf(stderr, "GLFW Error %d: %s\n", error, description); } +// Main code int main(int, char**) { - // Setup window glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return 1; - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL2 example", NULL, NULL); - if (window == NULL) + + // Create window with graphics context + GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL2 example", nullptr, nullptr); + if (window == nullptr) return 1; glfwMakeContextCurrent(window); glfwSwapInterval(1); // Enable vsync @@ -44,12 +50,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); @@ -58,17 +64,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -80,8 +87,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); @@ -94,7 +101,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -113,7 +120,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } diff --git a/third_party/imgui/examples/example_glfw_opengl3/Makefile b/third_party/imgui/examples/example_glfw_opengl3/Makefile index 672a7059c76..252ce571442 100644 --- a/third_party/imgui/examples/example_glfw_opengl3/Makefile +++ b/third_party/imgui/examples/example_glfw_opengl3/Makefile @@ -23,7 +23,7 @@ OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) LINUX_GL_LIBS = -lGL -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = diff --git a/third_party/imgui/examples/example_glfw_opengl3/Makefile.emscripten b/third_party/imgui/examples/example_glfw_opengl3/Makefile.emscripten new file mode 100644 index 00000000000..bd972abffc8 --- /dev/null +++ b/third_party/imgui/examples/example_glfw_opengl3/Makefile.emscripten @@ -0,0 +1,91 @@ +# +# Makefile to use with GLFW+emscripten +# See https://emscripten.org/docs/getting_started/downloads.html +# for installation instructions. +# +# This Makefile assumes you have loaded emscripten's environment. +# (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead) +# +# Running `make -f Makefile.emscripten` will produce three files: +# - web/index.html +# - web/index.js +# - web/index.wasm +# +# All three are needed to run the demo. + +CC = emcc +CXX = em++ +WEB_DIR = web +EXE = $(WEB_DIR)/index.html +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) +CPPFLAGS = +LDFLAGS = +EMS = + +##--------------------------------------------------------------------- +## EMSCRIPTEN OPTIONS +##--------------------------------------------------------------------- + +# ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) +EMS += -s DISABLE_EXCEPTION_CATCHING=1 +LDFLAGS += -s USE_GLFW=3 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 + +# Uncomment next line to fix possible rendering bugs with Emscripten version older then 1.39.0 (https://github.com/ocornut/imgui/issues/2877) +#EMS += -s BINARYEN_TRAP_MODE=clamp +#EMS += -s SAFE_HEAP=1 ## Adds overhead + +# Emscripten allows preloading a file or folder to be accessible at runtime. +# The Makefile for this example project suggests embedding the misc/fonts/ folder into our application, it will then be accessible as "/fonts" +# See documentation for more details: https://emscripten.org/docs/porting/files/packaging_files.html +# (Default value is 0. Set to 1 to enable file-system and include the misc/fonts/ folder as part of the build.) +USE_FILE_SYSTEM ?= 0 +ifeq ($(USE_FILE_SYSTEM), 0) +LDFLAGS += -s NO_FILESYSTEM=1 +CPPFLAGS += -DIMGUI_DISABLE_FILE_FUNCTIONS +endif +ifeq ($(USE_FILE_SYSTEM), 1) +LDFLAGS += --no-heap-copy --preload-file ../../misc/fonts@/fonts +endif + +##--------------------------------------------------------------------- +## FINAL BUILD FLAGS +##--------------------------------------------------------------------- + +CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +#CPPFLAGS += -g +CPPFLAGS += -Wall -Wformat -Os $(EMS) +LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html +LDFLAGS += $(EMS) + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(EXE) + +$(WEB_DIR): + mkdir $@ + +serve: all + python3 -m http.server -d $(WEB_DIR) + +$(EXE): $(OBJS) $(WEB_DIR) + $(CXX) -o $@ $(OBJS) $(LDFLAGS) + +clean: + rm -rf $(OBJS) $(WEB_DIR) diff --git a/third_party/imgui/examples/example_glfw_opengl3/build_win32.bat b/third_party/imgui/examples/example_glfw_opengl3/build_win32.bat index 4ba58d8c9d4..b5979ad4939 100644 --- a/third_party/imgui/examples/example_glfw_opengl3/build_win32.bat +++ b/third_party/imgui/examples/example_glfw_opengl3/build_win32.bat @@ -5,4 +5,4 @@ @set SOURCES=main.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj b/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj index 7721c8ffacb..4bd503afe33 100644 --- a/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj +++ b/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj @@ -91,6 +91,7 @@ Level4 Disabled ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -105,6 +106,7 @@ Level4 Disabled ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -122,6 +124,7 @@ true ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -142,6 +145,7 @@ true ..\..;..\..\backends;..\libs\glfw\include;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -173,10 +177,11 @@ + - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters b/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters index fd2f8071453..bc79bb197d4 100644 --- a/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters +++ b/third_party/imgui/examples/example_glfw_opengl3/example_glfw_opengl3.vcxproj.filters @@ -58,7 +58,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_glfw_opengl3/main.cpp b/third_party/imgui/examples/example_glfw_opengl3/main.cpp index f8e8a02cf68..4438fa5bb6c 100644 --- a/third_party/imgui/examples/example_glfw_opengl3/main.cpp +++ b/third_party/imgui/examples/example_glfw_opengl3/main.cpp @@ -1,12 +1,17 @@ // Dear ImGui: standalone example application for GLFW + OpenGL 3, using programmable pipeline // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include +#define GL_SILENCE_DEPRECATION #if defined(IMGUI_IMPL_OPENGL_ES2) #include #endif @@ -19,14 +24,19 @@ #pragma comment(lib, "legacy_stdio_definitions") #endif +// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. +#ifdef __EMSCRIPTEN__ +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif + static void glfw_error_callback(int error, const char* description) { - fprintf(stderr, "Glfw Error %d: %s\n", error, description); + fprintf(stderr, "GLFW Error %d: %s\n", error, description); } +// Main code int main(int, char**) { - // Setup window glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return 1; @@ -55,8 +65,8 @@ int main(int, char**) #endif // Create window with graphics context - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL3 example", NULL, NULL); - if (window == NULL) + GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL3 example", nullptr, nullptr); + if (window == nullptr) return 1; glfwMakeContextCurrent(window); glfwSwapInterval(1); // Enable vsync @@ -65,31 +75,36 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); +#ifdef __EMSCRIPTEN__ + ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas"); +#endif ImGui_ImplOpenGL3_Init(glsl_version); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -97,12 +112,19 @@ int main(int, char**) ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Main loop +#ifdef __EMSCRIPTEN__ + // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. + // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. + io.IniFilename = nullptr; + EMSCRIPTEN_MAINLOOP_BEGIN +#else while (!glfwWindowShouldClose(window)) +#endif { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); @@ -115,7 +137,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -134,7 +156,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -159,6 +181,9 @@ int main(int, char**) glfwSwapBuffers(window); } +#ifdef __EMSCRIPTEN__ + EMSCRIPTEN_MAINLOOP_END; +#endif // Cleanup ImGui_ImplOpenGL3_Shutdown(); diff --git a/third_party/imgui/examples/example_glfw_vulkan/CMakeLists.txt b/third_party/imgui/examples/example_glfw_vulkan/CMakeLists.txt index 05eab3bc520..a6e5bf910fd 100644 --- a/third_party/imgui/examples/example_glfw_vulkan/CMakeLists.txt +++ b/third_party/imgui/examples/example_glfw_vulkan/CMakeLists.txt @@ -10,6 +10,7 @@ if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE) endif() +set(CMAKE_CXX_STANDARD 11) set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DVK_PROTOTYPES") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVK_PROTOTYPES") @@ -41,3 +42,4 @@ file(GLOB sources *.cpp) add_executable(example_glfw_vulkan ${sources} ${IMGUI_DIR}/backends/imgui_impl_glfw.cpp ${IMGUI_DIR}/backends/imgui_impl_vulkan.cpp ${IMGUI_DIR}/imgui.cpp ${IMGUI_DIR}/imgui_draw.cpp ${IMGUI_DIR}/imgui_demo.cpp ${IMGUI_DIR}/imgui_tables.cpp ${IMGUI_DIR}/imgui_widgets.cpp) target_link_libraries(example_glfw_vulkan ${LIBRARIES}) +target_compile_definitions(example_glfw_vulkan PUBLIC -DImTextureID=ImU64) diff --git a/third_party/imgui/examples/example_glfw_vulkan/build_win32.bat b/third_party/imgui/examples/example_glfw_vulkan/build_win32.bat index f49cbd77de8..be92398162e 100644 --- a/third_party/imgui/examples/example_glfw_vulkan/build_win32.bat +++ b/third_party/imgui/examples/example_glfw_vulkan/build_win32.bat @@ -7,8 +7,8 @@ @set OUT_DIR=Debug mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% @set OUT_DIR=Release mkdir %OUT_DIR% -cl /nologo /Zi /MD /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_glfw_vulkan/build_win64.bat b/third_party/imgui/examples/example_glfw_vulkan/build_win64.bat index 893f296f499..c60b027893b 100644 --- a/third_party/imgui/examples/example_glfw_vulkan/build_win64.bat +++ b/third_party/imgui/examples/example_glfw_vulkan/build_win64.bat @@ -6,8 +6,8 @@ @set OUT_DIR=Debug mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% @set OUT_DIR=Release mkdir %OUT_DIR% -cl /nologo /Zi /MD /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj b/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj index 34b3f21c5b6..d0d1c5f88df 100644 --- a/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj +++ b/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj @@ -91,6 +91,8 @@ Level4 Disabled ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -105,6 +107,8 @@ Level4 Disabled ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -122,6 +126,8 @@ true ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) false + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -142,6 +148,8 @@ true ..\..;..\..\backends;%VULKAN_SDK%\include;..\libs\glfw\include;%(AdditionalIncludeDirectories) false + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -172,6 +180,7 @@ + diff --git a/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters b/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters index adc3365cec0..510fc8547a3 100644 --- a/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters +++ b/third_party/imgui/examples/example_glfw_vulkan/example_glfw_vulkan.vcxproj.filters @@ -55,7 +55,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_glfw_vulkan/main.cpp b/third_party/imgui/examples/example_glfw_vulkan/main.cpp index 615f2ee1d10..b1c596dd38f 100644 --- a/third_party/imgui/examples/example_glfw_vulkan/main.cpp +++ b/third_party/imgui/examples/example_glfw_vulkan/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for Glfw + Vulkan -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. @@ -18,6 +22,7 @@ #define GLFW_INCLUDE_VULKAN #include #include +//#include // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers. // To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma. @@ -26,12 +31,13 @@ #pragma comment(lib, "legacy_stdio_definitions") #endif -//#define IMGUI_UNLIMITED_FRAME_RATE +//#define APP_USE_UNLIMITED_FRAME_RATE #ifdef _DEBUG -#define IMGUI_VULKAN_DEBUG_REPORT +#define APP_USE_VULKAN_DEBUG_REPORT #endif -static VkAllocationCallbacks* g_Allocator = NULL; +// Data +static VkAllocationCallbacks* g_Allocator = nullptr; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; static VkDevice g_Device = VK_NULL_HANDLE; @@ -45,6 +51,10 @@ static ImGui_ImplVulkanH_Window g_MainWindowData; static int g_MinImageCount = 2; static bool g_SwapChainRebuild = false; +static void glfw_error_callback(int error, const char* description) +{ + fprintf(stderr, "GLFW Error %d: %s\n", error, description); +} static void check_vk_result(VkResult err) { if (err == 0) @@ -54,16 +64,53 @@ static void check_vk_result(VkResult err) abort(); } -#ifdef IMGUI_VULKAN_DEBUG_REPORT +#ifdef APP_USE_VULKAN_DEBUG_REPORT static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } -#endif // IMGUI_VULKAN_DEBUG_REPORT +#endif // APP_USE_VULKAN_DEBUG_REPORT + +static bool IsExtensionAvailable(const ImVector& properties, const char* extension) +{ + for (const VkExtensionProperties& p : properties) + if (strcmp(p.extensionName, extension) == 0) + return true; + return false; +} + +static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice() +{ + uint32_t gpu_count; + VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr); + check_vk_result(err); + IM_ASSERT(gpu_count > 0); + + ImVector gpus; + gpus.resize(gpu_count); + err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data); + check_vk_result(err); + + // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers + // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple + // dedicated GPUs) is out of scope of this sample. + for (VkPhysicalDevice& device : gpus) + { + VkPhysicalDeviceProperties properties; + vkGetPhysicalDeviceProperties(device, &properties); + if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) + return device; + } + + // Use first GPU (Integrated) is a Discrete one is not available. + if (gpu_count > 0) + return gpus[0]; + return VK_NULL_HANDLE; +} -static void SetupVulkan(const char** extensions, uint32_t extensions_count) +static void SetupVulkan(ImVector instance_extensions) { VkResult err; @@ -71,80 +118,61 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) { VkInstanceCreateInfo create_info = {}; create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - create_info.enabledExtensionCount = extensions_count; - create_info.ppEnabledExtensionNames = extensions; -#ifdef IMGUI_VULKAN_DEBUG_REPORT + + // Enumerate available extensions + uint32_t properties_count; + ImVector properties; + vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, nullptr); + properties.resize(properties_count); + err = vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, properties.Data); + check_vk_result(err); + + // Enable required extensions + if (IsExtensionAvailable(properties, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) + instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); +#ifdef VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME + if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME)) + { + instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); + create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR; + } +#endif + // Enabling validation layers +#ifdef APP_USE_VULKAN_DEBUG_REPORT const char* layers[] = { "VK_LAYER_KHRONOS_validation" }; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = layers; - - // Enable debug report extension (we need additional storage, so we duplicate the user array to add our new extension to it) - const char** extensions_ext = (const char**)malloc(sizeof(const char*) * (extensions_count + 1)); - memcpy(extensions_ext, extensions, extensions_count * sizeof(const char*)); - extensions_ext[extensions_count] = "VK_EXT_debug_report"; - create_info.enabledExtensionCount = extensions_count + 1; - create_info.ppEnabledExtensionNames = extensions_ext; + instance_extensions.push_back("VK_EXT_debug_report"); +#endif // Create Vulkan Instance + create_info.enabledExtensionCount = (uint32_t)instance_extensions.Size; + create_info.ppEnabledExtensionNames = instance_extensions.Data; err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); check_vk_result(err); - free(extensions_ext); - - // Get the function pointer (required for any extensions) - auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); - IM_ASSERT(vkCreateDebugReportCallbackEXT != NULL); // Setup the debug report callback +#ifdef APP_USE_VULKAN_DEBUG_REPORT + auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); + IM_ASSERT(vkCreateDebugReportCallbackEXT != nullptr); VkDebugReportCallbackCreateInfoEXT debug_report_ci = {}; debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; debug_report_ci.pfnCallback = debug_report; - debug_report_ci.pUserData = NULL; + debug_report_ci.pUserData = nullptr; err = vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); check_vk_result(err); -#else - // Create Vulkan Instance without any debug feature - err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); - check_vk_result(err); - IM_UNUSED(g_DebugReport); #endif } - // Select GPU - { - uint32_t gpu_count; - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, NULL); - check_vk_result(err); - IM_ASSERT(gpu_count > 0); - - VkPhysicalDevice* gpus = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * gpu_count); - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus); - check_vk_result(err); - - // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers - // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple - // dedicated GPUs) is out of scope of this sample. - int use_gpu = 0; - for (int i = 0; i < (int)gpu_count; i++) - { - VkPhysicalDeviceProperties properties; - vkGetPhysicalDeviceProperties(gpus[i], &properties); - if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) - { - use_gpu = i; - break; - } - } - - g_PhysicalDevice = gpus[use_gpu]; - free(gpus); - } + // Select Physical Device (GPU) + g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice(); // Select graphics queue family { uint32_t count; - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, NULL); + vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr); VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); for (uint32_t i = 0; i < count; i++) @@ -159,8 +187,20 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) // Create Logical Device (with 1 queue) { - int device_extension_count = 1; - const char* device_extensions[] = { "VK_KHR_swapchain" }; + ImVector device_extensions; + device_extensions.push_back("VK_KHR_swapchain"); + + // Enumerate physical device extension + uint32_t properties_count; + ImVector properties; + vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, nullptr); + properties.resize(properties_count); + vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, properties.Data); +#ifdef VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME + if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME)) + device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME); +#endif + const float queue_priority[] = { 1.0f }; VkDeviceQueueCreateInfo queue_info[1] = {}; queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; @@ -171,33 +211,25 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; create_info.queueCreateInfoCount = sizeof(queue_info) / sizeof(queue_info[0]); create_info.pQueueCreateInfos = queue_info; - create_info.enabledExtensionCount = device_extension_count; - create_info.ppEnabledExtensionNames = device_extensions; + create_info.enabledExtensionCount = (uint32_t)device_extensions.Size; + create_info.ppEnabledExtensionNames = device_extensions.Data; err = vkCreateDevice(g_PhysicalDevice, &create_info, g_Allocator, &g_Device); check_vk_result(err); vkGetDeviceQueue(g_Device, g_QueueFamily, 0, &g_Queue); } // Create Descriptor Pool + // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) + // If you wish to load e.g. additional textures you may need to alter pools sizes. { VkDescriptorPoolSize pool_sizes[] = { - { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 }, - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 }, - { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 }, - { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 }, - { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 } + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; - pool_info.maxSets = 1000 * IM_ARRAYSIZE(pool_sizes); + pool_info.maxSets = 1; pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); @@ -226,7 +258,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode -#ifdef IMGUI_UNLIMITED_FRAME_RATE +#ifdef APP_USE_UNLIMITED_FRAME_RATE VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; @@ -243,11 +275,11 @@ static void CleanupVulkan() { vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); -#ifdef IMGUI_VULKAN_DEBUG_REPORT +#ifdef APP_USE_VULKAN_DEBUG_REPORT // Remove the debug report callback auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT"); vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator); -#endif // IMGUI_VULKAN_DEBUG_REPORT +#endif // APP_USE_VULKAN_DEBUG_REPORT vkDestroyDevice(g_Device, g_Allocator); vkDestroyInstance(g_Instance, g_Allocator); @@ -344,33 +376,31 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) return; } check_vk_result(err); - wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores -} - -static void glfw_error_callback(int error, const char* description) -{ - fprintf(stderr, "Glfw Error %d: %s\n", error, description); + wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores } +// Main code int main(int, char**) { - // Setup GLFW window glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return 1; + // Create window with Vulkan context glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Vulkan example", NULL, NULL); - - // Setup Vulkan + GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Vulkan example", nullptr, nullptr); if (!glfwVulkanSupported()) { printf("GLFW: Vulkan Not Supported\n"); return 1; } + + ImVector extensions; uint32_t extensions_count = 0; - const char** extensions = glfwGetRequiredInstanceExtensions(&extensions_count); - SetupVulkan(extensions, extensions_count); + const char** glfw_extensions = glfwGetRequiredInstanceExtensions(&extensions_count); + for (uint32_t i = 0; i < extensions_count; i++) + extensions.push_back(glfw_extensions[i]); + SetupVulkan(extensions); // Create Window Surface VkSurfaceKHR surface; @@ -387,12 +417,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForVulkan(window, true); @@ -404,56 +434,30 @@ int main(int, char**) init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; - init_info.Allocator = g_Allocator; + init_info.RenderPass = wd->RenderPass; + init_info.Subpass = 0; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd->ImageCount; + init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; + init_info.Allocator = g_Allocator; init_info.CheckVkResultFn = check_vk_result; - ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); + ImGui_ImplVulkan_Init(&init_info); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); - - // Upload Fonts - { - // Use any command queue - VkCommandPool command_pool = wd->Frames[wd->FrameIndex].CommandPool; - VkCommandBuffer command_buffer = wd->Frames[wd->FrameIndex].CommandBuffer; - - err = vkResetCommandPool(g_Device, command_pool, 0); - check_vk_result(err); - VkCommandBufferBeginInfo begin_info = {}; - begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - err = vkBeginCommandBuffer(command_buffer, &begin_info); - check_vk_result(err); - - ImGui_ImplVulkan_CreateFontsTexture(command_buffer); - - VkSubmitInfo end_info = {}; - end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - end_info.commandBufferCount = 1; - end_info.pCommandBuffers = &command_buffer; - err = vkEndCommandBuffer(command_buffer); - check_vk_result(err); - err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE); - check_vk_result(err); - - err = vkDeviceWaitIdle(g_Device); - check_vk_result(err); - ImGui_ImplVulkan_DestroyFontUploadObjects(); - } + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -465,8 +469,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. glfwPollEvents(); @@ -493,7 +497,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -512,7 +516,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } diff --git a/third_party/imgui/examples/example_glut_opengl2/Makefile b/third_party/imgui/examples/example_glut_opengl2/Makefile index a980f56fb04..7af289dc492 100644 --- a/third_party/imgui/examples/example_glut_opengl2/Makefile +++ b/third_party/imgui/examples/example_glut_opengl2/Makefile @@ -17,7 +17,7 @@ SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glut.cpp $(IMGUI_DIR)/backends/imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = diff --git a/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj b/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj index 4c9d00f5cab..c56452b26c5 100644 --- a/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj +++ b/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj @@ -91,6 +91,7 @@ Level4 Disabled $(GLUT_INCLUDE_DIR);..\..;..\..\backends;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -105,6 +106,7 @@ Level4 Disabled $(GLUT_INCLUDE_DIR);..\..;..\..\backends;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -122,6 +124,7 @@ true $(GLUT_INCLUDE_DIR);..\..;..\..\backends;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -142,6 +145,7 @@ true $(GLUT_INCLUDE_DIR);..\..;..\..\backends;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -172,6 +176,7 @@ + diff --git a/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters b/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters index 3c017ba94aa..0ac4a0b2ed0 100644 --- a/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters +++ b/third_party/imgui/examples/example_glut_opengl2/example_glut_opengl2.vcxproj.filters @@ -55,7 +55,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_glut_opengl2/main.cpp b/third_party/imgui/examples/example_glut_opengl2/main.cpp index fed62b52c5f..58539ca5f91 100644 --- a/third_party/imgui/examples/example_glut_opengl2/main.cpp +++ b/third_party/imgui/examples/example_glut_opengl2/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for GLUT/FreeGLUT + OpenGL2, using legacy fixed pipeline -// 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 + +// 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 // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! @@ -17,28 +21,104 @@ #include "imgui.h" #include "imgui_impl_glut.h" #include "imgui_impl_opengl2.h" +#define GL_SILENCE_DEPRECATION #ifdef __APPLE__ - #include +#include #else - #include +#include #endif #ifdef _MSC_VER #pragma warning (disable: 4505) // unreferenced local function has been removed #endif +// Forward declarations of helper functions +void MainLoopStep(); + // Our state static bool show_demo_window = true; static bool show_another_window = false; static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); -void my_display_code() +int main(int argc, char** argv) +{ + // Create GLUT window + glutInit(&argc, argv); +#ifdef __FREEGLUT_EXT_H__ + glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); +#endif + glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE); + glutInitWindowSize(1280, 720); + glutCreateWindow("Dear ImGui GLUT+OpenGL2 Example"); + + // Setup GLUT display function + // We will also call ImGui_ImplGLUT_InstallFuncs() to get all the other functions installed for us, + // otherwise it is possible to install our own functions and call the imgui_impl_glut.h functions ourselves. + glutDisplayFunc(MainLoopStep); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup Platform/Renderer backends + // FIXME: Consider reworking this example to install our own GLUT funcs + forward calls ImGui_ImplGLUT_XXX ones, instead of using ImGui_ImplGLUT_InstallFuncs(). + ImGui_ImplGLUT_Init(); + ImGui_ImplOpenGL2_Init(); + + // Install GLUT handlers (glutReshapeFunc(), glutMotionFunc(), glutPassiveMotionFunc(), glutMouseFunc(), glutKeyboardFunc() etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + ImGui_ImplGLUT_InstallFuncs(); + + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); + + // Main loop + glutMainLoop(); + + // Cleanup + ImGui_ImplOpenGL2_Shutdown(); + ImGui_ImplGLUT_Shutdown(); + ImGui::DestroyContext(); + + return 0; +} + +void MainLoopStep() { + // Start the Dear ImGui frame + ImGui_ImplOpenGL2_NewFrame(); + ImGui_ImplGLUT_NewFrame(); + ImGui::NewFrame(); + ImGuiIO& io = ImGui::GetIO(); + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -57,7 +137,7 @@ void my_display_code() ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -70,19 +150,9 @@ void my_display_code() show_another_window = false; ImGui::End(); } -} - -void glut_display_func() -{ - // Start the Dear ImGui frame - ImGui_ImplOpenGL2_NewFrame(); - ImGui_ImplGLUT_NewFrame(); - - my_display_code(); // Rendering ImGui::Render(); - ImGuiIO& io = ImGui::GetIO(); glViewport(0, 0, (GLsizei)io.DisplaySize.x, (GLsizei)io.DisplaySize.y); glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); @@ -92,64 +162,3 @@ void glut_display_func() glutSwapBuffers(); glutPostRedisplay(); } - -// 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. - -int main(int argc, char** argv) -{ - // Create GLUT window - glutInit(&argc, argv); -#ifdef __FREEGLUT_EXT_H__ - glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); -#endif - glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE); - glutInitWindowSize(1280, 720); - glutCreateWindow("Dear ImGui GLUT+OpenGL2 Example"); - - // Setup GLUT display function - // We will also call ImGui_ImplGLUT_InstallFuncs() to get all the other functions installed for us, - // otherwise it is possible to install our own functions and call the imgui_impl_glut.h functions ourselves. - glutDisplayFunc(glut_display_func); - - // Setup Dear ImGui context - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - - // Setup Dear ImGui style - ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); - - // Setup Platform/Renderer backends - ImGui_ImplGLUT_Init(); - ImGui_ImplGLUT_InstallFuncs(); - ImGui_ImplOpenGL2_Init(); - - // Load Fonts - // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. - // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). - // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.md' for more instructions and details. - // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! - //io.Fonts->AddFontDefault(); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); - - glutMainLoop(); - - // Cleanup - ImGui_ImplOpenGL2_Shutdown(); - ImGui_ImplGLUT_Shutdown(); - ImGui::DestroyContext(); - - return 0; -} diff --git a/third_party/imgui/examples/example_null/Makefile b/third_party/imgui/examples/example_null/Makefile index 9208e8a080a..9ceb353493b 100644 --- a/third_party/imgui/examples/example_null/Makefile +++ b/third_party/imgui/examples/example_null/Makefile @@ -17,7 +17,7 @@ SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS += -I$(IMGUI_DIR) +CXXFLAGS += -std=c++11 -I$(IMGUI_DIR) CXXFLAGS += -g -Wall -Wformat LIBS = @@ -52,7 +52,7 @@ endif ifeq ($(UNAME_S), Darwin) #APPLE ECHO_MESSAGE = "Mac OS X" ifeq ($(WITH_EXTRA_WARNINGS), 1) - CXXFLAGS += -Weverything -Wno-reserved-id-macro -Wno-c++98-compat-pedantic -Wno-padded -Wno-c++11-long-long -Wno-poison-system-directories + CXXFLAGS += -Weverything -Wno-reserved-id-macro -Wno-c++98-compat-pedantic -Wno-padded -Wno-poison-system-directories endif CFLAGS = $(CXXFLAGS) endif diff --git a/third_party/imgui/examples/example_null/build_win32.bat b/third_party/imgui/examples/example_null/build_win32.bat index 0cdfdc93b8f..be81d80936f 100644 --- a/third_party/imgui/examples/example_null/build_win32.bat +++ b/third_party/imgui/examples/example_null/build_win32.bat @@ -1,3 +1,3 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. mkdir Debug -cl /nologo /Zi /MD /I ..\.. %* *.cpp ..\..\*.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib +cl /nologo /Zi /MD /utf-8 /I ..\.. %* *.cpp ..\..\*.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib diff --git a/third_party/imgui/examples/example_null/main.cpp b/third_party/imgui/examples/example_null/main.cpp index 72381f0afa6..f7153cc4888 100644 --- a/third_party/imgui/examples/example_null/main.cpp +++ b/third_party/imgui/examples/example_null/main.cpp @@ -11,7 +11,7 @@ int main(int, char**) ImGuiIO& io = ImGui::GetIO(); // Build atlas - unsigned char* tex_pixels = NULL; + unsigned char* tex_pixels = nullptr; int tex_w, tex_h; io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_w, &tex_h); @@ -26,7 +26,7 @@ int main(int, char**) ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); - ImGui::ShowDemoWindow(NULL); + ImGui::ShowDemoWindow(nullptr); ImGui::Render(); } diff --git a/third_party/imgui/examples/example_sdl_directx11/build_win32.bat b/third_party/imgui/examples/example_sdl2_directx11/build_win32.bat similarity index 61% rename from third_party/imgui/examples/example_sdl_directx11/build_win32.bat rename to third_party/imgui/examples/example_sdl2_directx11/build_win32.bat index b93082704e4..f0b485ca68b 100644 --- a/third_party/imgui/examples/example_sdl_directx11/build_win32.bat +++ b/third_party/imgui/examples/example_sdl2_directx11/build_win32.bat @@ -1,8 +1,8 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug -@set OUT_EXE=example_sdl_directx11 +@set OUT_EXE=example_sdl2_directx11 @set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib shell32.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_sdl_directx11/example_sdl_directx11.vcxproj b/third_party/imgui/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj similarity index 94% rename from third_party/imgui/examples/example_sdl_directx11/example_sdl_directx11.vcxproj rename to third_party/imgui/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj index ac636d2f339..c23800c9e4a 100644 --- a/third_party/imgui/examples/example_sdl_directx11/example_sdl_directx11.vcxproj +++ b/third_party/imgui/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj @@ -20,9 +20,9 @@ {9E1987E3-1F19-45CA-B9C9-D31E791836D8} - example_sdl_directx11 + example_sdl2_directx11 8.1 - example_sdl_directx11 + example_sdl2_directx11 @@ -92,6 +92,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -106,6 +107,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -123,6 +125,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -143,6 +146,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -161,18 +165,19 @@ + - + - + diff --git a/third_party/imgui/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters b/third_party/imgui/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj.filters similarity index 86% rename from third_party/imgui/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters rename to third_party/imgui/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj.filters index 15fc8533561..92d11f88e91 100644 --- a/third_party/imgui/examples/example_sdl_directx11/example_sdl_directx11.vcxproj.filters +++ b/third_party/imgui/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj.filters @@ -18,10 +18,10 @@ imgui - + sources - + sources @@ -44,17 +44,20 @@ imgui - + sources - + sources - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl_directx11/main.cpp b/third_party/imgui/examples/example_sdl2_directx11/main.cpp similarity index 79% rename from third_party/imgui/examples/example_sdl_directx11/main.cpp rename to third_party/imgui/examples/example_sdl2_directx11/main.cpp index fc517152082..3275bafde50 100644 --- a/third_party/imgui/examples/example_sdl_directx11/main.cpp +++ b/third_party/imgui/examples/example_sdl2_directx11/main.cpp @@ -1,10 +1,14 @@ // Dear ImGui: standalone example application for SDL2 + DirectX 11 // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" -#include "imgui_impl_sdl.h" +#include "imgui_impl_sdl2.h" #include "imgui_impl_dx11.h" #include #include @@ -12,10 +16,10 @@ #include // Data -static ID3D11Device* g_pd3dDevice = NULL; -static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; -static IDXGISwapChain* g_pSwapChain = NULL; -static ID3D11RenderTargetView* g_mainRenderTargetView = NULL; +static ID3D11Device* g_pd3dDevice = nullptr; +static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr; +static IDXGISwapChain* g_pSwapChain = nullptr; +static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr; // Forward declarations of helper functions bool CreateDeviceD3D(HWND hWnd); @@ -28,16 +32,27 @@ int main(int, char**) { // Setup SDL // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems, - // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to latest version of SDL is recommended!) + // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to the latest version of SDL is recommended!) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } + // From 2.0.18: Enable native IME. +#ifdef SDL_HINT_IME_SHOW_UI + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); +#endif + // Setup window SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window, &wmInfo); @@ -54,12 +69,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForD3D(window); @@ -68,17 +83,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -91,8 +107,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) @@ -120,7 +136,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -139,7 +155,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -156,7 +172,7 @@ int main(int, char**) // Rendering ImGui::Render(); const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; - g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL); + g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr); g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); @@ -176,8 +192,7 @@ int main(int, char**) return 0; } -// Helper functions - +// Helper functions to use DirectX11 bool CreateDeviceD3D(HWND hWnd) { // Setup swap chain @@ -201,7 +216,7 @@ bool CreateDeviceD3D(HWND hWnd) //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; D3D_FEATURE_LEVEL featureLevel; const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; - if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) + if (D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) return false; CreateRenderTarget(); @@ -211,20 +226,20 @@ bool CreateDeviceD3D(HWND hWnd) void CleanupDeviceD3D() { CleanupRenderTarget(); - if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } - if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } + if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; } + if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = nullptr; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; } } void CreateRenderTarget() { ID3D11Texture2D* pBackBuffer; g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); - g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView); pBackBuffer->Release(); } void CleanupRenderTarget() { - if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } + if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; } } diff --git a/third_party/imgui/examples/example_sdl_metal/Makefile b/third_party/imgui/examples/example_sdl2_metal/Makefile similarity index 83% rename from third_party/imgui/examples/example_sdl_metal/Makefile rename to third_party/imgui/examples/example_sdl2_metal/Makefile index 042bb04cce9..53c5f75db37 100644 --- a/third_party/imgui/examples/example_sdl_metal/Makefile +++ b/third_party/imgui/examples/example_sdl2_metal/Makefile @@ -6,18 +6,18 @@ #CXX = g++ #CXX = clang++ -EXE = example_sdl_metal +EXE = example_sdl2_metal IMGUI_DIR = ../.. SOURCES = main.mm SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp -SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_metal.mm +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp $(IMGUI_DIR)/backends/imgui_impl_metal.mm OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore LIBS += `sdl2-config --libs` LIBS += -L/usr/local/lib -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include CXXFLAGS += `sdl2-config --cflags` CXXFLAGS += -Wall -Wformat CFLAGS = $(CXXFLAGS) diff --git a/third_party/imgui/examples/example_sdl_metal/main.mm b/third_party/imgui/examples/example_sdl2_metal/main.mm similarity index 84% rename from third_party/imgui/examples/example_sdl_metal/main.mm rename to third_party/imgui/examples/example_sdl2_metal/main.mm index caa86e644da..d54812710c5 100644 --- a/third_party/imgui/examples/example_sdl_metal/main.mm +++ b/third_party/imgui/examples/example_sdl2_metal/main.mm @@ -1,10 +1,14 @@ // Dear ImGui: standalone example application for SDL2 + Metal // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" -#include "imgui_impl_sdl.h" +#include "imgui_impl_sdl2.h" #include "imgui_impl_metal.h" #include #include @@ -18,27 +22,28 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. - // - Read 'docs/FONTS.txt' for more instructions and details. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Setup SDL // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems, @@ -52,15 +57,18 @@ int main(int, char**) // Inform SDL that we will be using metal for rendering. Without this hint initialization of metal renderer may fail. SDL_SetHint(SDL_HINT_RENDER_DRIVER, "metal"); + // Enable native IME. + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL+Metal example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - if (window == NULL) + if (window == nullptr) { printf("Error creating window: %s\n", SDL_GetError()); return -2; } SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); - if (renderer == NULL) + if (renderer == nullptr) { printf("Error creating renderer: %s\n", SDL_GetError()); return -3; @@ -88,8 +96,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) @@ -123,7 +131,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -142,7 +150,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } diff --git a/third_party/imgui/examples/example_sdl_opengl2/Makefile b/third_party/imgui/examples/example_sdl2_opengl2/Makefile similarity index 91% rename from third_party/imgui/examples/example_sdl_opengl2/Makefile rename to third_party/imgui/examples/example_sdl2_opengl2/Makefile index 92e0554bbfa..a85ced0232a 100644 --- a/third_party/imgui/examples/example_sdl_opengl2/Makefile +++ b/third_party/imgui/examples/example_sdl2_opengl2/Makefile @@ -14,15 +14,15 @@ #CXX = g++ #CXX = clang++ -EXE = example_sdl_opengl2 +EXE = example_sdl2_opengl2 IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp -SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = diff --git a/third_party/imgui/examples/example_sdl2_opengl2/README.md b/third_party/imgui/examples/example_sdl2_opengl2/README.md new file mode 100644 index 00000000000..40a49e691bb --- /dev/null +++ b/third_party/imgui/examples/example_sdl2_opengl2/README.md @@ -0,0 +1,29 @@ + +# How to Build + +- On Windows with Visual Studio's IDE + +Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) if necessary. + +- On Windows with Visual Studio's CLI + +``` +set SDL2_DIR=path_to_your_sdl2_folder +cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl2_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +# ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries +# or for 64-bit: +cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl2_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +``` + +- On Linux and similar Unixes + +``` +c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends main.cpp ../../backends/imgui_impl_sdl2.cpp ../../backends/imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL +``` + +- On Mac OS X + +``` +brew install sdl2 +c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends main.cpp ../../backends/imgui_impl_sdl2.cpp ../../backends/imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl +``` diff --git a/third_party/imgui/examples/example_sdl_opengl2/build_win32.bat b/third_party/imgui/examples/example_sdl2_opengl2/build_win32.bat similarity index 52% rename from third_party/imgui/examples/example_sdl_opengl2/build_win32.bat rename to third_party/imgui/examples/example_sdl2_opengl2/build_win32.bat index 47529e289dd..7543edafc3d 100644 --- a/third_party/imgui/examples/example_sdl_opengl2/build_win32.bat +++ b/third_party/imgui/examples/example_sdl2_opengl2/build_win32.bat @@ -1,8 +1,8 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug -@set OUT_EXE=example_sdl_opengl2 +@set OUT_EXE=example_sdl2_opengl2 @set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib shell32.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj b/third_party/imgui/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj similarity index 94% rename from third_party/imgui/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj rename to third_party/imgui/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj index d22a67baed7..036463f96bf 100644 --- a/third_party/imgui/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj +++ b/third_party/imgui/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj @@ -20,7 +20,7 @@ {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} - example_sdl_opengl2 + example_sdl2_opengl2 8.1 @@ -91,6 +91,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -105,6 +106,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -122,6 +124,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -142,6 +145,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -160,18 +164,19 @@ + - + - + diff --git a/third_party/imgui/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters b/third_party/imgui/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj.filters similarity index 87% rename from third_party/imgui/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters rename to third_party/imgui/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj.filters index 2253b8656bf..752a1965d9f 100644 --- a/third_party/imgui/examples/example_sdl_opengl2/example_sdl_opengl2.vcxproj.filters +++ b/third_party/imgui/examples/example_sdl2_opengl2/example_sdl2_opengl2.vcxproj.filters @@ -28,7 +28,7 @@ imgui - + sources @@ -48,14 +48,17 @@ sources - + sources - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl_opengl2/main.cpp b/third_party/imgui/examples/example_sdl2_opengl2/main.cpp similarity index 80% rename from third_party/imgui/examples/example_sdl_opengl2/main.cpp rename to third_party/imgui/examples/example_sdl2_opengl2/main.cpp index a81f8564039..efb28edbc41 100644 --- a/third_party/imgui/examples/example_sdl_opengl2/main.cpp +++ b/third_party/imgui/examples/example_sdl2_opengl2/main.cpp @@ -1,14 +1,18 @@ // Dear ImGui: standalone example application for SDL2 + OpenGL // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** -// **Prefer using the code in the example_sdl_opengl3/ folder** -// See imgui_impl_sdl.cpp for details. +// **Prefer using the code in the example_sdl2_opengl3/ folder** +// See imgui_impl_sdl2.cpp for details. #include "imgui.h" -#include "imgui_impl_sdl.h" +#include "imgui_impl_sdl2.h" #include "imgui_impl_opengl2.h" #include #include @@ -18,14 +22,17 @@ int main(int, char**) { // Setup SDL - // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems, - // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to latest version of SDL is recommended!) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } + // From 2.0.18: Enable native IME. +#ifdef SDL_HINT_IME_SHOW_UI + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); +#endif + // Setup window SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); @@ -34,6 +41,12 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(1); // Enable vsync @@ -42,12 +55,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); @@ -56,17 +69,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -79,8 +93,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) @@ -101,7 +115,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -120,7 +134,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } diff --git a/third_party/imgui/examples/example_sdl_opengl3/Makefile b/third_party/imgui/examples/example_sdl2_opengl3/Makefile similarity index 92% rename from third_party/imgui/examples/example_sdl_opengl3/Makefile rename to third_party/imgui/examples/example_sdl2_opengl3/Makefile index 1b8ab422722..5b4f9419c08 100644 --- a/third_party/imgui/examples/example_sdl_opengl3/Makefile +++ b/third_party/imgui/examples/example_sdl2_opengl3/Makefile @@ -14,16 +14,16 @@ #CXX = g++ #CXX = clang++ -EXE = example_sdl_opengl3 +EXE = example_sdl2_opengl3 IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp -SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) LINUX_GL_LIBS = -lGL -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = diff --git a/third_party/imgui/examples/example_emscripten_opengl3/Makefile b/third_party/imgui/examples/example_sdl2_opengl3/Makefile.emscripten similarity index 91% rename from third_party/imgui/examples/example_emscripten_opengl3/Makefile rename to third_party/imgui/examples/example_sdl2_opengl3/Makefile.emscripten index b2933e10845..da0348435d0 100644 --- a/third_party/imgui/examples/example_emscripten_opengl3/Makefile +++ b/third_party/imgui/examples/example_sdl2_opengl3/Makefile.emscripten @@ -1,12 +1,12 @@ # -# Makefile to use with emscripten +# Makefile to use with SDL+emscripten # See https://emscripten.org/docs/getting_started/downloads.html # for installation instructions. # # This Makefile assumes you have loaded emscripten's environment. # (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead) # -# Running `make` will produce three files: +# Running `make -f Makefile.emscripten` will produce three files: # - web/index.html # - web/index.js # - web/index.wasm @@ -20,7 +20,7 @@ EXE = $(WEB_DIR)/index.html IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp -SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) CPPFLAGS = @@ -60,7 +60,8 @@ endif CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends #CPPFLAGS += -g CPPFLAGS += -Wall -Wformat -Os $(EMS) -LDFLAGS += --shell-file shell_minimal.html $(EMS) +LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html +LDFLAGS += $(EMS) ##--------------------------------------------------------------------- ## BUILD RULES diff --git a/third_party/imgui/examples/example_sdl2_opengl3/README.md b/third_party/imgui/examples/example_sdl2_opengl3/README.md new file mode 100644 index 00000000000..81fd9fe7b7d --- /dev/null +++ b/third_party/imgui/examples/example_sdl2_opengl3/README.md @@ -0,0 +1,57 @@ + +# How to Build + +## Windows with Visual Studio's IDE + +Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) if necessary. + +## Windows with Visual Studio's CLI + +Use build_win32.bat or directly: +``` +set SDL2_DIR=path_to_your_sdl2_folder +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl2_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +# ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries +# or for 64-bit: +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl2_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console +``` + +## Linux and similar Unixes + +Use our Makefile or directly: +``` +c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends + main.cpp ../../backends/imgui_impl_sdl2.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp + `sdl2-config --libs` -lGL -ldl +``` + +## macOS + +Use our Makefile or directly: +``` +brew install sdl2 +c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends + main.cpp ../../backends/imgui_impl_sdl2.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp + `sdl2-config --libs` -framework OpenGl -framework CoreFoundation +``` + +## Emscripten + +**Building** + +You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions + +- Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools. +- You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. +- Then build using `make -f Makefile.emscripten` while in the current directory. + +**Running an Emscripten project** + +To run on a local machine: +- `make -f Makefile.emscripten serve` will use Python3 to spawn a local webserver, you can then browse http://localhost:8000 to access your build. +- Otherwise, generally you will need a local webserver. Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):
+_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and can’t load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers you’ll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ +- Emscripten SDK has a handy `emrun` command: `emrun web/index.html --browser firefox` which will spawn a temporary local webserver (in Firefox). See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. +- You may use Python 3 builtin webserver: `python -m http.server -d web` (this is what `make serve` uses). +- You may use Python 2 builtin webserver: `cd web && python -m SimpleHTTPServer`. +- If you are accessing the files over a network, certain browsers, such as Firefox, will restrict Gamepad API access to secure contexts only (e.g. https only). diff --git a/third_party/imgui/examples/example_sdl_opengl3/build_win32.bat b/third_party/imgui/examples/example_sdl2_opengl3/build_win32.bat similarity index 52% rename from third_party/imgui/examples/example_sdl_opengl3/build_win32.bat rename to third_party/imgui/examples/example_sdl2_opengl3/build_win32.bat index 20851bff6f1..7b2fac9223f 100644 --- a/third_party/imgui/examples/example_sdl_opengl3/build_win32.bat +++ b/third_party/imgui/examples/example_sdl2_opengl3/build_win32.bat @@ -1,8 +1,8 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. @set OUT_DIR=Debug -@set OUT_EXE=example_sdl_opengl3 +@set OUT_EXE=example_sdl2_opengl3 @set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib shell32.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj b/third_party/imgui/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj similarity index 94% rename from third_party/imgui/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj rename to third_party/imgui/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj index ace041df26b..6a81c67704b 100644 --- a/third_party/imgui/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj +++ b/third_party/imgui/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj @@ -20,7 +20,7 @@ {BBAEB705-1669-40F3-8567-04CF6A991F4C} - example_sdl_opengl3 + example_sdl2_opengl3 8.1 @@ -91,6 +91,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions)
true @@ -105,6 +106,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions)
true @@ -122,6 +124,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions)
true @@ -142,6 +145,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions)
true @@ -160,23 +164,24 @@ + - + - + - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters b/third_party/imgui/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj.filters similarity index 88% rename from third_party/imgui/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters rename to third_party/imgui/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj.filters index c8dbeae4c22..846d5575957 100644 --- a/third_party/imgui/examples/example_sdl_opengl3/example_sdl_opengl3.vcxproj.filters +++ b/third_party/imgui/examples/example_sdl2_opengl3/example_sdl2_opengl3.vcxproj.filters @@ -22,10 +22,10 @@ sources - + sources - + sources @@ -45,20 +45,23 @@ imgui - + sources - + sources - + sources - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl_opengl3/main.cpp b/third_party/imgui/examples/example_sdl2_opengl3/main.cpp similarity index 77% rename from third_party/imgui/examples/example_sdl_opengl3/main.cpp rename to third_party/imgui/examples/example_sdl2_opengl3/main.cpp index a7e7fc014cd..d748c1360bb 100644 --- a/third_party/imgui/examples/example_sdl_opengl3/main.cpp +++ b/third_party/imgui/examples/example_sdl2_opengl3/main.cpp @@ -1,10 +1,14 @@ // Dear ImGui: standalone example application for SDL2 + OpenGL // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" -#include "imgui_impl_sdl.h" +#include "imgui_impl_sdl2.h" #include "imgui_impl_opengl3.h" #include #include @@ -14,12 +18,15 @@ #include #endif +// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details. +#ifdef __EMSCRIPTEN__ +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif + // Main code int main(int, char**) { // Setup SDL - // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems, - // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to latest version of SDL is recommended!) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); @@ -50,12 +57,23 @@ int main(int, char**) SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); #endif + // From 2.0.18: Enable native IME. +#ifdef SDL_HINT_IME_SHOW_UI + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); +#endif + // Create window with graphics context SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(1); // Enable vsync @@ -64,12 +82,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForOpenGL(window, gl_context); @@ -78,17 +96,19 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -97,12 +117,19 @@ int main(int, char**) // Main loop bool done = false; +#ifdef __EMSCRIPTEN__ + // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. + // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. + io.IniFilename = nullptr; + EMSCRIPTEN_MAINLOOP_BEGIN +#else while (!done) +#endif { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) @@ -123,7 +150,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -142,7 +169,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -164,6 +191,9 @@ int main(int, char**) ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(window); } +#ifdef __EMSCRIPTEN__ + EMSCRIPTEN_MAINLOOP_END; +#endif // Cleanup ImGui_ImplOpenGL3_Shutdown(); diff --git a/third_party/imgui/examples/example_sdl_sdlrenderer/Makefile b/third_party/imgui/examples/example_sdl2_sdlrenderer2/Makefile similarity index 90% rename from third_party/imgui/examples/example_sdl_sdlrenderer/Makefile rename to third_party/imgui/examples/example_sdl2_sdlrenderer2/Makefile index 5667789af03..5820d9bc718 100644 --- a/third_party/imgui/examples/example_sdl_sdlrenderer/Makefile +++ b/third_party/imgui/examples/example_sdl2_sdlrenderer2/Makefile @@ -14,15 +14,15 @@ #CXX = g++ #CXX = clang++ -EXE = example_sdl_sdlrenderer +EXE = example_sdl2_sdlrenderer2 IMGUI_DIR = ../.. SOURCES = main.cpp SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp -SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl.cpp $(IMGUI_DIR)/backends/imgui_impl_sdlrenderer.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl2.cpp $(IMGUI_DIR)/backends/imgui_impl_sdlrenderer2.cpp OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) UNAME_S := $(shell uname -s) -CXXFLAGS = -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CXXFLAGS += -g -Wall -Wformat LIBS = diff --git a/third_party/imgui/examples/example_sdl2_sdlrenderer2/README.md b/third_party/imgui/examples/example_sdl2_sdlrenderer2/README.md new file mode 100644 index 00000000000..ef6fe85a53b --- /dev/null +++ b/third_party/imgui/examples/example_sdl2_sdlrenderer2/README.md @@ -0,0 +1,25 @@ + +# How to Build + +- On Windows with Visual Studio's CLI + +``` +set SDL2_DIR=path_to_your_sdl2_folder +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_sdlrenderer2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl2_sdlrenderer.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib /subsystem:console +# ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries +# or for 64-bit: +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_sdlrenderer2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl2_sdlrenderer.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib /subsystem:console +``` + +- On Linux and similar Unixes + +``` +c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../../backends/imgui_impl_sdl2.cpp ../../backends/imgui_impl_sdlrenderer2.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL +``` + +- On Mac OS X + +``` +brew install sdl2 +c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../../backends/imgui_impl_sdl2.cpp ../../backends/imgui_impl_sdlrenderer2.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl +``` diff --git a/third_party/imgui/examples/example_sdl2_sdlrenderer2/build_win32.bat b/third_party/imgui/examples/example_sdl2_sdlrenderer2/build_win32.bat new file mode 100644 index 00000000000..e311bfcd0fa --- /dev/null +++ b/third_party/imgui/examples/example_sdl2_sdlrenderer2/build_win32.bat @@ -0,0 +1,8 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@set OUT_DIR=Debug +@set OUT_EXE=example_sdl2_sdlrenderer_ +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_sdlrenderer2.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_sdl_sdlrenderer/example_sdl_sdlrenderer.vcxproj b/third_party/imgui/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj similarity index 91% rename from third_party/imgui/examples/example_sdl_sdlrenderer/example_sdl_sdlrenderer.vcxproj rename to third_party/imgui/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj index 4d502ab67d5..cf2c890bba1 100644 --- a/third_party/imgui/examples/example_sdl_sdlrenderer/example_sdl_sdlrenderer.vcxproj +++ b/third_party/imgui/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj @@ -19,9 +19,10 @@ - {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741} - example_sdl_sdlrenderer + {0C0B2BEA-311F-473C-9652-87923EF639E3} + example_sdl2_sdlrenderer2 8.1 + example_sdl2_sdlrenderer2 @@ -91,6 +92,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -105,6 +107,7 @@ Level4 Disabled ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) true @@ -122,6 +125,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -142,6 +146,7 @@ true ..\..;..\..\backends;%SDL2_DIR%\include;%(AdditionalIncludeDirectories) false + /utf-8 %(AdditionalOptions) true @@ -160,22 +165,23 @@ - - + + - - + + + - \ No newline at end of file + diff --git a/third_party/imgui/examples/example_sdl_sdlrenderer/example_sdl_sdlrenderer.vcxproj.filters b/third_party/imgui/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj.filters similarity index 81% rename from third_party/imgui/examples/example_sdl_sdlrenderer/example_sdl_sdlrenderer.vcxproj.filters rename to third_party/imgui/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj.filters index 01e98fcbc93..5c6da42e337 100644 --- a/third_party/imgui/examples/example_sdl_sdlrenderer/example_sdl_sdlrenderer.vcxproj.filters +++ b/third_party/imgui/examples/example_sdl2_sdlrenderer2/example_sdl2_sdlrenderer2.vcxproj.filters @@ -28,10 +28,10 @@ imgui - + sources - + sources @@ -45,17 +45,20 @@ imgui - + sources - + sources - sources + imgui + + + imgui diff --git a/third_party/imgui/examples/example_sdl_sdlrenderer/main.cpp b/third_party/imgui/examples/example_sdl2_sdlrenderer2/main.cpp similarity index 74% rename from third_party/imgui/examples/example_sdl_sdlrenderer/main.cpp rename to third_party/imgui/examples/example_sdl2_sdlrenderer2/main.cpp index aee4a7855a7..bfba8fa6ac2 100644 --- a/third_party/imgui/examples/example_sdl_sdlrenderer/main.cpp +++ b/third_party/imgui/examples/example_sdl2_sdlrenderer2/main.cpp @@ -1,15 +1,18 @@ // Dear ImGui: standalone example application for SDL2 + SDL_Renderer // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) -// 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 -// Important to understand: SDL_Renderer is an _optional_ component of SDL. We do not recommend you use SDL_Renderer -// because it provide a rather limited API to the end-user. We provide this backend for the sake of completeness. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important to understand: SDL_Renderer is an _optional_ component of SDL2. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. #include "imgui.h" -#include "imgui_impl_sdl.h" -#include "imgui_impl_sdlrenderer.h" +#include "imgui_impl_sdl2.h" +#include "imgui_impl_sdlrenderer2.h" #include #include @@ -21,24 +24,30 @@ int main(int, char**) { // Setup SDL - // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems, - // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to latest version of SDL is recommended!) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } - // Setup window - SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); - SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + // From 2.0.18: Enable native IME. +#ifdef SDL_HINT_IME_SHOW_UI + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); +#endif - // Setup SDL_Renderer instance + // Create window with SDL_Renderer graphics context + SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); - if (renderer == NULL) + if (renderer == nullptr) { SDL_Log("Error creating SDL_Renderer!"); - return false; + return 0; } //SDL_RendererInfo info; //SDL_GetRendererInfo(renderer, &info); @@ -48,31 +57,32 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends - ImGui_ImplSDL2_InitForSDLRenderer(window); - ImGui_ImplSDLRenderer_Init(renderer); + ImGui_ImplSDL2_InitForSDLRenderer(window, renderer); + ImGui_ImplSDLRenderer2_Init(renderer); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -85,8 +95,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) @@ -99,15 +109,15 @@ int main(int, char**) } // Start the Dear ImGui frame - ImGui_ImplSDLRenderer_NewFrame(); - ImGui_ImplSDL2_NewFrame(window); + ImGui_ImplSDLRenderer2_NewFrame(); + ImGui_ImplSDL2_NewFrame(); ImGui::NewFrame(); // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -126,7 +136,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -142,14 +152,15 @@ int main(int, char**) // Rendering ImGui::Render(); + SDL_RenderSetScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); SDL_SetRenderDrawColor(renderer, (Uint8)(clear_color.x * 255), (Uint8)(clear_color.y * 255), (Uint8)(clear_color.z * 255), (Uint8)(clear_color.w * 255)); SDL_RenderClear(renderer); - ImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData()); + ImGui_ImplSDLRenderer2_RenderDrawData(ImGui::GetDrawData()); SDL_RenderPresent(renderer); } // Cleanup - ImGui_ImplSDLRenderer_Shutdown(); + ImGui_ImplSDLRenderer2_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); diff --git a/third_party/imgui/examples/example_sdl_vulkan/build_win32.bat b/third_party/imgui/examples/example_sdl2_vulkan/build_win32.bat similarity index 55% rename from third_party/imgui/examples/example_sdl_vulkan/build_win32.bat rename to third_party/imgui/examples/example_sdl2_vulkan/build_win32.bat index 21b5ea314be..8a4aefc223b 100644 --- a/third_party/imgui/examples/example_sdl_vulkan/build_win32.bat +++ b/third_party/imgui/examples/example_sdl2_vulkan/build_win32.bat @@ -1,10 +1,10 @@ @REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_EXE=example_sdl_vulkan +@set OUT_EXE=example_sdl2_vulkan @set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 SDL2.lib SDL2main.lib shell32.lib vulkan-1.lib @set OUT_DIR=Debug mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj b/third_party/imgui/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj similarity index 90% rename from third_party/imgui/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj rename to third_party/imgui/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj index 5cc3eab2a6a..ba6afaf72b7 100644 --- a/third_party/imgui/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj +++ b/third_party/imgui/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj @@ -20,7 +20,7 @@ {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3} - example_sdl_vulkan + example_sdl2_vulkan 8.1 @@ -91,6 +91,8 @@ Level4 Disabled ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -105,6 +107,8 @@ Level4 Disabled ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -122,6 +126,8 @@ true ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -142,6 +148,8 @@ true ..\..;..\..\backends;%VULKAN_SDK%\include;%SDL2_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL2;%(AdditionalIncludeDirectories) false + ImTextureID=ImU64;_MBCS;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -160,7 +168,7 @@ - + @@ -168,10 +176,11 @@ - + + diff --git a/third_party/imgui/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj.filters b/third_party/imgui/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj.filters similarity index 86% rename from third_party/imgui/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj.filters rename to third_party/imgui/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj.filters index 063a5936f1c..ab424851540 100644 --- a/third_party/imgui/examples/example_sdl_vulkan/example_sdl_vulkan.vcxproj.filters +++ b/third_party/imgui/examples/example_sdl2_vulkan/example_sdl2_vulkan.vcxproj.filters @@ -19,7 +19,7 @@ imgui - + sources @@ -32,7 +32,7 @@ imgui - sources + imgui @@ -45,7 +45,7 @@ imgui - + sources @@ -55,7 +55,10 @@ - sources + imgui + + + imgui \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl_vulkan/main.cpp b/third_party/imgui/examples/example_sdl2_vulkan/main.cpp similarity index 74% rename from third_party/imgui/examples/example_sdl_vulkan/main.cpp rename to third_party/imgui/examples/example_sdl2_vulkan/main.cpp index 2c01afef106..633f8bb8b69 100644 --- a/third_party/imgui/examples/example_sdl_vulkan/main.cpp +++ b/third_party/imgui/examples/example_sdl2_vulkan/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for SDL2 + Vulkan -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. @@ -10,20 +14,22 @@ // Read comments in imgui_impl_vulkan.h. #include "imgui.h" -#include "imgui_impl_sdl.h" +#include "imgui_impl_sdl2.h" #include "imgui_impl_vulkan.h" #include // printf, fprintf #include // abort #include #include #include +//#include -//#define IMGUI_UNLIMITED_FRAME_RATE +//#define APP_USE_UNLIMITED_FRAME_RATE #ifdef _DEBUG -#define IMGUI_VULKAN_DEBUG_REPORT +#define APP_USE_VULKAN_DEBUG_REPORT #endif -static VkAllocationCallbacks* g_Allocator = NULL; +// Data +static VkAllocationCallbacks* g_Allocator = nullptr; static VkInstance g_Instance = VK_NULL_HANDLE; static VkPhysicalDevice g_PhysicalDevice = VK_NULL_HANDLE; static VkDevice g_Device = VK_NULL_HANDLE; @@ -46,16 +52,53 @@ static void check_vk_result(VkResult err) abort(); } -#ifdef IMGUI_VULKAN_DEBUG_REPORT +#ifdef APP_USE_VULKAN_DEBUG_REPORT static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) { (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); return VK_FALSE; } -#endif // IMGUI_VULKAN_DEBUG_REPORT +#endif // APP_USE_VULKAN_DEBUG_REPORT + +static bool IsExtensionAvailable(const ImVector& properties, const char* extension) +{ + for (const VkExtensionProperties& p : properties) + if (strcmp(p.extensionName, extension) == 0) + return true; + return false; +} + +static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice() +{ + uint32_t gpu_count; + VkResult err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, nullptr); + check_vk_result(err); + IM_ASSERT(gpu_count > 0); + + ImVector gpus; + gpus.resize(gpu_count); + err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus.Data); + check_vk_result(err); + + // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers + // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple + // dedicated GPUs) is out of scope of this sample. + for (VkPhysicalDevice& device : gpus) + { + VkPhysicalDeviceProperties properties; + vkGetPhysicalDeviceProperties(device, &properties); + if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) + return device; + } + + // Use first GPU (Integrated) is a Discrete one is not available. + if (gpu_count > 0) + return gpus[0]; + return VK_NULL_HANDLE; +} -static void SetupVulkan(const char** extensions, uint32_t extensions_count) +static void SetupVulkan(ImVector instance_extensions) { VkResult err; @@ -63,80 +106,61 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) { VkInstanceCreateInfo create_info = {}; create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; - create_info.enabledExtensionCount = extensions_count; - create_info.ppEnabledExtensionNames = extensions; -#ifdef IMGUI_VULKAN_DEBUG_REPORT + + // Enumerate available extensions + uint32_t properties_count; + ImVector properties; + vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, nullptr); + properties.resize(properties_count); + err = vkEnumerateInstanceExtensionProperties(nullptr, &properties_count, properties.Data); + check_vk_result(err); + + // Enable required extensions + if (IsExtensionAvailable(properties, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) + instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); +#ifdef VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME + if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME)) + { + instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); + create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR; + } +#endif + // Enabling validation layers +#ifdef APP_USE_VULKAN_DEBUG_REPORT const char* layers[] = { "VK_LAYER_KHRONOS_validation" }; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = layers; - - // Enable debug report extension (we need additional storage, so we duplicate the user array to add our new extension to it) - const char** extensions_ext = (const char**)malloc(sizeof(const char*) * (extensions_count + 1)); - memcpy(extensions_ext, extensions, extensions_count * sizeof(const char*)); - extensions_ext[extensions_count] = "VK_EXT_debug_report"; - create_info.enabledExtensionCount = extensions_count + 1; - create_info.ppEnabledExtensionNames = extensions_ext; + instance_extensions.push_back("VK_EXT_debug_report"); +#endif // Create Vulkan Instance + create_info.enabledExtensionCount = (uint32_t)instance_extensions.Size; + create_info.ppEnabledExtensionNames = instance_extensions.Data; err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); check_vk_result(err); - free(extensions_ext); - - // Get the function pointer (required for any extensions) - auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); - IM_ASSERT(vkCreateDebugReportCallbackEXT != NULL); // Setup the debug report callback +#ifdef APP_USE_VULKAN_DEBUG_REPORT + auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); + IM_ASSERT(vkCreateDebugReportCallbackEXT != nullptr); VkDebugReportCallbackCreateInfoEXT debug_report_ci = {}; debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; debug_report_ci.pfnCallback = debug_report; - debug_report_ci.pUserData = NULL; + debug_report_ci.pUserData = nullptr; err = vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); check_vk_result(err); -#else - // Create Vulkan Instance without any debug feature - err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); - check_vk_result(err); - IM_UNUSED(g_DebugReport); #endif } - // Select GPU - { - uint32_t gpu_count; - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, NULL); - check_vk_result(err); - IM_ASSERT(gpu_count > 0); - - VkPhysicalDevice* gpus = (VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice) * gpu_count); - err = vkEnumeratePhysicalDevices(g_Instance, &gpu_count, gpus); - check_vk_result(err); - - // If a number >1 of GPUs got reported, find discrete GPU if present, or use first one available. This covers - // most common cases (multi-gpu/integrated+dedicated graphics). Handling more complicated setups (multiple - // dedicated GPUs) is out of scope of this sample. - int use_gpu = 0; - for (int i = 0; i < (int)gpu_count; i++) - { - VkPhysicalDeviceProperties properties; - vkGetPhysicalDeviceProperties(gpus[i], &properties); - if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) - { - use_gpu = i; - break; - } - } - - g_PhysicalDevice = gpus[use_gpu]; - free(gpus); - } + // Select Physical Device (GPU) + g_PhysicalDevice = SetupVulkan_SelectPhysicalDevice(); // Select graphics queue family { uint32_t count; - vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, NULL); + vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, nullptr); VkQueueFamilyProperties* queues = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties) * count); vkGetPhysicalDeviceQueueFamilyProperties(g_PhysicalDevice, &count, queues); for (uint32_t i = 0; i < count; i++) @@ -151,8 +175,20 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) // Create Logical Device (with 1 queue) { - int device_extension_count = 1; - const char* device_extensions[] = { "VK_KHR_swapchain" }; + ImVector device_extensions; + device_extensions.push_back("VK_KHR_swapchain"); + + // Enumerate physical device extension + uint32_t properties_count; + ImVector properties; + vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, nullptr); + properties.resize(properties_count); + vkEnumerateDeviceExtensionProperties(g_PhysicalDevice, nullptr, &properties_count, properties.Data); +#ifdef VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME + if (IsExtensionAvailable(properties, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME)) + device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME); +#endif + const float queue_priority[] = { 1.0f }; VkDeviceQueueCreateInfo queue_info[1] = {}; queue_info[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; @@ -163,33 +199,25 @@ static void SetupVulkan(const char** extensions, uint32_t extensions_count) create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; create_info.queueCreateInfoCount = sizeof(queue_info) / sizeof(queue_info[0]); create_info.pQueueCreateInfos = queue_info; - create_info.enabledExtensionCount = device_extension_count; - create_info.ppEnabledExtensionNames = device_extensions; + create_info.enabledExtensionCount = (uint32_t)device_extensions.Size; + create_info.ppEnabledExtensionNames = device_extensions.Data; err = vkCreateDevice(g_PhysicalDevice, &create_info, g_Allocator, &g_Device); check_vk_result(err); vkGetDeviceQueue(g_Device, g_QueueFamily, 0, &g_Queue); } // Create Descriptor Pool + // The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that) + // If you wish to load e.g. additional textures you may need to alter pools sizes. { VkDescriptorPoolSize pool_sizes[] = { - { VK_DESCRIPTOR_TYPE_SAMPLER, 1000 }, - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 }, - { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 }, - { VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 }, - { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 }, - { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 }, - { VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 } + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 }, }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; - pool_info.maxSets = 1000 * IM_ARRAYSIZE(pool_sizes); + pool_info.maxSets = 1; pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.pPoolSizes = pool_sizes; err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); @@ -218,7 +246,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); // Select Present Mode -#ifdef IMGUI_UNLIMITED_FRAME_RATE +#ifdef APP_UNLIMITED_FRAME_RATE VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; #else VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; @@ -235,11 +263,11 @@ static void CleanupVulkan() { vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); -#ifdef IMGUI_VULKAN_DEBUG_REPORT +#ifdef APP_USE_VULKAN_DEBUG_REPORT // Remove the debug report callback auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT"); vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator); -#endif // IMGUI_VULKAN_DEBUG_REPORT +#endif // APP_USE_VULKAN_DEBUG_REPORT vkDestroyDevice(g_Device, g_Allocator); vkDestroyInstance(g_Instance, g_Allocator); @@ -336,9 +364,10 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd) return; } check_vk_result(err); - wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores + wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores } +// Main code int main(int, char**) { // Setup SDL @@ -348,17 +377,26 @@ int main(int, char**) return -1; } - // Setup window + // From 2.0.18: Enable native IME. +#ifdef SDL_HINT_IME_SHOW_UI + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); +#endif + + // Create window with Vulkan graphics context SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } - // Setup Vulkan + ImVector extensions; uint32_t extensions_count = 0; - SDL_Vulkan_GetInstanceExtensions(window, &extensions_count, NULL); - const char** extensions = new const char*[extensions_count]; - SDL_Vulkan_GetInstanceExtensions(window, &extensions_count, extensions); - SetupVulkan(extensions, extensions_count); - delete[] extensions; + SDL_Vulkan_GetInstanceExtensions(window, &extensions_count, nullptr); + extensions.resize(extensions_count); + SDL_Vulkan_GetInstanceExtensions(window, &extensions_count, extensions.Data); + SetupVulkan(extensions); // Create Window Surface VkSurfaceKHR surface; @@ -379,12 +417,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplSDL2_InitForVulkan(window); @@ -396,56 +434,30 @@ int main(int, char**) init_info.Queue = g_Queue; init_info.PipelineCache = g_PipelineCache; init_info.DescriptorPool = g_DescriptorPool; - init_info.Allocator = g_Allocator; + init_info.RenderPass = wd->RenderPass; + init_info.Subpass = 0; init_info.MinImageCount = g_MinImageCount; init_info.ImageCount = wd->ImageCount; + init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; + init_info.Allocator = g_Allocator; init_info.CheckVkResultFn = check_vk_result; - ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); + ImGui_ImplVulkan_Init(&init_info); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); - - // Upload Fonts - { - // Use any command queue - VkCommandPool command_pool = wd->Frames[wd->FrameIndex].CommandPool; - VkCommandBuffer command_buffer = wd->Frames[wd->FrameIndex].CommandBuffer; - - err = vkResetCommandPool(g_Device, command_pool, 0); - check_vk_result(err); - VkCommandBufferBeginInfo begin_info = {}; - begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; - begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - err = vkBeginCommandBuffer(command_buffer, &begin_info); - check_vk_result(err); - - ImGui_ImplVulkan_CreateFontsTexture(command_buffer); - - VkSubmitInfo end_info = {}; - end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; - end_info.commandBufferCount = 1; - end_info.pCommandBuffers = &command_buffer; - err = vkEndCommandBuffer(command_buffer); - check_vk_result(err); - err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE); - check_vk_result(err); - - err = vkDeviceWaitIdle(g_Device); - check_vk_result(err); - ImGui_ImplVulkan_DestroyFontUploadObjects(); - } + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -458,8 +470,8 @@ int main(int, char**) { // Poll and handle events (inputs, window resize, etc.) // 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. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) @@ -494,7 +506,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -513,7 +525,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } diff --git a/third_party/imgui/examples/example_sdl3_opengl3/Makefile b/third_party/imgui/examples/example_sdl3_opengl3/Makefile new file mode 100644 index 00000000000..3a00a31e70f --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_opengl3/Makefile @@ -0,0 +1,84 @@ +# +# Cross Platform Makefile +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# +# You will need SDL3 (http://www.libsdl.org) which is still unreleased/unpackaged. + +#CXX = g++ +#CXX = clang++ + +EXE = example_sdl3_opengl3 +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) +LINUX_GL_LIBS = -lGL + +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## OPENGL ES +##--------------------------------------------------------------------- + +## This assumes a GL ES library available in the system, e.g. libGLESv2.so +# CXXFLAGS += -DIMGUI_IMPL_OPENGL_ES2 +# LINUX_GL_LIBS = -lGLESv2 +## If you're on a Raspberry Pi and want to use the legacy drivers, +## use the following instead: +# LINUX_GL_LIBS = -L/opt/vc/lib -lbrcmGLESv2 + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + LIBS += $(LINUX_GL_LIBS) -ldl `sdl3-config --libs` + + CXXFLAGS += `sdl3-config --cflags` + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl3-config --libs` + LIBS += -L/usr/local/lib -L/opt/local/lib + + CXXFLAGS += `sdl3-config --cflags` + CXXFLAGS += -I/usr/local/include -I/opt/local/include + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(OS), Windows_NT) + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl3` + + CXXFLAGS += `pkg-config --cflags sdl3` + CFLAGS = $(CXXFLAGS) +endif + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/third_party/imgui/examples/example_sdl3_opengl3/Makefile.emscripten b/third_party/imgui/examples/example_sdl3_opengl3/Makefile.emscripten new file mode 100644 index 00000000000..9e9ffd6034f --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_opengl3/Makefile.emscripten @@ -0,0 +1,96 @@ + +# IMPORTANT: SDL3 IS IN DEVELOPMENT, AS OF 2023-05-30, EMSCRIPTEN DOESN'T SUPPORT SDL3 YET. +# WE ARE LEAVING THIS MAKEFILE AROUND FOR THE DAY IT WILL SUPPORT IT. + +# +# Makefile to use with SDL+emscripten +# See https://emscripten.org/docs/getting_started/downloads.html +# for installation instructions. +# +# This Makefile assumes you have loaded emscripten's environment. +# (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead) +# +# Running `make -f Makefile.emscripten` will produce three files: +# - web/index.html +# - web/index.js +# - web/index.wasm +# +# All three are needed to run the demo. + +CC = emcc +CXX = em++ +WEB_DIR = web +EXE = $(WEB_DIR)/index.html +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp $(IMGUI_DIR)/backends/imgui_impl_opengl3.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) +CPPFLAGS = +LDFLAGS = +EMS = + +##--------------------------------------------------------------------- +## EMSCRIPTEN OPTIONS +##--------------------------------------------------------------------- + +# ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only) +EMS += -s USE_SDL=2 +EMS += -s DISABLE_EXCEPTION_CATCHING=1 +LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1 + +# Uncomment next line to fix possible rendering bugs with Emscripten version older then 1.39.0 (https://github.com/ocornut/imgui/issues/2877) +#EMS += -s BINARYEN_TRAP_MODE=clamp +#EMS += -s SAFE_HEAP=1 ## Adds overhead + +# Emscripten allows preloading a file or folder to be accessible at runtime. +# The Makefile for this example project suggests embedding the misc/fonts/ folder into our application, it will then be accessible as "/fonts" +# See documentation for more details: https://emscripten.org/docs/porting/files/packaging_files.html +# (Default value is 0. Set to 1 to enable file-system and include the misc/fonts/ folder as part of the build.) +USE_FILE_SYSTEM ?= 0 +ifeq ($(USE_FILE_SYSTEM), 0) +LDFLAGS += -s NO_FILESYSTEM=1 +CPPFLAGS += -DIMGUI_DISABLE_FILE_FUNCTIONS +endif +ifeq ($(USE_FILE_SYSTEM), 1) +LDFLAGS += --no-heap-copy --preload-file ../../misc/fonts@/fonts +endif + +##--------------------------------------------------------------------- +## FINAL BUILD FLAGS +##--------------------------------------------------------------------- + +CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +#CPPFLAGS += -g +CPPFLAGS += -Wall -Wformat -Os $(EMS) +LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html +LDFLAGS += $(EMS) + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(EXE) + +$(WEB_DIR): + mkdir $@ + +serve: all + python3 -m http.server -d $(WEB_DIR) + +$(EXE): $(OBJS) $(WEB_DIR) + $(CXX) -o $@ $(OBJS) $(LDFLAGS) + +clean: + rm -rf $(OBJS) $(WEB_DIR) diff --git a/third_party/imgui/examples/example_sdl3_opengl3/README.md b/third_party/imgui/examples/example_sdl3_opengl3/README.md new file mode 100644 index 00000000000..5828e4bfc71 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_opengl3/README.md @@ -0,0 +1,40 @@ + +# How to Build + +## Windows with Visual Studio's IDE + +Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) if necessary. + +## Windows with Visual Studio's CLI + +Use build_win32.bat or directly: +``` +set SDL2_DIR=path_to_your_sdl3_folder +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL3.lib opengl32.lib /subsystem:console +# ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries +# or for 64-bit: +cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL3.lib SDL2mainopengl32.lib /subsystem:console +``` + +## Linux and similar Unixes + +Use our Makefile or directly: +``` +c++ `sdl3-config --cflags` -I .. -I ../.. -I ../../backends + main.cpp ../../backends/imgui_impl_sdl3.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp + `sdl3-config --libs` -lGL -ldl +``` + +## macOS + +Use our Makefile or directly: +``` +brew install sdl3 +c++ `sdl3-config --cflags` -I .. -I ../.. -I ../../backends + main.cpp ../../backends/imgui_impl_sdl3.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp + `sdl3-config --libs` -framework OpenGl -framework CoreFoundation +``` + +## Emscripten + +As of 2023-05-30 Emscripten doesn't support SDL3 yet. diff --git a/third_party/imgui/examples/example_sdl3_opengl3/build_win32.bat b/third_party/imgui/examples/example_sdl3_opengl3/build_win32.bat new file mode 100644 index 00000000000..5b8d5f87136 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_opengl3/build_win32.bat @@ -0,0 +1,8 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@set OUT_DIR=Debug +@set OUT_EXE=example_sdl3_opengl3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib opengl32.lib shell32.lib +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj b/third_party/imgui/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj new file mode 100644 index 00000000000..051f87d764f --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj @@ -0,0 +1,187 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {84AAA301-84FE-428B-9E3E-817BC8123C0C} + example_sdl3_opengl3 + 8.1 + + + + Application + true + MultiByte + v140 + + + Application + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + + + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj.filters b/third_party/imgui/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj.filters new file mode 100644 index 00000000000..f365473c4a6 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_opengl3/example_sdl3_opengl3.vcxproj.filters @@ -0,0 +1,67 @@ + + + + + {20b90ce4-7fcb-4731-b9a0-075f875de82d} + + + {f18ab499-84e1-499f-8eff-9754361e0e52} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + sources + + + imgui + + + imgui + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + sources + + + + + + imgui + + + imgui + + + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl3_opengl3/main.cpp b/third_party/imgui/examples/example_sdl3_opengl3/main.cpp new file mode 100644 index 00000000000..da12589f8b5 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_opengl3/main.cpp @@ -0,0 +1,207 @@ +// Dear ImGui: standalone example application for SDL3 + OpenGL +// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#include "imgui.h" +#include "imgui_impl_sdl3.h" +#include "imgui_impl_opengl3.h" +#include +#include +#if defined(IMGUI_IMPL_OPENGL_ES2) +#include +#else +#include +#endif + +// This example doesn't compile with Emscripten yet! Awaiting SDL3 support. +#ifdef __EMSCRIPTEN__ +#include "../libs/emscripten/emscripten_mainloop_stub.h" +#endif + +// Main code +int main(int, char**) +{ + // Setup SDL + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD) != 0) + { + printf("Error: SDL_Init(): %s\n", SDL_GetError()); + return -1; + } + + // Decide GL+GLSL versions +#if defined(IMGUI_IMPL_OPENGL_ES2) + // GL ES 2.0 + GLSL 100 + const char* glsl_version = "#version 100"; + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); +#elif defined(__APPLE__) + // GL 3.2 Core + GLSL 150 + const char* glsl_version = "#version 150"; + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); +#else + // GL 3.0 + GLSL 130 + const char* glsl_version = "#version 130"; + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); +#endif + + // Enable native IME. + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); + + // Create window with graphics context + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); + SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); + Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", 1280, 720, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_GLContext gl_context = SDL_GL_CreateContext(window); + SDL_GL_MakeCurrent(window, gl_context); + SDL_GL_SetSwapInterval(1); // Enable vsync + SDL_ShowWindow(window); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup Platform/Renderer backends + ImGui_ImplSDL3_InitForOpenGL(window, gl_context); + ImGui_ImplOpenGL3_Init(glsl_version); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; +#ifdef __EMSCRIPTEN__ + // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. + // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. + io.IniFilename = nullptr; + EMSCRIPTEN_MAINLOOP_BEGIN +#else + while (!done) +#endif + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL3_ProcessEvent(&event); + if (event.type == SDL_EVENT_QUIT) + done = true; + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) + done = true; + } + + // Start the Dear ImGui frame + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); + glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + SDL_GL_SwapWindow(window); + } +#ifdef __EMSCRIPTEN__ + EMSCRIPTEN_MAINLOOP_END; +#endif + + // Cleanup + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + + SDL_GL_DeleteContext(gl_context); + SDL_DestroyWindow(window); + SDL_Quit(); + + return 0; +} diff --git a/third_party/imgui/examples/example_sdl3_sdlrenderer3/Makefile b/third_party/imgui/examples/example_sdl3_sdlrenderer3/Makefile new file mode 100644 index 00000000000..d0a73bf1648 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_sdlrenderer3/Makefile @@ -0,0 +1,73 @@ +# +# Cross Platform Makefile +# Compatible with MSYS2/MINGW, Ubuntu 14.04.1 and Mac OS X +# +# You will need SDL3 (http://www.libsdl.org) which is still unreleased/unpackaged. + +#CXX = g++ +#CXX = clang++ + +EXE = example_sdl3_sdlrenderer3 +IMGUI_DIR = ../.. +SOURCES = main.cpp +SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp +SOURCES += $(IMGUI_DIR)/backends/imgui_impl_sdl3.cpp $(IMGUI_DIR)/backends/imgui_impl_sdlrenderer3.cpp +OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) +UNAME_S := $(shell uname -s) +LINUX_GL_LIBS = -lGL + +CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends +CXXFLAGS += -g -Wall -Wformat +LIBS = + +##--------------------------------------------------------------------- +## BUILD FLAGS PER PLATFORM +##--------------------------------------------------------------------- + +ifeq ($(UNAME_S), Linux) #LINUX + ECHO_MESSAGE = "Linux" + LIBS += -ldl `sdl3-config --libs` + + CXXFLAGS += `sdl3-config --cflags` + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(UNAME_S), Darwin) #APPLE + ECHO_MESSAGE = "Mac OS X" + LIBS += -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo `sdl3-config --libs` + LIBS += -L/usr/local/lib -L/opt/local/lib + + CXXFLAGS += `sdl3-config --cflags` + CXXFLAGS += -I/usr/local/include -I/opt/local/include + CFLAGS = $(CXXFLAGS) +endif + +ifeq ($(OS), Windows_NT) + ECHO_MESSAGE = "MinGW" + LIBS += -lgdi32 -lopengl32 -limm32 `pkg-config --static --libs sdl3` + + CXXFLAGS += `pkg-config --cflags sdl3` + CFLAGS = $(CXXFLAGS) +endif + +##--------------------------------------------------------------------- +## BUILD RULES +##--------------------------------------------------------------------- + +%.o:%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +%.o:$(IMGUI_DIR)/backends/%.cpp + $(CXX) $(CXXFLAGS) -c -o $@ $< + +all: $(EXE) + @echo Build complete for $(ECHO_MESSAGE) + +$(EXE): $(OBJS) + $(CXX) -o $@ $^ $(CXXFLAGS) $(LIBS) + +clean: + rm -f $(EXE) $(OBJS) diff --git a/third_party/imgui/examples/example_sdl3_sdlrenderer3/build_win32.bat b/third_party/imgui/examples/example_sdl3_sdlrenderer3/build_win32.bat new file mode 100644 index 00000000000..7bc131a6af4 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_sdlrenderer3/build_win32.bat @@ -0,0 +1,8 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@set OUT_DIR=Debug +@set OUT_EXE=example_sdl3_sdlrenderer3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlrenderer3.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj b/third_party/imgui/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj new file mode 100644 index 00000000000..8b71324cc75 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj @@ -0,0 +1,186 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {C0290D21-3AD2-4A35-ABBC-A2F5F48326DA} + example_sdl3_opengl3 + 8.1 + + + + Application + true + MultiByte + v140 + + + Application + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + Application + false + true + MultiByte + v140 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + $(IncludePath) + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + Disabled + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + /utf-8 %(AdditionalOptions) + + + true + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + msvcrt.lib + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + + + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends;%SDL3_DIR%\include;$(VcpkgCurrentInstalledDir)include\SDL3;%(AdditionalIncludeDirectories) + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + opengl32.lib;SDL3.lib;%(AdditionalDependencies) + Console + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj.filters b/third_party/imgui/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj.filters new file mode 100644 index 00000000000..c41210d677a --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_sdlrenderer3/example_sdl3_sdlrenderer3.vcxproj.filters @@ -0,0 +1,64 @@ + + + + + {20b90ce4-7fcb-4731-b9a0-075f875de82d} + + + {f18ab499-84e1-499f-8eff-9754361e0e52} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + imgui + + + imgui + + + sources + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + + + + imgui + + + imgui + + + \ No newline at end of file diff --git a/third_party/imgui/examples/example_sdl3_sdlrenderer3/main.cpp b/third_party/imgui/examples/example_sdl3_sdlrenderer3/main.cpp new file mode 100644 index 00000000000..9740054e517 --- /dev/null +++ b/third_party/imgui/examples/example_sdl3_sdlrenderer3/main.cpp @@ -0,0 +1,178 @@ +// Dear ImGui: standalone example application for SDL3 + SDL_Renderer +// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// Important to understand: SDL_Renderer is an _optional_ component of SDL3. +// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. + +#include "imgui.h" +#include "imgui_impl_sdl3.h" +#include "imgui_impl_sdlrenderer3.h" +#include +#include +#if defined(IMGUI_IMPL_OPENGL_ES2) +#include +#else +#include +#endif + +// Main code +int main(int, char**) +{ + // Setup SDL + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMEPAD) != 0) + { + printf("Error: SDL_Init(): %s\n", SDL_GetError()); + return -1; + } + + // Enable native IME. + SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); + + // Create window with SDL_Renderer graphics context + Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN; + SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", 1280, 720, window_flags); + if (window == nullptr) + { + printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); + return -1; + } + SDL_Renderer* renderer = SDL_CreateRenderer(window, nullptr, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); + if (renderer == nullptr) + { + SDL_Log("Error: SDL_CreateRenderer(): %s\n", SDL_GetError()); + return -1; + } + SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_ShowWindow(window); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsLight(); + + // Setup Platform/Renderer backends + ImGui_ImplSDL3_InitForSDLRenderer(window, renderer); + ImGui_ImplSDLRenderer3_Init(renderer); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details. + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; +#ifdef __EMSCRIPTEN__ + // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file. + // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage. + io.IniFilename = nullptr; + EMSCRIPTEN_MAINLOOP_BEGIN +#else + while (!done) +#endif + { + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + SDL_Event event; + while (SDL_PollEvent(&event)) + { + ImGui_ImplSDL3_ProcessEvent(&event); + if (event.type == SDL_EVENT_QUIT) + done = true; + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window)) + done = true; + } + + // Start the Dear ImGui frame + ImGui_ImplSDLRenderer3_NewFrame(); + ImGui_ImplSDL3_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + //SDL_RenderSetScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); + SDL_SetRenderDrawColor(renderer, (Uint8)(clear_color.x * 255), (Uint8)(clear_color.y * 255), (Uint8)(clear_color.z * 255), (Uint8)(clear_color.w * 255)); + SDL_RenderClear(renderer); + ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData()); + SDL_RenderPresent(renderer); + } + + // Cleanup + ImGui_ImplSDLRenderer3_Shutdown(); + ImGui_ImplSDL3_Shutdown(); + ImGui::DestroyContext(); + + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + SDL_Quit(); + + return 0; +} diff --git a/third_party/imgui/examples/example_sdl_opengl2/README.md b/third_party/imgui/examples/example_sdl_opengl2/README.md deleted file mode 100644 index 2bf4d03adf9..00000000000 --- a/third_party/imgui/examples/example_sdl_opengl2/README.md +++ /dev/null @@ -1,29 +0,0 @@ - -# How to Build - -- On Windows with Visual Studio's IDE - -Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) if necessary. - -- On Windows with Visual Studio's CLI - -``` -set SDL2_DIR=path_to_your_sdl2_folder -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console -# ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries -# or for 64-bit: -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl2.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console -``` - -- On Linux and similar Unixes - -``` -c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL -``` - -- On Mac OS X - -``` -brew install sdl2 -c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl2.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl -``` diff --git a/third_party/imgui/examples/example_sdl_opengl3/README.md b/third_party/imgui/examples/example_sdl_opengl3/README.md deleted file mode 100644 index 06d4b2d337f..00000000000 --- a/third_party/imgui/examples/example_sdl_opengl3/README.md +++ /dev/null @@ -1,29 +0,0 @@ - -# How to Build - -- On Windows with Visual Studio's IDE - -Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) if necessary. - -- On Windows with Visual Studio's CLI - -``` -set SDL2_DIR=path_to_your_sdl2_folder -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console -# ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries -# or for 64-bit: -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_opengl3.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib opengl32.lib /subsystem:console -``` - -- On Linux and similar Unixes - -``` -c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL -ldl -``` - -- On Mac OS X - -``` -brew install sdl2 -c++ `sdl2-config --cflags` -I .. -I ../.. -I ../../backends main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_opengl3.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl -framework CoreFoundation -``` diff --git a/third_party/imgui/examples/example_sdl_sdlrenderer/README.md b/third_party/imgui/examples/example_sdl_sdlrenderer/README.md deleted file mode 100644 index 209f15acf05..00000000000 --- a/third_party/imgui/examples/example_sdl_sdlrenderer/README.md +++ /dev/null @@ -1,25 +0,0 @@ - -# How to Build - -- On Windows with Visual Studio's CLI - -``` -set SDL2_DIR=path_to_your_sdl2_folder -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_sdlrenderer.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_sdlrenderer.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib /subsystem:console -# ^^ include paths ^^ source files ^^ output exe ^^ output dir ^^ libraries -# or for 64-bit: -cl /Zi /MD /I.. /I..\.. /I%SDL2_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_sdlrenderer.cpp ..\..\imgui*.cpp /FeDebug/example_sdl_sdlrenderer.exe /FoDebug/ /link /libpath:%SDL2_DIR%\lib\x64 SDL2.lib SDL2main.lib /subsystem:console -``` - -- On Linux and similar Unixes - -``` -c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_sdlrenderer.cpp ../../imgui*.cpp `sdl2-config --libs` -lGL -``` - -- On Mac OS X - -``` -brew install sdl2 -c++ `sdl2-config --cflags` -I .. -I ../.. main.cpp ../../backends/imgui_impl_sdl.cpp ../../backends/imgui_impl_sdlrenderer.cpp ../../imgui*.cpp `sdl2-config --libs` -framework OpenGl -``` diff --git a/third_party/imgui/examples/example_sdl_sdlrenderer/build_win32.bat b/third_party/imgui/examples/example_sdl_sdlrenderer/build_win32.bat deleted file mode 100644 index 6c1b5fde054..00000000000 --- a/third_party/imgui/examples/example_sdl_sdlrenderer/build_win32.bat +++ /dev/null @@ -1,8 +0,0 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. -@set OUT_DIR=Debug -@set OUT_EXE=example_sdl_sdlrenderer_ -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl.cpp ..\..\backends\imgui_impl_sdlrenderer.cpp ..\..\imgui*.cpp -@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x86 SDL2.lib SDL2main.lib -mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/third_party/imgui/examples/example_win32_directx10/build_win32.bat b/third_party/imgui/examples/example_win32_directx10/build_win32.bat index fd742239cae..78a6e374d57 100644 --- a/third_party/imgui/examples/example_win32_directx10/build_win32.bat +++ b/third_party/imgui/examples/example_win32_directx10/build_win32.bat @@ -5,4 +5,4 @@ @set SOURCES=main.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\backends\imgui_impl_dx10.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d10.lib d3dcompiler.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj b/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj index e71cb0a79e8..d11aed88387 100644 --- a/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -87,6 +87,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories); + /utf-8 %(AdditionalOptions) true @@ -100,6 +101,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories); + /utf-8 %(AdditionalOptions) true @@ -116,6 +118,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories); false + /utf-8 %(AdditionalOptions) true @@ -134,6 +137,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories); false + /utf-8 %(AdditionalOptions) true @@ -162,6 +166,7 @@ + diff --git a/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters b/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters index 11ad8f90f06..33ab99b5189 100644 --- a/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters +++ b/third_party/imgui/examples/example_win32_directx10/example_win32_directx10.vcxproj.filters @@ -54,7 +54,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_win32_directx10/main.cpp b/third_party/imgui/examples/example_win32_directx10/main.cpp index ad88d1e9607..94d5e02d41b 100644 --- a/third_party/imgui/examples/example_win32_directx10/main.cpp +++ b/third_party/imgui/examples/example_win32_directx10/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for DirectX 10 -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" #include "imgui_impl_win32.h" @@ -10,9 +14,10 @@ #include // Data -static ID3D10Device* g_pd3dDevice = NULL; -static IDXGISwapChain* g_pSwapChain = NULL; -static ID3D10RenderTargetView* g_mainRenderTargetView = NULL; +static ID3D10Device* g_pd3dDevice = nullptr; +static IDXGISwapChain* g_pSwapChain = nullptr; +static UINT g_ResizeWidth = 0, g_ResizeHeight = 0; +static ID3D10RenderTargetView* g_mainRenderTargetView = nullptr; // Forward declarations of helper functions bool CreateDeviceD3D(HWND hWnd); @@ -26,15 +31,15 @@ int main(int, char**) { // Create application window //ImGui_ImplWin32_EnableDpiAwareness(); - WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - ::RegisterClassEx(&wc); - HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX10 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; + ::RegisterClassExW(&wc); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX10 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 1; } @@ -46,12 +51,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); @@ -60,17 +65,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -82,12 +88,9 @@ int main(int, char**) while (!done) { // Poll and handle messages (inputs, window resize, etc.) - // 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. + // See the WndProc() function below for our to dispatch events to the Win32 backend. MSG msg; - while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); @@ -97,6 +100,15 @@ int main(int, char**) if (done) break; + // Handle window resize (we don't resize directly in the WM_SIZE handler) + if (g_ResizeWidth != 0 && g_ResizeHeight != 0) + { + CleanupRenderTarget(); + g_pSwapChain->ResizeBuffers(0, g_ResizeWidth, g_ResizeHeight, DXGI_FORMAT_UNKNOWN, 0); + g_ResizeWidth = g_ResizeHeight = 0; + CreateRenderTarget(); + } + // Start the Dear ImGui frame ImGui_ImplDX10_NewFrame(); ImGui_ImplWin32_NewFrame(); @@ -106,7 +118,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -125,7 +137,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -142,7 +154,7 @@ int main(int, char**) // Rendering ImGui::Render(); const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; - g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL); + g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr); g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha); ImGui_ImplDX10_RenderDrawData(ImGui::GetDrawData()); @@ -156,7 +168,7 @@ int main(int, char**) CleanupDeviceD3D(); ::DestroyWindow(hwnd); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 0; } @@ -184,7 +196,10 @@ bool CreateDeviceD3D(HWND hWnd) UINT createDeviceFlags = 0; //createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; - if (D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice) != S_OK) + HRESULT res = D3D10CreateDeviceAndSwapChain(nullptr, D3D10_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice); + if (res == DXGI_ERROR_UNSUPPORTED) // Try high-performance WARP software driver if hardware is not available. + res = D3D10CreateDeviceAndSwapChain(nullptr, D3D10_DRIVER_TYPE_WARP, nullptr, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice); + if (res != S_OK) return false; CreateRenderTarget(); @@ -194,27 +209,31 @@ bool CreateDeviceD3D(HWND hWnd) void CleanupDeviceD3D() { CleanupRenderTarget(); - if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } + if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; } } void CreateRenderTarget() { ID3D10Texture2D* pBackBuffer; g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); - g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView); pBackBuffer->Release(); } void CleanupRenderTarget() { - if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } + if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; } } // Forward declare message handler from imgui_impl_win32.cpp extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Win32 message handler +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) @@ -223,12 +242,10 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) switch (msg) { case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) - { - CleanupRenderTarget(); - g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); - CreateRenderTarget(); - } + if (wParam == SIZE_MINIMIZED) + return 0; + g_ResizeWidth = (UINT)LOWORD(lParam); // Queue resize + g_ResizeHeight = (UINT)HIWORD(lParam); return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu @@ -238,5 +255,5 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) ::PostQuitMessage(0); return 0; } - return ::DefWindowProc(hWnd, msg, wParam, lParam); + return ::DefWindowProcW(hWnd, msg, wParam, lParam); } diff --git a/third_party/imgui/examples/example_win32_directx11/build_win32.bat b/third_party/imgui/examples/example_win32_directx11/build_win32.bat index b1cf7d1cb84..c9a717c60a6 100644 --- a/third_party/imgui/examples/example_win32_directx11/build_win32.bat +++ b/third_party/imgui/examples/example_win32_directx11/build_win32.bat @@ -5,5 +5,5 @@ @set SOURCES=main.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj b/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj index 273d351cb74..bace6a2c836 100644 --- a/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -86,6 +86,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories); + /utf-8 %(AdditionalOptions) true @@ -99,6 +100,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories); + /utf-8 %(AdditionalOptions) true @@ -115,6 +117,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories); false + /utf-8 %(AdditionalOptions) true @@ -133,6 +136,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories); false + /utf-8 %(AdditionalOptions) true @@ -161,6 +165,7 @@ + diff --git a/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters b/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters index 02cf18cabe6..63032a6aa58 100644 --- a/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters +++ b/third_party/imgui/examples/example_win32_directx11/example_win32_directx11.vcxproj.filters @@ -54,7 +54,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_win32_directx11/main.cpp b/third_party/imgui/examples/example_win32_directx11/main.cpp index 7f1b4b896a3..19422c152a5 100644 --- a/third_party/imgui/examples/example_win32_directx11/main.cpp +++ b/third_party/imgui/examples/example_win32_directx11/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for DirectX 11 -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" #include "imgui_impl_win32.h" @@ -9,10 +13,11 @@ #include // Data -static ID3D11Device* g_pd3dDevice = NULL; -static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; -static IDXGISwapChain* g_pSwapChain = NULL; -static ID3D11RenderTargetView* g_mainRenderTargetView = NULL; +static ID3D11Device* g_pd3dDevice = nullptr; +static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr; +static IDXGISwapChain* g_pSwapChain = nullptr; +static UINT g_ResizeWidth = 0, g_ResizeHeight = 0; +static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr; // Forward declarations of helper functions bool CreateDeviceD3D(HWND hWnd); @@ -26,15 +31,15 @@ int main(int, char**) { // Create application window //ImGui_ImplWin32_EnableDpiAwareness(); - WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - ::RegisterClassEx(&wc); - HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; + ::RegisterClassExW(&wc); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX11 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 1; } @@ -46,12 +51,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); @@ -60,17 +65,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -82,12 +88,9 @@ int main(int, char**) while (!done) { // Poll and handle messages (inputs, window resize, etc.) - // 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. + // See the WndProc() function below for our to dispatch events to the Win32 backend. MSG msg; - while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); @@ -97,6 +100,15 @@ int main(int, char**) if (done) break; + // Handle window resize (we don't resize directly in the WM_SIZE handler) + if (g_ResizeWidth != 0 && g_ResizeHeight != 0) + { + CleanupRenderTarget(); + g_pSwapChain->ResizeBuffers(0, g_ResizeWidth, g_ResizeHeight, DXGI_FORMAT_UNKNOWN, 0); + g_ResizeWidth = g_ResizeHeight = 0; + CreateRenderTarget(); + } + // Start the Dear ImGui frame ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); @@ -106,7 +118,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -125,7 +137,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -142,7 +154,7 @@ int main(int, char**) // Rendering ImGui::Render(); const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; - g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL); + g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr); g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); @@ -157,7 +169,7 @@ int main(int, char**) CleanupDeviceD3D(); ::DestroyWindow(hwnd); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 0; } @@ -187,7 +199,10 @@ bool CreateDeviceD3D(HWND hWnd) //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; D3D_FEATURE_LEVEL featureLevel; const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; - if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) + HRESULT res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); + if (res == DXGI_ERROR_UNSUPPORTED) // Try high-performance WARP software driver if hardware is not available. + res = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_WARP, nullptr, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext); + if (res != S_OK) return false; CreateRenderTarget(); @@ -197,28 +212,32 @@ bool CreateDeviceD3D(HWND hWnd) void CleanupDeviceD3D() { CleanupRenderTarget(); - if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } - if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } + if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = nullptr; } + if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = nullptr; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; } } void CreateRenderTarget() { ID3D11Texture2D* pBackBuffer; g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer)); - g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &g_mainRenderTargetView); pBackBuffer->Release(); } void CleanupRenderTarget() { - if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } + if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; } } // Forward declare message handler from imgui_impl_win32.cpp extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Win32 message handler +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) @@ -227,12 +246,10 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) switch (msg) { case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) - { - CleanupRenderTarget(); - g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); - CreateRenderTarget(); - } + if (wParam == SIZE_MINIMIZED) + return 0; + g_ResizeWidth = (UINT)LOWORD(lParam); // Queue resize + g_ResizeHeight = (UINT)HIWORD(lParam); return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu @@ -242,5 +259,5 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) ::PostQuitMessage(0); return 0; } - return ::DefWindowProc(hWnd, msg, wParam, lParam); + return ::DefWindowProcW(hWnd, msg, wParam, lParam); } diff --git a/third_party/imgui/examples/example_win32_directx12/build_win32.bat b/third_party/imgui/examples/example_win32_directx12/build_win32.bat index 48dadb29943..68e3c921e39 100644 --- a/third_party/imgui/examples/example_win32_directx12/build_win32.bat +++ b/third_party/imgui/examples/example_win32_directx12/build_win32.bat @@ -6,4 +6,4 @@ @set SOURCES=main.cpp ..\..\backends\imgui_impl_dx12.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp @set LIBS=d3d12.lib d3dcompiler.lib dxgi.lib mkdir Debug -cl /nologo /Zi /MD %INCLUDES% /D ImTextureID=ImU64 /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D ImTextureID=ImU64 /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj b/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj index 3fed30d9445..7b64371eff8 100644 --- a/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj +++ b/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj @@ -88,6 +88,7 @@ Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -102,6 +103,7 @@ Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -118,6 +120,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -136,6 +139,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories) ImTextureID=ImU64;_UNICODE;UNICODE;%(PreprocessorDefinitions) + /utf-8 %(AdditionalOptions) true @@ -164,8 +168,12 @@ + + + + diff --git a/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters b/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters index 91fc7343d89..23a99526f7d 100644 --- a/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters +++ b/third_party/imgui/examples/example_win32_directx12/example_win32_directx12.vcxproj.filters @@ -53,5 +53,13 @@ + + imgui + + + + + imgui + - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_win32_directx12/main.cpp b/third_party/imgui/examples/example_win32_directx12/main.cpp index 74bfef326df..b146129ecbf 100644 --- a/third_party/imgui/examples/example_win32_directx12/main.cpp +++ b/third_party/imgui/examples/example_win32_directx12/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for DirectX 12 -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp // Important: to compile on 32-bit systems, the DirectX12 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*. @@ -34,16 +38,16 @@ static FrameContext g_frameContext[NUM_FRAMES_IN_FLIGHT] = {}; static UINT g_frameIndex = 0; static int const NUM_BACK_BUFFERS = 3; -static ID3D12Device* g_pd3dDevice = NULL; -static ID3D12DescriptorHeap* g_pd3dRtvDescHeap = NULL; -static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = NULL; -static ID3D12CommandQueue* g_pd3dCommandQueue = NULL; -static ID3D12GraphicsCommandList* g_pd3dCommandList = NULL; -static ID3D12Fence* g_fence = NULL; -static HANDLE g_fenceEvent = NULL; +static ID3D12Device* g_pd3dDevice = nullptr; +static ID3D12DescriptorHeap* g_pd3dRtvDescHeap = nullptr; +static ID3D12DescriptorHeap* g_pd3dSrvDescHeap = nullptr; +static ID3D12CommandQueue* g_pd3dCommandQueue = nullptr; +static ID3D12GraphicsCommandList* g_pd3dCommandList = nullptr; +static ID3D12Fence* g_fence = nullptr; +static HANDLE g_fenceEvent = nullptr; static UINT64 g_fenceLastSignaledValue = 0; -static IDXGISwapChain3* g_pSwapChain = NULL; -static HANDLE g_hSwapChainWaitableObject = NULL; +static IDXGISwapChain3* g_pSwapChain = nullptr; +static HANDLE g_hSwapChainWaitableObject = nullptr; static ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {}; static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {}; @@ -61,15 +65,15 @@ int main(int, char**) { // Create application window //ImGui_ImplWin32_EnableDpiAwareness(); - WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - ::RegisterClassEx(&wc); - HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX12 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; + ::RegisterClassExW(&wc); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX12 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 1; } @@ -81,12 +85,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); @@ -98,17 +102,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -120,12 +125,9 @@ int main(int, char**) while (!done) { // Poll and handle messages (inputs, window resize, etc.) - // 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. + // See the WndProc() function below for our to dispatch events to the Win32 backend. MSG msg; - while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); @@ -144,7 +146,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -163,7 +165,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -191,13 +193,13 @@ int main(int, char**) barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - g_pd3dCommandList->Reset(frameCtx->CommandAllocator, NULL); + g_pd3dCommandList->Reset(frameCtx->CommandAllocator, nullptr); g_pd3dCommandList->ResourceBarrier(1, &barrier); // Render Dear ImGui graphics const float clear_color_with_alpha[4] = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w }; - g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], clear_color_with_alpha, 0, NULL); - g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, NULL); + g_pd3dCommandList->ClearRenderTargetView(g_mainRenderTargetDescriptor[backBufferIdx], clear_color_with_alpha, 0, nullptr); + g_pd3dCommandList->OMSetRenderTargets(1, &g_mainRenderTargetDescriptor[backBufferIdx], FALSE, nullptr); g_pd3dCommandList->SetDescriptorHeaps(1, &g_pd3dSrvDescHeap); ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), g_pd3dCommandList); barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; @@ -225,7 +227,7 @@ int main(int, char**) CleanupDeviceD3D(); ::DestroyWindow(hwnd); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 0; } @@ -254,21 +256,21 @@ bool CreateDeviceD3D(HWND hWnd) // [DEBUG] Enable debug interface #ifdef DX12_ENABLE_DEBUG_LAYER - ID3D12Debug* pdx12Debug = NULL; + ID3D12Debug* pdx12Debug = nullptr; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&pdx12Debug)))) pdx12Debug->EnableDebugLayer(); #endif // Create device D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; - if (D3D12CreateDevice(NULL, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK) + if (D3D12CreateDevice(nullptr, featureLevel, IID_PPV_ARGS(&g_pd3dDevice)) != S_OK) return false; // [DEBUG] Setup debug interface to break on any warnings/errors #ifdef DX12_ENABLE_DEBUG_LAYER - if (pdx12Debug != NULL) + if (pdx12Debug != nullptr) { - ID3D12InfoQueue* pInfoQueue = NULL; + ID3D12InfoQueue* pInfoQueue = nullptr; g_pd3dDevice->QueryInterface(IID_PPV_ARGS(&pInfoQueue)); pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true); pInfoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true); @@ -318,23 +320,23 @@ bool CreateDeviceD3D(HWND hWnd) if (g_pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_frameContext[i].CommandAllocator)) != S_OK) return false; - if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, NULL, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK || + if (g_pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_frameContext[0].CommandAllocator, nullptr, IID_PPV_ARGS(&g_pd3dCommandList)) != S_OK || g_pd3dCommandList->Close() != S_OK) return false; if (g_pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_fence)) != S_OK) return false; - g_fenceEvent = CreateEvent(NULL, FALSE, FALSE, NULL); - if (g_fenceEvent == NULL) + g_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + if (g_fenceEvent == nullptr) return false; { - IDXGIFactory4* dxgiFactory = NULL; - IDXGISwapChain1* swapChain1 = NULL; + IDXGIFactory4* dxgiFactory = nullptr; + IDXGISwapChain1* swapChain1 = nullptr; if (CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)) != S_OK) return false; - if (dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, NULL, NULL, &swapChain1) != S_OK) + if (dxgiFactory->CreateSwapChainForHwnd(g_pd3dCommandQueue, hWnd, &sd, nullptr, nullptr, &swapChain1) != S_OK) return false; if (swapChain1->QueryInterface(IID_PPV_ARGS(&g_pSwapChain)) != S_OK) return false; @@ -351,20 +353,20 @@ bool CreateDeviceD3D(HWND hWnd) void CleanupDeviceD3D() { CleanupRenderTarget(); - if (g_pSwapChain) { g_pSwapChain->SetFullscreenState(false, NULL); g_pSwapChain->Release(); g_pSwapChain = NULL; } - if (g_hSwapChainWaitableObject != NULL) { CloseHandle(g_hSwapChainWaitableObject); } + if (g_pSwapChain) { g_pSwapChain->SetFullscreenState(false, nullptr); g_pSwapChain->Release(); g_pSwapChain = nullptr; } + if (g_hSwapChainWaitableObject != nullptr) { CloseHandle(g_hSwapChainWaitableObject); } for (UINT i = 0; i < NUM_FRAMES_IN_FLIGHT; i++) - if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = NULL; } - if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = NULL; } - if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = NULL; } - if (g_pd3dRtvDescHeap) { g_pd3dRtvDescHeap->Release(); g_pd3dRtvDescHeap = NULL; } - if (g_pd3dSrvDescHeap) { g_pd3dSrvDescHeap->Release(); g_pd3dSrvDescHeap = NULL; } - if (g_fence) { g_fence->Release(); g_fence = NULL; } - if (g_fenceEvent) { CloseHandle(g_fenceEvent); g_fenceEvent = NULL; } - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } + if (g_frameContext[i].CommandAllocator) { g_frameContext[i].CommandAllocator->Release(); g_frameContext[i].CommandAllocator = nullptr; } + if (g_pd3dCommandQueue) { g_pd3dCommandQueue->Release(); g_pd3dCommandQueue = nullptr; } + if (g_pd3dCommandList) { g_pd3dCommandList->Release(); g_pd3dCommandList = nullptr; } + if (g_pd3dRtvDescHeap) { g_pd3dRtvDescHeap->Release(); g_pd3dRtvDescHeap = nullptr; } + if (g_pd3dSrvDescHeap) { g_pd3dSrvDescHeap->Release(); g_pd3dSrvDescHeap = nullptr; } + if (g_fence) { g_fence->Release(); g_fence = nullptr; } + if (g_fenceEvent) { CloseHandle(g_fenceEvent); g_fenceEvent = nullptr; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; } #ifdef DX12_ENABLE_DEBUG_LAYER - IDXGIDebug1* pDebug = NULL; + IDXGIDebug1* pDebug = nullptr; if (SUCCEEDED(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug)))) { pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_SUMMARY); @@ -377,9 +379,9 @@ void CreateRenderTarget() { for (UINT i = 0; i < NUM_BACK_BUFFERS; i++) { - ID3D12Resource* pBackBuffer = NULL; + ID3D12Resource* pBackBuffer = nullptr; g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&pBackBuffer)); - g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, g_mainRenderTargetDescriptor[i]); + g_pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, g_mainRenderTargetDescriptor[i]); g_mainRenderTargetResource[i] = pBackBuffer; } } @@ -389,7 +391,7 @@ void CleanupRenderTarget() WaitForLastSubmittedFrame(); for (UINT i = 0; i < NUM_BACK_BUFFERS; i++) - if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = NULL; } + if (g_mainRenderTargetResource[i]) { g_mainRenderTargetResource[i]->Release(); g_mainRenderTargetResource[i] = nullptr; } } void WaitForLastSubmittedFrame() @@ -413,7 +415,7 @@ FrameContext* WaitForNextFrameResources() UINT nextFrameIndex = g_frameIndex + 1; g_frameIndex = nextFrameIndex; - HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, NULL }; + HANDLE waitableObjects[] = { g_hSwapChainWaitableObject, nullptr }; DWORD numWaitableObjects = 1; FrameContext* frameCtx = &g_frameContext[nextFrameIndex % NUM_FRAMES_IN_FLIGHT]; @@ -435,6 +437,10 @@ FrameContext* WaitForNextFrameResources() extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Win32 message handler +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) @@ -443,7 +449,7 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) switch (msg) { case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) + if (g_pd3dDevice != nullptr && wParam != SIZE_MINIMIZED) { WaitForLastSubmittedFrame(); CleanupRenderTarget(); @@ -460,5 +466,5 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) ::PostQuitMessage(0); return 0; } - return ::DefWindowProc(hWnd, msg, wParam, lParam); + return ::DefWindowProcW(hWnd, msg, wParam, lParam); } diff --git a/third_party/imgui/examples/example_win32_directx9/build_win32.bat b/third_party/imgui/examples/example_win32_directx9/build_win32.bat index bbd4b13ca94..ece5ea1ba0a 100644 --- a/third_party/imgui/examples/example_win32_directx9/build_win32.bat +++ b/third_party/imgui/examples/example_win32_directx9/build_win32.bat @@ -5,4 +5,4 @@ @set SOURCES=main.cpp ..\..\backends\imgui_impl_dx9.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp @set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d9.lib mkdir %OUT_DIR% -cl /nologo /Zi /MD %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj b/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj index e01eca14620..8c3f99589bb 100644 --- a/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj +++ b/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj @@ -87,6 +87,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + /utf-8 %(AdditionalOptions) true @@ -100,6 +101,7 @@ Level4 Disabled ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; + /utf-8 %(AdditionalOptions) true @@ -116,6 +118,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; false + /utf-8 %(AdditionalOptions) true @@ -134,6 +137,7 @@ true ..\..;..\..\backends;%(AdditionalIncludeDirectories);$(DXSDK_DIR)Include; false + /utf-8 %(AdditionalOptions) true @@ -162,6 +166,7 @@ + diff --git a/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters b/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters index 9493970b64c..5ed89d6fde4 100644 --- a/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters +++ b/third_party/imgui/examples/example_win32_directx9/example_win32_directx9.vcxproj.filters @@ -55,7 +55,10 @@ - sources + imgui + + + imgui - + \ No newline at end of file diff --git a/third_party/imgui/examples/example_win32_directx9/main.cpp b/third_party/imgui/examples/example_win32_directx9/main.cpp index bdcd8b3e8c0..f36b3ea5859 100644 --- a/third_party/imgui/examples/example_win32_directx9/main.cpp +++ b/third_party/imgui/examples/example_win32_directx9/main.cpp @@ -1,6 +1,10 @@ // Dear ImGui: standalone example application for DirectX 9 -// 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 + +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp #include "imgui.h" #include "imgui_impl_dx9.h" @@ -9,8 +13,9 @@ #include // Data -static LPDIRECT3D9 g_pD3D = NULL; -static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; +static LPDIRECT3D9 g_pD3D = nullptr; +static LPDIRECT3DDEVICE9 g_pd3dDevice = nullptr; +static UINT g_ResizeWidth = 0, g_ResizeHeight = 0; static D3DPRESENT_PARAMETERS g_d3dpp = {}; // Forward declarations of helper functions @@ -24,15 +29,15 @@ int main(int, char**) { // Create application window //ImGui_ImplWin32_EnableDpiAwareness(); - WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; - ::RegisterClassEx(&wc); - HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX9 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); + WNDCLASSEXW wc = { sizeof(wc), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; + ::RegisterClassExW(&wc); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui DirectX9 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); // Initialize Direct3D if (!CreateDeviceD3D(hwnd)) { CleanupDeviceD3D(); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 1; } @@ -44,12 +49,12 @@ int main(int, char**) IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls - //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); // Setup Platform/Renderer backends ImGui_ImplWin32_Init(hwnd); @@ -58,17 +63,18 @@ int main(int, char**) // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. - // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); - //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); - //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); - //IM_ASSERT(font != NULL); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); // Our state bool show_demo_window = true; @@ -80,12 +86,9 @@ int main(int, char**) while (!done) { // Poll and handle messages (inputs, window resize, etc.) - // 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. + // See the WndProc() function below for our to dispatch events to the Win32 backend. MSG msg; - while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) + while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); @@ -95,6 +98,15 @@ int main(int, char**) if (done) break; + // Handle window resize (we don't resize directly in the WM_SIZE handler) + if (g_ResizeWidth != 0 && g_ResizeHeight != 0) + { + g_d3dpp.BackBufferWidth = g_ResizeWidth; + g_d3dpp.BackBufferHeight = g_ResizeHeight; + g_ResizeWidth = g_ResizeHeight = 0; + ResetDevice(); + } + // Start the Dear ImGui frame ImGui_ImplDX9_NewFrame(); ImGui_ImplWin32_NewFrame(); @@ -104,7 +116,7 @@ int main(int, char**) if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); - // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. { static float f = 0.0f; static int counter = 0; @@ -123,7 +135,7 @@ int main(int, char**) ImGui::SameLine(); ImGui::Text("counter = %d", counter); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::End(); } @@ -143,14 +155,14 @@ int main(int, char**) g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*clear_color.w*255.0f), (int)(clear_color.y*clear_color.w*255.0f), (int)(clear_color.z*clear_color.w*255.0f), (int)(clear_color.w*255.0f)); - g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); + g_pd3dDevice->Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); g_pd3dDevice->EndScene(); } - HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL); + HRESULT result = g_pd3dDevice->Present(nullptr, nullptr, nullptr, nullptr); // Handle loss of D3D9 device if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET) @@ -163,7 +175,7 @@ int main(int, char**) CleanupDeviceD3D(); ::DestroyWindow(hwnd); - ::UnregisterClass(wc.lpszClassName, wc.hInstance); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); return 0; } @@ -172,7 +184,7 @@ int main(int, char**) bool CreateDeviceD3D(HWND hWnd) { - if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) + if ((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == nullptr) return false; // Create the D3DDevice @@ -192,8 +204,8 @@ bool CreateDeviceD3D(HWND hWnd) void CleanupDeviceD3D() { - if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } - if (g_pD3D) { g_pD3D->Release(); g_pD3D = NULL; } + if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = nullptr; } + if (g_pD3D) { g_pD3D->Release(); g_pD3D = nullptr; } } void ResetDevice() @@ -209,6 +221,10 @@ void ResetDevice() extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Win32 message handler +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) @@ -217,12 +233,10 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) switch (msg) { case WM_SIZE: - if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) - { - g_d3dpp.BackBufferWidth = LOWORD(lParam); - g_d3dpp.BackBufferHeight = HIWORD(lParam); - ResetDevice(); - } + if (wParam == SIZE_MINIMIZED) + return 0; + g_ResizeWidth = (UINT)LOWORD(lParam); // Queue resize + g_ResizeHeight = (UINT)HIWORD(lParam); return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu @@ -232,5 +246,5 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) ::PostQuitMessage(0); return 0; } - return ::DefWindowProc(hWnd, msg, wParam, lParam); + return ::DefWindowProcW(hWnd, msg, wParam, lParam); } diff --git a/third_party/imgui/examples/example_win32_opengl3/build_win32.bat b/third_party/imgui/examples/example_win32_opengl3/build_win32.bat new file mode 100644 index 00000000000..48df0808708 --- /dev/null +++ b/third_party/imgui/examples/example_win32_opengl3/build_win32.bat @@ -0,0 +1,8 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. +@set OUT_DIR=Debug +@set OUT_EXE=example_win32_opengl3 +@set INCLUDES=/I..\.. /I..\..\backends +@set SOURCES=main.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp +@set LIBS=opengl32.lib +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/third_party/imgui/examples/example_win32_opengl3/example_win32_opengl3.vcxproj b/third_party/imgui/examples/example_win32_opengl3/example_win32_opengl3.vcxproj new file mode 100644 index 00000000000..98fc38fd34d --- /dev/null +++ b/third_party/imgui/examples/example_win32_opengl3/example_win32_opengl3.vcxproj @@ -0,0 +1,176 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {C624E5FF-D4FE-4D35-9164-B8A91864F98E} + example_win32_opengl2 + 8.1 + + + + Application + true + Unicode + v140 + + + Application + true + Unicode + v140 + + + Application + false + true + Unicode + v140 + + + Application + false + true + Unicode + v140 + + + + + + + + + + + + + + + + + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + $(ProjectDir)$(Configuration)\ + $(ProjectDir)$(Configuration)\ + + + + Level4 + Disabled + ..\..;..\..\backends; + /utf-8 %(AdditionalOptions) + + + true + %(AdditionalLibraryDirectories) + opengl32.lib;%(AdditionalDependencies) + Console + + + + + Level4 + Disabled + ..\..;..\..\backends; + /utf-8 %(AdditionalOptions) + + + true + %(AdditionalLibraryDirectories) + opengl32.lib;%(AdditionalDependencies) + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends; + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %(AdditionalLibraryDirectories) + opengl32.lib;%(AdditionalDependencies) + Console + + + + + Level4 + MaxSpeed + true + true + ..\..;..\..\backends; + false + /utf-8 %(AdditionalOptions) + + + true + true + true + %(AdditionalLibraryDirectories) + opengl32.lib;%(AdditionalDependencies) + Console + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/third_party/imgui/examples/example_win32_opengl3/example_win32_opengl3.vcxproj.filters b/third_party/imgui/examples/example_win32_opengl3/example_win32_opengl3.vcxproj.filters new file mode 100644 index 00000000000..47ed299bc70 --- /dev/null +++ b/third_party/imgui/examples/example_win32_opengl3/example_win32_opengl3.vcxproj.filters @@ -0,0 +1,64 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {a82cba23-9de0-45c2-b1e3-2eb1666702de} + + + + + sources + + + imgui + + + imgui + + + imgui + + + imgui + + + sources + + + imgui + + + sources + + + + + imgui + + + imgui + + + imgui + + + sources + + + sources + + + sources + + + + + + sources + + + \ No newline at end of file diff --git a/third_party/imgui/examples/example_win32_opengl3/main.cpp b/third_party/imgui/examples/example_win32_opengl3/main.cpp new file mode 100644 index 00000000000..594931dca83 --- /dev/null +++ b/third_party/imgui/examples/example_win32_opengl3/main.cpp @@ -0,0 +1,238 @@ +// Dear ImGui: standalone example application for Win32 + OpenGL 3 + +// 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 is provided for completeness, however it is strongly recommended you use OpenGL with SDL or GLFW. + +#include "imgui.h" +#include "imgui_impl_opengl3.h" +#include "imgui_impl_win32.h" +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +#include + +// Data stored per platform window +struct WGL_WindowData { HDC hDC; }; + +// Data +static HGLRC g_hRC; +static WGL_WindowData g_MainWindow; +static int g_Width; +static int g_Height; + +// Forward declarations of helper functions +bool CreateDeviceWGL(HWND hWnd, WGL_WindowData* data); +void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data); +void ResetDeviceWGL(); +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Main code +int main(int, char**) +{ + // Create application window + //ImGui_ImplWin32_EnableDpiAwareness(); + WNDCLASSEXW wc = { sizeof(wc), CS_OWNDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr }; + ::RegisterClassExW(&wc); + HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+OpenGL3 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr); + + // Initialize OpenGL + if (!CreateDeviceWGL(hwnd, &g_MainWindow)) + { + CleanupDeviceWGL(hwnd, &g_MainWindow); + ::DestroyWindow(hwnd); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); + return 1; + } + wglMakeCurrent(g_MainWindow.hDC, g_hRC); + + // Show the window + ::ShowWindow(hwnd, SW_SHOWDEFAULT); + ::UpdateWindow(hwnd); + + // Setup Dear ImGui context + IMGUI_CHECKVERSION(); + ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); (void)io; + io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls + io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + + // Setup Platform/Renderer backends + ImGui_ImplWin32_InitForOpenGL(hwnd); + ImGui_ImplOpenGL3_Init(); + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); + + // Our state + bool show_demo_window = true; + bool show_another_window = false; + ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); + + // Main loop + bool done = false; + while (!done) + { + // Poll and handle messages (inputs, window resize, etc.) + // See the WndProc() function below for our to dispatch events to the Win32 backend. + MSG msg; + while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) + { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + if (msg.message == WM_QUIT) + done = true; + } + if (done) + break; + + // Start the Dear ImGui frame + ImGui_ImplOpenGL3_NewFrame(); + ImGui_ImplWin32_NewFrame(); + ImGui::NewFrame(); + + // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). + if (show_demo_window) + ImGui::ShowDemoWindow(&show_demo_window); + + // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window. + { + static float f = 0.0f; + static int counter = 0; + + ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. + + ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) + ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state + ImGui::Checkbox("Another Window", &show_another_window); + + ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f + ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color + + if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) + counter++; + ImGui::SameLine(); + ImGui::Text("counter = %d", counter); + + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); + ImGui::End(); + } + + // 3. Show another simple window. + if (show_another_window) + { + ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked) + ImGui::Text("Hello from another window!"); + if (ImGui::Button("Close Me")) + show_another_window = false; + ImGui::End(); + } + + // Rendering + ImGui::Render(); + glViewport(0, 0, g_Width, g_Height); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); + + // Present + ::SwapBuffers(g_MainWindow.hDC); + } + + ImGui_ImplOpenGL3_Shutdown(); + ImGui_ImplWin32_Shutdown(); + ImGui::DestroyContext(); + + CleanupDeviceWGL(hwnd, &g_MainWindow); + wglDeleteContext(g_hRC); + ::DestroyWindow(hwnd); + ::UnregisterClassW(wc.lpszClassName, wc.hInstance); + + return 0; +} + +// Helper functions +bool CreateDeviceWGL(HWND hWnd, WGL_WindowData* data) +{ + HDC hDc = ::GetDC(hWnd); + PIXELFORMATDESCRIPTOR pfd = { 0 }; + pfd.nSize = sizeof(pfd); + pfd.nVersion = 1; + pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; + pfd.iPixelType = PFD_TYPE_RGBA; + pfd.cColorBits = 32; + + const int pf = ::ChoosePixelFormat(hDc, &pfd); + if (pf == 0) + return false; + if (::SetPixelFormat(hDc, pf, &pfd) == FALSE) + return false; + ::ReleaseDC(hWnd, hDc); + + data->hDC = ::GetDC(hWnd); + if (!g_hRC) + g_hRC = wglCreateContext(data->hDC); + return true; +} + +void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data) +{ + wglMakeCurrent(nullptr, nullptr); + ::ReleaseDC(hWnd, data->hDC); +} + +// Forward declare message handler from imgui_impl_win32.cpp +extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); + +// Win32 message handler +// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. +// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. +// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. +// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. +LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) + return true; + + switch (msg) + { + case WM_SIZE: + if (wParam != SIZE_MINIMIZED) + { + g_Width = LOWORD(lParam); + g_Height = HIWORD(lParam); + } + return 0; + case WM_SYSCOMMAND: + if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu + return 0; + break; + case WM_DESTROY: + ::PostQuitMessage(0); + return 0; + } + return ::DefWindowProcW(hWnd, msg, wParam, lParam); +} diff --git a/third_party/imgui/examples/imgui_examples.sln b/third_party/imgui/examples/imgui_examples.sln index df1006d54e6..071bcbd6382 100644 --- a/third_party/imgui/examples/imgui_examples.sln +++ b/third_party/imgui/examples/imgui_examples.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32616.157 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_directx9", "example_win32_directx9\example_win32_directx9.vcxproj", "{4165A294-21F2-44CA-9B38-E3F935ABADF5}" EndProject @@ -17,6 +17,18 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_glfw_opengl3", "exa EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_glfw_vulkan", "example_glfw_vulkan\example_glfw_vulkan.vcxproj", "{57E2DF5A-6FC8-45BB-99DD-91A18C646E80}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_directx11", "example_sdl2_directx11\example_sdl2_directx11.vcxproj", "{9E1987E3-1F19-45CA-B9C9-D31E791836D8}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_opengl2", "example_sdl2_opengl2\example_sdl2_opengl2.vcxproj", "{2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_opengl3", "example_sdl2_opengl3\example_sdl2_opengl3.vcxproj", "{BBAEB705-1669-40F3-8567-04CF6A991F4C}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_vulkan", "example_sdl2_vulkan\example_sdl2_vulkan.vcxproj", "{BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_win32_opengl3", "example_win32_opengl3\example_win32_opengl3.vcxproj", "{C624E5FF-D4FE-4D35-9164-B8A91864F98E}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example_sdl2_sdlrenderer2", "example_sdl2_sdlrenderer2\example_sdl2_sdlrenderer2.vcxproj", "{0C0B2BEA-311F-473C-9652-87923EF639E3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -81,8 +93,59 @@ Global {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Release|Win32.Build.0 = Release|Win32 {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Release|x64.ActiveCfg = Release|x64 {57E2DF5A-6FC8-45BB-99DD-91A18C646E80}.Release|x64.Build.0 = Release|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|Win32.ActiveCfg = Debug|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|Win32.Build.0 = Debug|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|x64.ActiveCfg = Debug|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Debug|x64.Build.0 = Debug|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|Win32.ActiveCfg = Release|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|Win32.Build.0 = Release|Win32 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|x64.ActiveCfg = Release|x64 + {9E1987E3-1F19-45CA-B9C9-D31E791836D8}.Release|x64.Build.0 = Release|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|Win32.ActiveCfg = Debug|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|Win32.Build.0 = Debug|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|x64.ActiveCfg = Debug|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Debug|x64.Build.0 = Debug|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|Win32.ActiveCfg = Release|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|Win32.Build.0 = Release|Win32 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|x64.ActiveCfg = Release|x64 + {2AE17FDE-F7F3-4CAC-ADAB-0710EDA4F741}.Release|x64.Build.0 = Release|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|Win32.ActiveCfg = Debug|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|Win32.Build.0 = Debug|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|x64.ActiveCfg = Debug|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Debug|x64.Build.0 = Debug|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|Win32.ActiveCfg = Release|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|Win32.Build.0 = Release|Win32 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|x64.ActiveCfg = Release|x64 + {BBAEB705-1669-40F3-8567-04CF6A991F4C}.Release|x64.Build.0 = Release|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|Win32.ActiveCfg = Debug|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|Win32.Build.0 = Debug|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|x64.ActiveCfg = Debug|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Debug|x64.Build.0 = Debug|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|Win32.ActiveCfg = Release|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|Win32.Build.0 = Release|Win32 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|x64.ActiveCfg = Release|x64 + {BAE3D0B5-9695-4EB1-AD0F-75890EB4A3B3}.Release|x64.Build.0 = Release|x64 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Debug|Win32.ActiveCfg = Debug|Win32 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Debug|Win32.Build.0 = Debug|Win32 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Debug|x64.ActiveCfg = Debug|x64 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Debug|x64.Build.0 = Debug|x64 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Release|Win32.ActiveCfg = Release|Win32 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Release|Win32.Build.0 = Release|Win32 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Release|x64.ActiveCfg = Release|x64 + {C624E5FF-D4FE-4D35-9164-B8A91864F98E}.Release|x64.Build.0 = Release|x64 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Debug|Win32.ActiveCfg = Debug|Win32 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Debug|Win32.Build.0 = Debug|Win32 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Debug|x64.ActiveCfg = Debug|x64 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Debug|x64.Build.0 = Debug|x64 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|Win32.ActiveCfg = Release|Win32 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|Win32.Build.0 = Release|Win32 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.ActiveCfg = Release|x64 + {0C0B2BEA-311F-473C-9652-87923EF639E3}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B1ACFD20-A0A9-4A4C-ADBA-E7608F0E2BEE} + EndGlobalSection EndGlobal diff --git a/third_party/imgui/examples/libs/emscripten/emscripten_mainloop_stub.h b/third_party/imgui/examples/libs/emscripten/emscripten_mainloop_stub.h new file mode 100644 index 00000000000..05cf60fed73 --- /dev/null +++ b/third_party/imgui/examples/libs/emscripten/emscripten_mainloop_stub.h @@ -0,0 +1,37 @@ +// What does this file solves? +// - Since Dear ImGui 1.00 we took pride that most of our examples applications had their entire +// main-loop inside the main() function. That's because: +// - It makes the examples easier to read, keeping the code sequential. +// - It permit the use of local variables, making it easier to try things and perform quick +// changes when someone needs to quickly test something (vs having to structure the example +// in order to pass data around). This is very important because people use those examples +// to craft easy-to-past repro when they want to discuss features or report issues. +// - It conveys at a glance that this is a no-BS framework, it won't take your main loop away from you. +// - It is generally nice and elegant. +// - However, comes Emscripten... it is a wonderful and magical tech but it requires a "main loop" function. +// - Only some of our examples would run on Emscripten. Typically the ones rendering with GL or WGPU ones. +// - I tried to refactor those examples but felt it was problematic that other examples didn't follow the +// same layout. Why would the SDL+GL example be structured one way and the SGL+DX11 be structured differently? +// Especially as we are trying hard to convey that using a Dear ImGui backend in an *existing application* +// should requires only a few dozens lines of code, and this should be consistent and symmetrical for all backends. +// - So the next logical step was to refactor all examples to follow that layout of using a "main loop" function. +// This worked, but it made us lose all the nice things we had... + +// Since only about 3 examples really need to run with Emscripten, here's our solution: +// - Use some weird macros and capturing lambda to turn a loop in main() into a function. +// - Hide all that crap in this file so it doesn't make our examples unusually ugly. +// As a stance and principle of Dear ImGui development we don't use C++ headers and we don't +// want to suggest to the newcomer that we would ever use C++ headers as this would affect +// the initial judgment of many of our target audience. +// - Technique is based on this idea: https://github.com/ocornut/imgui/pull/2492/ +#ifdef __EMSCRIPTEN__ +#include +#include +static std::function MainLoopForEmscriptenP; +static void MainLoopForEmscripten() { MainLoopForEmscriptenP(); } +#define EMSCRIPTEN_MAINLOOP_BEGIN MainLoopForEmscriptenP = [&]() +#define EMSCRIPTEN_MAINLOOP_END ; emscripten_set_main_loop(MainLoopForEmscripten, 0, true) +#else +#define EMSCRIPTEN_MAINLOOP_BEGIN +#define EMSCRIPTEN_MAINLOOP_END +#endif diff --git a/third_party/imgui/examples/example_emscripten_opengl3/shell_minimal.html b/third_party/imgui/examples/libs/emscripten/shell_minimal.html similarity index 95% rename from third_party/imgui/examples/example_emscripten_opengl3/shell_minimal.html rename to third_party/imgui/examples/libs/emscripten/shell_minimal.html index 514385d7cf5..bcf626261f5 100644 --- a/third_party/imgui/examples/example_emscripten_opengl3/shell_minimal.html +++ b/third_party/imgui/examples/libs/emscripten/shell_minimal.html @@ -6,6 +6,7 @@ Dear ImGui Emscripten example